1use axum::extract::{Path, Query, State};
15use axum::http::{header, StatusCode};
16use axum::response::{IntoResponse, Response};
17use axum::{Extension, Json};
18use serde::Deserialize;
19use serde_json::{json, Value};
20
21use super::http_viewer::{agent_hidden, not_found, FeedSource, ViewerCaller};
22use crate::backend::attachments::prompt::{BLOCK_CLOSE, BLOCK_OPEN};
23use crate::backend::attachments::{self, store, Kind};
24use crate::backend::viewer::feed;
25use crate::server::AppState;
26
27pub(crate) const MAX_ATTACHMENT_BYTES: u64 = attachments::process::SEND_MAX_BYTES;
30
31#[derive(Deserialize)]
32pub(crate) struct AttachmentQuery {
33 at: String,
34}
35
36fn refuse(status: StatusCode, reason: &str, error: &str) -> Response {
37 (status, Json(json!({ "error": error, "reason": reason }))).into_response()
38}
39
40pub(crate) fn named_attachment(line: &str, id: &str) -> Option<Option<String>> {
45 if !line.contains(id) || !line.contains(BLOCK_OPEN) {
46 return None;
47 }
48 let record = serde_json::from_str::<Value>(line.trim_end()).ok()?;
49 if record["type"] != "user" {
50 return None;
51 }
52 let content = &record["message"]["content"];
53 let texts: Vec<&str> = match content {
54 Value::String(text) => vec![text.as_str()],
55 Value::Array(blocks) => blocks.iter().filter(|b| b["type"] == "text").filter_map(|b| b["text"].as_str()).collect(),
56 _ => Vec::new(),
57 };
58 let mut named = None;
61 for list in texts.into_iter().flat_map(attachment_lists) {
62 let mut hits = list.match_indices(id).peekable();
63 if hits.peek().is_none() {
64 continue;
65 }
66 let fp = hits.find_map(|(at, _)| {
67 list[at + id.len()..].strip_prefix('.').and_then(|rest| rest.split('.').next()).filter(|fp| is_fingerprint(fp))
68 });
69 named = Some(fp.map(str::to_string));
70 }
71 named
72}
73
74fn is_fingerprint(fp: &str) -> bool {
76 let digits = |s: &str, max: usize| !s.is_empty() && s.len() <= max && s.bytes().all(|b| b.is_ascii_digit());
77 fp.strip_prefix('v').and_then(|rest| rest.split_once("-e")).is_some_and(|(v, e)| digits(v, 4) && digits(e, 6))
78}
79
80fn attachment_lists(text: &str) -> impl Iterator<Item = &str> {
84 let mut rest = text;
85 std::iter::from_fn(move || {
86 let open = rest.find(BLOCK_OPEN)?;
87 let body = &rest[open + BLOCK_OPEN.len()..];
88 let end = [body.find(BLOCK_CLOSE), body.find(BLOCK_OPEN)].into_iter().flatten().min().unwrap_or(body.len());
89 rest = &body[end..];
90 Some(&body[..end])
91 })
92}
93
94fn served_as(meta: &store::StoredMeta) -> Option<(Kind, String)> {
97 if meta.is_image() {
98 return meta.send_mime.starts_with("image/").then(|| (Kind::Send, meta.send_mime.clone()));
99 }
100 let text = "text/plain; charset=utf-8".to_string();
101 match meta.kind.as_str() {
102 "text" => Some((Kind::Original, text)),
103 _ if meta.text_ext.is_some() => Some((Kind::Text, text)),
104 _ => None,
105 }
106}
107
108pub(crate) async fn handle_viewer_attachment(
113 State(state): State<AppState>,
114 Extension(caller): Extension<ViewerCaller>,
115 Path((name, id)): Path<(String, String)>,
116 Query(q): Query<AttachmentQuery>,
117 uri: axum::http::Uri,
118 headers: axum::http::HeaderMap,
119) -> Response {
120 let Some(agent) = state.reactive_handler.get_agent(&name) else {
121 return not_found();
122 };
123 if agent_hidden(&state, &agent.block_id) || !store::is_valid_id(&id) {
124 return not_found();
125 }
126 let signed_path = uri.path_and_query().map_or(uri.path(), |p| p.as_str());
127 if let Some(refused) = super::http_viewer_computers::refuse_unsigned_open(&state, &caller.device_id, signed_path, &headers) {
128 return refused;
129 }
130 let Some((gen, line)) = feed::parse_event_id(&q.at) else {
131 return refuse(StatusCode::BAD_REQUEST, "bad_cursor", "at is <gen>:<line>");
132 };
133 let source = FeedSource::of(&state, &agent.block_id);
134 match source.position().await {
135 Some((_, current, _)) if current != gen => return refuse(StatusCode::CONFLICT, "gen_changed", "the conversation was replaced since"),
136 None => return refuse(StatusCode::CONFLICT, "gen_changed", "the conversation was replaced since"),
137 Some(_) => {}
138 }
139 let named = match source.read(line, 1, &gen, false).await {
140 Some(result) => result.lines.first().and_then(|l| named_attachment(l, &id)),
141 None => return refuse(StatusCode::CONFLICT, "gen_changed", "the conversation was replaced since"),
142 };
143 let Some(named_fp) = named else {
144 return refuse(StatusCode::NOT_FOUND, "not_named", "that message doesn't name this attachment");
145 };
146 let service = attachments::init(state.broker.clone(), state.config_watcher.clone());
147 let fp = named_fp.unwrap_or_else(|| store::fingerprint(service.limits().send_max_edge));
148 serve(service.store(), &fp, &id).await
149}
150
151async fn serve(store: &store::Store, fp: &str, id: &str) -> Response {
153 let Some(meta) = store.meta(id, fp) else {
154 return refuse(StatusCode::NOT_FOUND, "gone", "this attachment is no longer kept on its computer");
155 };
156 let Some((kind, mime)) = served_as(&meta) else {
157 return refuse(StatusCode::UNSUPPORTED_MEDIA_TYPE, "not_viewable", "only pictures and text are shown on another computer");
158 };
159 let Some((path, _)) = store.file(id, fp, kind) else {
160 return refuse(StatusCode::NOT_FOUND, "gone", "this attachment is no longer kept on its computer");
161 };
162 let bytes = tokio::task::spawn_blocking(move || -> std::io::Result<Option<Vec<u8>>> {
163 if std::fs::metadata(&path)?.len() > MAX_ATTACHMENT_BYTES {
164 return Ok(None);
165 }
166 std::fs::read(&path).map(Some)
167 })
168 .await;
169 match bytes {
170 Ok(Ok(Some(bytes))) if bytes.len() as u64 <= MAX_ATTACHMENT_BYTES => (
171 [
172 (header::CONTENT_TYPE, mime),
173 (header::CACHE_CONTROL, "no-store".to_string()),
174 (header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()),
175 ],
176 bytes,
177 )
178 .into_response(),
179 Ok(Ok(_)) => refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large", "this attachment is larger than 5 MiB"),
180 _ => refuse(StatusCode::NOT_FOUND, "gone", "this attachment is no longer kept on its computer"),
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 const ID: &str = "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00";
189
190 fn user(content: Value) -> String {
191 json!({ "type": "user", "message": { "role": "user", "content": content } }).to_string()
192 }
193
194 fn names(line: &str, id: &str) -> bool {
195 named_attachment(line, id).is_some()
196 }
197
198 #[test]
199 fn the_fingerprint_is_the_one_the_list_names_and_only_in_its_shape() {
200 let line = |path: &str| user(json!(format!("{BLOCK_OPEN}\n1. a.png — /x/ab/{path}\n{BLOCK_CLOSE}")));
201 assert_eq!(named_attachment(&line(&format!("{ID}.v1-e1000.send.png")), ID), Some(Some("v1-e1000".into())));
202 assert_eq!(named_attachment(&line(&format!("{ID}.txt")), ID), Some(None), "a path with none: today's is used");
203 for bad in ["v1-e", "v-e2000", "v1-e2000x", "v1e2000", "v1-e1234567", "v1-e2000/..\\x"] {
204 assert_eq!(named_attachment(&line(&format!("{ID}.{bad}.send.png")), ID), Some(None), "{bad}");
205 }
206 let quoted_then_real = format!(
207 "{BLOCK_OPEN}\n1. a.png — {ID}.png\n{BLOCK_CLOSE}\n{BLOCK_OPEN}\n1. a.png — {ID}.v1-e800.send.png\n{BLOCK_CLOSE}"
208 );
209 assert_eq!(named_attachment(&user(json!(quoted_then_real)), ID), Some(Some("v1-e800".into())));
210 let quoted_older_copy = format!(
211 "{BLOCK_OPEN}\n1. a.png — {ID}.v1-e2000.send.png\n{BLOCK_CLOSE}\n{BLOCK_OPEN}\n1. a.png — {ID}.v1-e800.send.png\n{BLOCK_CLOSE}"
212 );
213 assert_eq!(named_attachment(&user(json!(quoted_older_copy)), ID), Some(Some("v1-e800".into())), "the appended list's copy");
214 }
215
216 #[tokio::test]
217 async fn the_copy_under_the_fingerprint_the_message_named_is_served() {
218 let dir = tempfile::tempdir().unwrap();
219 let s = stored(dir.path(), ID, meta("image", "image/png", None), b"the original", Some(b"the copy it was sent"));
220 let (status, _, bytes) = body_of(serve(&s, FP, ID).await).await;
221 assert_eq!((status, bytes.as_slice()), (StatusCode::OK, &b"the copy it was sent"[..]));
222 assert_eq!(body_of(serve(&s, "v1-e4000", ID).await).await.0, StatusCode::NOT_FOUND, "today's edge has no copy");
223 }
224
225 #[test]
226 fn only_a_persons_attachment_list_names_an_attachment() {
227 let list = format!("look\n{BLOCK_OPEN}\n1. a.png — {ID}.v1-e2000.send.png\n{BLOCK_CLOSE}");
228 assert!(names(&user(json!(list)), ID));
229 assert!(names(&user(json!([{ "type": "text", "text": list }])), ID));
230 assert!(!names(&user(json!(list)), &ID.replace('c', "d")), "another id");
231 let outside = format!("{ID}.png and then {BLOCK_OPEN}\n1. b.png — other.png\n{BLOCK_CLOSE}");
232 assert!(!names(&user(json!(outside)), ID), "the id outside the list");
233 let tool = user(json!([{ "type": "tool_result", "tool_use_id": "t1", "content": list }]));
234 assert!(!names(&tool, ID), "a tool's output");
235 let assistant = json!({ "type": "assistant", "message": { "content": [{ "type": "text", "text": list }] } }).to_string();
236 assert!(!names(&assistant, ID), "the agent's words");
237 assert!(!names("not json", ID));
238 }
239
240 #[test]
241 fn every_list_in_a_message_is_looked_at_and_an_open_quoted_one_ends_at_the_next() {
242 let real = format!("{BLOCK_OPEN}\n1. a.png — {ID}.v1-e2000.send.png\n{BLOCK_CLOSE}");
243 let quoted = format!("as before:\n{BLOCK_OPEN}\n1. old.png — other.png\n{BLOCK_CLOSE}\nnow this\n{real}");
244 assert!(names(&user(json!(quoted)), ID), "the list after a quoted one");
245 let left_open = format!("{BLOCK_OPEN}\n1. old.png — other.png\nsee {ID}\n{BLOCK_OPEN}\n1. b.png — b.png\n{BLOCK_CLOSE}");
246 assert!(names(&user(json!(left_open.clone())), ID), "inside the open list, before the next");
247 let words_after = format!("{BLOCK_OPEN}\n1. old.png — other.png\n{BLOCK_OPEN}\n1. b.png — b.png\n{BLOCK_CLOSE}\nsee {ID}");
248 assert!(!names(&user(json!(words_after)), ID), "the person's words after the last list");
249 let lists: Vec<&str> = attachment_lists(&left_open).collect();
250 assert_eq!(lists.len(), 2);
251 }
252
253 fn meta(kind: &str, send_mime: &str, text_ext: Option<&str>) -> store::StoredMeta {
254 serde_json::from_value(json!({
255 "v": 1, "mime": "x", "ext": "x", "bytes": 1, "width": 0, "height": 0, "send_mime": send_mime, "send_ext": "png",
256 "send_bytes": 1, "send_width": 0, "send_height": 0, "thumb_mime": "", "thumb_ext": "", "kind": kind,
257 "text_ext": text_ext,
258 }))
259 .unwrap()
260 }
261
262 #[test]
263 fn a_device_gets_pictures_and_text_and_nothing_else() {
264 assert_eq!(served_as(&meta("image", "image/png", None)).map(|s| s.0), Some(Kind::Send));
265 assert_eq!(served_as(&meta("text", "", None)).map(|s| s.0), Some(Kind::Original));
266 assert_eq!(served_as(&meta("pdf", "", Some("txt"))).map(|s| s.0), Some(Kind::Text));
267 for (kind, text) in [("pdf", None), ("svg", None), ("archive", None), ("video", None), ("other", None)] {
268 assert_eq!(served_as(&meta(kind, "", text)), None, "{kind}");
269 }
270 assert_eq!(served_as(&meta("text", "", None)).unwrap().1, "text/plain; charset=utf-8");
271 }
272
273 const FP: &str = "v1-e2000";
274
275 fn stored(dir: &std::path::Path, id: &str, mut meta: store::StoredMeta, original: &[u8], send: Option<&[u8]>) -> store::Store {
277 let at = |folder: &str| dir.join(folder).join(&id[..2]);
278 std::fs::create_dir_all(at("blobs")).unwrap();
279 std::fs::create_dir_all(at("derived")).unwrap();
280 meta.ext = "bin".into();
281 std::fs::write(at("blobs").join(format!("{id}.bin")), original).unwrap();
282 if let Some(send) = send {
283 std::fs::write(at("derived").join(format!("{id}.{FP}.send.png")), send).unwrap();
284 }
285 std::fs::write(at("derived").join(format!("{id}.{FP}.json")), serde_json::to_string(&meta).unwrap()).unwrap();
286 store::Store::new(dir.to_path_buf())
287 }
288
289 async fn body_of(resp: Response) -> (StatusCode, Option<String>, Vec<u8>) {
290 let status = resp.status();
291 let mime = resp.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).map(str::to_string);
292 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap().to_vec();
293 (status, mime, bytes)
294 }
295
296 #[tokio::test]
297 async fn a_picture_is_its_send_copy_and_a_text_file_itself() {
298 let dir = tempfile::tempdir().unwrap();
299 let s = stored(dir.path(), ID, meta("image", "image/png", None), b"the original", Some(b"the send copy"));
300 let (status, mime, bytes) = body_of(serve(&s, FP, ID).await).await;
301 assert_eq!((status, mime.as_deref(), bytes.as_slice()), (StatusCode::OK, Some("image/png"), &b"the send copy"[..]));
302
303 let text_id = ID.replace('c', "a");
304 let s = stored(dir.path(), &text_id, meta("text", "", None), b"<script>hi</script>", None);
305 let resp = serve(&s, FP, &text_id).await;
306 assert_eq!(resp.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
307 let (_, mime, bytes) = body_of(resp).await;
308 assert_eq!((mime.as_deref(), bytes.as_slice()), (Some("text/plain; charset=utf-8"), &b"<script>hi</script>"[..]));
309 }
310
311 #[tokio::test]
312 async fn another_kind_a_large_file_and_one_not_kept_are_refused() {
313 let dir = tempfile::tempdir().unwrap();
314 let s = stored(dir.path(), ID, meta("archive", "", None), b"PK", None);
315 assert_eq!(body_of(serve(&s, FP, ID).await).await.0, StatusCode::UNSUPPORTED_MEDIA_TYPE);
316 let big_id = ID.replace('c', "b");
317 let big = vec![b'x'; MAX_ATTACHMENT_BYTES as usize + 1];
318 let s = stored(dir.path(), &big_id, meta("text", "", None), &big, None);
319 assert_eq!(body_of(serve(&s, FP, &big_id).await).await.0, StatusCode::PAYLOAD_TOO_LARGE);
320 assert_eq!(body_of(serve(&s, FP, &ID.replace('c', "d")).await).await.0, StatusCode::NOT_FOUND);
321 }
322}