use std::collections::HashSet;
use std::sync::{Arc, LazyLock};
use atproto_extras::link_card::extract_link_card;
use atproto_extras::{
FacetAllowList, FacetLimits, parse_facets_allowed, parse_mention_spans, parse_tags, parse_urls,
};
use atproto_identity::traits::IdentityResolver;
use atproto_lexicon::validation::{BaseCatalog, ValidateFlags, validate_record};
use atproto_record::lexicon::app::bsky::richtext::facet::{Facet, FacetFeature};
use atpxrpc::accounts;
use futures::StreamExt;
use reqwest::Url;
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use serde_json::{Map, Value};
use crate::context::ServerContext;
use crate::errors::ToolError;
use crate::host_policy;
use crate::mime;
use crate::proto::serve::RequestCtx;
use crate::tools::blob::{Uploaded, put_blob};
use crate::tools::{tool_error, tool_structured};
pub const POST_NSID: &str = "app.bsky.feed.post";
pub const EXTERNAL_NSID: &str = "app.bsky.embed.external";
pub const MAX_PAGE_BYTES: u64 = 1_048_576;
pub const MAX_THUMB_BYTES: u64 = 1_000_000;
pub const MAX_LANGS: usize = 3;
pub const DEFAULT_LANGS: &[&str] = &["en"];
pub const GALLERY_NSID: &str = "app.bsky.embed.gallery";
pub const IMAGES_NSID: &str = "app.bsky.embed.images";
pub const MAX_GALLERY_ITEMS: usize = 10;
pub const MAX_IMAGES_ITEMS: usize = 4;
pub const MAX_MEDIA_IMAGE_BYTES: u64 = 2_000_000;
const LEXICONS: &[(&str, &str)] = &[
(
"app.bsky.feed.post",
include_str!("../../lexicons/app/bsky/feed/post.json"),
),
(
"app.bsky.embed.external",
include_str!("../../lexicons/app/bsky/embed/external.json"),
),
(
"app.bsky.embed.gallery",
include_str!("../../lexicons/app/bsky/embed/gallery.json"),
),
(
"app.bsky.embed.images",
include_str!("../../lexicons/app/bsky/embed/images.json"),
),
(
"app.bsky.embed.defs",
include_str!("../../lexicons/app/bsky/embed/defs.json"),
),
(
"app.bsky.richtext.facet",
include_str!("../../lexicons/app/bsky/richtext/facet.json"),
),
(
"com.atproto.repo.strongRef",
include_str!("../../lexicons/com/atproto/repo/strongRef.json"),
),
(
"com.atproto.label.defs",
include_str!("../../lexicons/com/atproto/label/defs.json"),
),
];
static CATALOG: LazyLock<BaseCatalog> = LazyLock::new(|| {
let mut catalog = BaseCatalog::new();
for (nsid, json) in LEXICONS {
if let Err(error) = catalog.add_schema_json(json) {
tracing::error!(nsid = %nsid, error = %error, "A bundled lexicon does not parse.");
}
}
catalog
});
pub async fn generate_bsky_post(
ctx: &Arc<ServerContext>,
rctx: &mut RequestCtx,
arguments: Value,
) -> Value {
let cancel = rctx.cancel.clone();
let result = tokio::select! {
biased;
() = cancel.cancelled() => Err(ToolError::PostGenerationFailed {
reason: "cancelled".to_string(),
}),
result = generate(ctx, rctx, arguments) => result,
};
match result {
Ok(value) => value,
Err(error) => {
tracing::error!(error = %error, "Post generation failed.");
tool_error(&error.to_string())
}
}
}
struct PostRequest {
text: String,
allow: FacetAllowList,
embed_external: Option<(String, Url)>,
media: Option<Media>,
langs: Vec<String>,
auth_handle: Option<String>,
shorten_links: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MediaKind {
Gallery,
Images,
}
impl MediaKind {
fn argument(self) -> &'static str {
match self {
Self::Gallery => "gallery",
Self::Images => "images",
}
}
fn max_items(self) -> usize {
match self {
Self::Gallery => MAX_GALLERY_ITEMS,
Self::Images => MAX_IMAGES_ITEMS,
}
}
fn nsid(self) -> &'static str {
match self {
Self::Gallery => GALLERY_NSID,
Self::Images => IMAGES_NSID,
}
}
}
enum ImageSource {
Path(String),
Url(Url),
}
struct ImageItem {
source: ImageSource,
alt: String,
label: String,
}
struct Media {
kind: MediaKind,
items: Vec<ImageItem>,
}
fn invalid(reason: impl Into<String>) -> ToolError {
ToolError::PostGenerationFailed {
reason: reason.into(),
}
}
fn optional_string(arguments: &Value, name: &str) -> Result<Option<String>, ToolError> {
match arguments.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(invalid(format!("the '{name}' argument must be a string"))),
}
}
fn optional_strings(arguments: &Value, name: &str) -> Result<Option<Vec<String>>, ToolError> {
let refused = || invalid(format!("the '{name}' argument must be an array of strings"));
match arguments.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::Array(items)) => items
.iter()
.map(|item| item.as_str().map(str::to_string).ok_or_else(refused))
.collect::<Result<Vec<_>, _>>()
.map(Some),
Some(_) => Err(refused()),
}
}
fn read_media(arguments: &Value) -> Result<Option<Media>, ToolError> {
let present = |name: &str| !matches!(arguments.get(name), None | Some(Value::Null));
let kind = match (present("gallery"), present("images")) {
(true, true) => {
return Err(invalid(
"give 'gallery' or 'images', not both: a post has one embed",
));
}
(true, false) => MediaKind::Gallery,
(false, true) => MediaKind::Images,
(false, false) => return Ok(None),
};
let name = kind.argument();
let Some(Value::Array(list)) = arguments.get(name) else {
return Err(invalid(format!(
"the '{name}' argument must be an array of images"
)));
};
if list.is_empty() || list.len() > kind.max_items() {
return Err(invalid(format!(
"'{name}' takes 1 to {} images, not {}",
kind.max_items(),
list.len()
)));
}
let items = list
.iter()
.enumerate()
.map(|(index, item)| {
let number = index + 1;
let Value::Object(fields) = item else {
return Err(invalid(format!(
"{name} item {number} must be an object with 'path' or 'url'"
)));
};
if let Some(unknown) = fields
.keys()
.find(|key| !matches!(key.as_str(), "path" | "url" | "alt"))
{
return Err(invalid(format!(
"{name} item {number} has an unknown field '{unknown}'; an image is \
{{\"path\"}} or {{\"url\"}}, with an optional \"alt\""
)));
}
let text = |field: &str| match fields.get(field) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(invalid(format!(
"{name} item {number}'s '{field}' must be a string"
))),
};
let source = match (text("path")?, text("url")?) {
(Some(path), None) => ImageSource::Path(path),
(None, Some(raw)) => {
let url = Url::parse(raw.trim()).map_err(|error| {
invalid(format!(
"{name} item {number}'s 'url' must be an absolute URL ({raw}): {error}"
))
})?;
if !matches!(url.scheme(), "http" | "https") {
return Err(invalid(format!(
"{name} item {number}'s 'url' must be http or https, not {}",
url.scheme()
)));
}
ImageSource::Url(url)
}
(Some(_), Some(_)) => {
return Err(invalid(format!(
"{name} item {number} gives both 'path' and 'url'; give one"
)));
}
(None, None) => {
return Err(invalid(format!(
"{name} item {number} needs a 'path' or a 'url'"
)));
}
};
let label = match &source {
ImageSource::Path(path) => format!("{name} item {number} ({path})"),
ImageSource::Url(url) => format!("{name} item {number} ({url})"),
};
Ok(ImageItem {
source,
alt: text("alt")?.unwrap_or_default(),
label,
})
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Some(Media { kind, items }))
}
fn read_arguments(arguments: &Value) -> Result<PostRequest, ToolError> {
let text = match arguments.get("text") {
Some(Value::String(text)) => text.clone(),
_ => return Err(invalid("the 'text' argument must be a string")),
};
let allow = FacetAllowList {
mentions: optional_strings(arguments, "mention_facet_allow")?.unwrap_or_default(),
tags: optional_strings(arguments, "tag_facet_allow")?.unwrap_or_default(),
links: optional_strings(arguments, "link_facet_allow")?.unwrap_or_default(),
};
let embed_external = match optional_string(arguments, "embed_external")? {
None => None,
Some(raw) => {
let raw = raw.trim().to_string();
let url = Url::parse(&raw).map_err(|error| {
invalid(format!(
"'embed_external' must be an absolute URL ({raw}): {error}"
))
})?;
if !matches!(url.scheme(), "http" | "https") {
return Err(invalid(format!(
"'embed_external' must be an http or https URL, not {}",
url.scheme()
)));
}
Some((raw, url))
}
};
let media = read_media(arguments)?;
if let (Some(media), Some(_)) = (&media, &embed_external) {
return Err(invalid(format!(
"give one of '{}' or 'embed_external', not both: a post has one embed",
media.kind.argument()
)));
}
let shorten_links = match arguments.get("shorten_links") {
None | Some(Value::Null) => false,
Some(Value::Bool(value)) => *value,
Some(_) => return Err(invalid("the 'shorten_links' argument must be a boolean")),
};
let langs = match optional_strings(arguments, "langs")? {
None => DEFAULT_LANGS
.iter()
.map(|lang| (*lang).to_string())
.collect(),
Some(langs) if langs.len() > MAX_LANGS => {
return Err(invalid(format!(
"'langs' has {} entries; a post has at most {MAX_LANGS}",
langs.len()
)));
}
Some(langs) => langs,
};
Ok(PostRequest {
text,
allow,
embed_external,
media,
langs,
auth_handle: optional_string(arguments, "auth_handle")?,
shorten_links,
})
}
async fn generate(
ctx: &Arc<ServerContext>,
rctx: &mut RequestCtx,
arguments: Value,
) -> Result<Value, ToolError> {
let request = read_arguments(&arguments)?;
if let (Some(media), None) = (&request.media, &request.auth_handle) {
return Err(invalid(format!(
"'{}' needs auth_handle: its images are uploaded to that account's PDS",
media.kind.argument()
)));
}
let embeds = request.embed_external.is_some() || request.media.is_some();
let mut account =
match (embeds, &request.auth_handle) {
(true, Some(handle)) => Some(accounts::load_account(handle).map_err(|error| {
invalid(format!("the account '{handle}' cannot be used: {error}"))
})?),
_ => None,
};
let (facets, mut notes) =
facets_for(&request.text, &request.allow, ctx.resolver.as_ref()).await;
let (text, facets) = if request.shorten_links {
shorten_links(&request.text, &facets)
} else {
(request.text.clone(), facets)
};
let mut record = Map::new();
record.insert("$type".to_string(), Value::from(POST_NSID));
record.insert("text".to_string(), Value::from(text));
if !facets.is_empty() {
let facets = serde_json::to_value(&facets)
.map_err(|error| invalid(format!("the facets could not be serialized: {error}")))?;
record.insert("facets".to_string(), facets);
}
if !request.langs.is_empty() {
record.insert("langs".to_string(), Value::from(request.langs.clone()));
}
record.insert(
"createdAt".to_string(),
Value::from(atproto_record::datetime::Datetime::now().into_string()),
);
let validate = |record: &Value| {
validate_record(POST_NSID, record, &*CATALOG, ValidateFlags::empty()).map_err(|error| {
invalid(format!(
"the record does not validate against {POST_NSID}: {error}"
))
})
};
validate(&Value::Object(record.clone()))?;
let mut card_summary = None;
let mut thumbnail = None;
let mut uploaded = Vec::new();
if let Some((raw, url)) = &request.embed_external {
let card = link_card(ctx, rctx, raw, url, account.as_mut(), &mut notes).await?;
card_summary = Some(format!(
", and a link card for {raw} titled \"{}\"",
card.embed["external"]["title"].as_str().unwrap_or_default()
));
thumbnail = card.thumbnail;
record.insert("embed".to_string(), card.embed);
} else if let Some(media) = &request.media {
let Some(account) = account.as_mut() else {
return Err(invalid("images need a stored account to upload them to"));
};
let embed = media_embed(ctx, rctx, media, account, &mut notes).await?;
card_summary = Some(format!(
", and an {} of {} image{} uploaded to {}'s PDS",
media.kind.nsid(),
embed.uploaded.len(),
if embed.uploaded.len() == 1 { "" } else { "s" },
account.handle
));
uploaded = embed.uploaded;
record.insert("embed".to_string(), embed.value);
}
let record = Value::Object(record);
validate(&record)?;
let count = record["facets"].as_array().map_or(0, Vec::len);
let mut summary = format!(
"Generated an {POST_NSID} record with {count} facet{}",
if count == 1 { "" } else { "s" }
);
if let Some(card) = card_summary {
summary.push_str(&card);
}
let publisher = match (&thumbnail, &account) {
(Some(uploaded), Some(account)) => {
summary.push_str(&format!(
", with a thumbnail uploaded to {}'s PDS (blob {})",
account.handle, uploaded.cid
));
format!(
"{}, the account its thumbnail was uploaded to",
account.handle
)
}
(None, Some(account)) if !uploaded.is_empty() => {
format!(
"{}, the account its images were uploaded to",
account.handle
)
}
_ => "the account that should post it".to_string(),
};
summary.push_str(&format!(
". It is not published: create it with invoke_xrpc com.atproto.repo.createRecord \
(collection {POST_NSID}) as {publisher}."
));
for note in ¬es {
summary.push_str(&format!(" Note: {note}."));
}
let mut structured = serde_json::json!({ "record": record, "notes": notes });
let described = |uploaded: &Uploaded| {
serde_json::json!({
"cid": uploaded.cid,
"uri": uploaded.uri,
"verified": uploaded.verified,
})
};
if let Some(uploaded) = &thumbnail {
structured["thumbnail"] = described(uploaded);
}
if !uploaded.is_empty() {
structured["uploaded"] = Value::from(uploaded.iter().map(described).collect::<Vec<_>>());
}
Ok(tool_structured(&summary, structured, Vec::new()))
}
async fn facets_for(
text: &str,
allow: &FacetAllowList,
resolver: &dyn IdentityResolver,
) -> (Vec<Facet>, Vec<String>) {
let limits = FacetLimits::default();
let facets = parse_facets_allowed(text, resolver, &limits, allow)
.await
.unwrap_or_default();
let mut notes = Vec::new();
let mentioned: HashSet<usize> = facets
.iter()
.filter(|facet| matches!(facet.features.first(), Some(FacetFeature::Mention(_))))
.map(|facet| facet.index.byte_start)
.collect();
let spans = parse_mention_spans(text);
let admitted = spans
.iter()
.filter(|span| allow.admits_mention(&span.handle))
.count();
for span in &spans {
if !allow.admits_mention(&span.handle) {
notes.push(format!(
"@{} has no facet: mention_facet_allow leaves it out",
span.handle
));
} else if !mentioned.contains(&span.index.byte_start) {
notes.push(if admitted > limits.mentions_max {
format!(
"@{} has no facet: it did not resolve to a DID, or the post has more than {} mentions",
span.handle, limits.mentions_max
)
} else {
format!("@{} has no facet: it did not resolve to a DID", span.handle)
});
}
}
let links = parse_urls(text);
for facet in &links {
if let Some(FacetFeature::Link(link)) = facet.features.first()
&& !allow.admits_link(&link.uri)
{
notes.push(format!(
"{} has no facet: link_facet_allow leaves it out",
link.uri
));
}
}
let tags = parse_tags(text);
for facet in &tags {
if let Some(FacetFeature::Tag(tag)) = facet.features.first()
&& !allow.admits_tag(&tag.tag)
{
notes.push(format!(
"#{} has no facet: tag_facet_allow leaves it out",
tag.tag
));
}
}
let kept = |kind: fn(&FacetFeature) -> bool| {
facets
.iter()
.filter(|facet| facet.features.first().is_some_and(kind))
.count()
};
let admitted_links = links
.iter()
.filter(|facet| match facet.features.first() {
Some(FacetFeature::Link(link)) => allow.admits_link(&link.uri),
_ => false,
})
.count();
let admitted_tags = tags
.iter()
.filter(|facet| match facet.features.first() {
Some(FacetFeature::Tag(tag)) => allow.admits_tag(&tag.tag),
_ => false,
})
.count();
for (noun, admitted, kept) in [
(
"links",
admitted_links,
kept(|f| matches!(f, FacetFeature::Link(_))),
),
(
"tags",
admitted_tags,
kept(|f| matches!(f, FacetFeature::Tag(_))),
),
] {
if kept < admitted {
notes.push(format!(
"{} of the post's {noun} have no facet: a post gets at most {} links, {} tags and {} facets in all",
admitted - kept,
limits.links_max,
limits.tags_max,
limits.max
));
}
}
(facets, notes)
}
struct Card {
embed: Value,
thumbnail: Option<Uploaded>,
}
async fn link_card(
ctx: &Arc<ServerContext>,
rctx: &mut RequestCtx,
raw: &str,
url: &Url,
account: Option<&mut accounts::Account>,
notes: &mut Vec<String>,
) -> Result<Card, ToolError> {
let failed = |reason: String| ToolError::LinkCardFailed {
url: raw.to_string(),
reason,
};
check_url(ctx, url)?;
let page = fetch(
&ctx.web_client,
url,
"text/html, application/xhtml+xml",
MAX_PAGE_BYTES,
Overflow::Truncate,
)
.await
.map_err(|error| failed(error.to_string()))?;
if !is_html(page.content_type.as_deref(), &page.body) {
return Err(failed(format!(
"the page is served as {}, not HTML",
page.content_type.as_deref().unwrap_or("an unnamed type")
)));
}
let html = decode(&page.body, page.content_type.as_deref());
let found = extract_link_card(&html, &page.url);
let mut external = serde_json::json!({
"uri": raw,
"title": found.title,
"description": found.description,
});
let thumbnail = match (found.image, account) {
(None, _) => {
notes.push("the card has no thumbnail: the page names no image".to_string());
None
}
(Some(image), None) => {
notes.push(format!(
"the card has no thumbnail: pass auth_handle to upload the page's image ({image}) to that account"
));
None
}
(Some(image), Some(account)) => match thumbnail_bytes(ctx, &image).await {
Err(reason) => {
notes.push(format!("the card has no thumbnail: {reason}"));
None
}
Ok(thumb) => {
if let Some(note) = thumb.note {
notes.push(note);
}
let uploaded = put_blob(ctx, rctx, account, thumb.data, &thumb.mime_type).await?;
external["thumb"] = uploaded.blob.clone();
Some(uploaded)
}
},
};
Ok(Card {
embed: serde_json::json!({ "$type": EXTERNAL_NSID, "external": external }),
thumbnail,
})
}
struct Thumb {
data: Vec<u8>,
mime_type: String,
note: Option<String>,
}
async fn thumbnail_bytes(ctx: &ServerContext, image: &Url) -> Result<Thumb, String> {
let label = format!("the page's image ({image})");
let fetched = fetch_image(ctx, image, &label).await?;
prepare_image(
ctx.limits.preserve_exif,
fetched.body,
fetched.content_type.as_deref(),
MAX_THUMB_BYTES,
&label,
)
.await
}
async fn fetch_image(ctx: &ServerContext, url: &Url, label: &str) -> Result<Fetched, String> {
check_url(ctx, url).map_err(|error| format!("{label} is refused: {error}"))?;
let ceiling = ctx.limits.blob_max_download_bytes;
fetch(&ctx.web_client, url, "image/*", ceiling, Overflow::Refuse)
.await
.map_err(|error| match error {
FetchError::TooLarge => format!(
"{label} is over {ceiling} bytes, atpmcp's download ceiling \
(ATPMCP_BLOB_MAX_DOWNLOAD_BYTES)"
),
FetchError::Failed(reason) => format!("{label} could not be fetched: {reason}"),
})
}
async fn prepare_image(
preserve: bool,
body: Vec<u8>,
served: Option<&str>,
limit_bytes: u64,
label: &str,
) -> Result<Thumb, String> {
let sniffed = match mime::sniff(&body) {
Some(sniffed) if mime::is_image(sniffed) => sniffed,
_ => {
return Err(format!(
"{label} is not a recognised image{}",
served
.map(|served| format!(" (served as {served})"))
.unwrap_or_default()
));
}
};
let size = body.len();
let limit = usize::try_from(limit_bytes).unwrap_or(usize::MAX);
let mut turned = false;
if size <= limit {
if preserve {
return Ok(Thumb {
data: body,
mime_type: sniffed.to_string(),
note: None,
});
}
let stripped = crate::image_metadata::strip(&body).map_err(|reason| {
format!("{label}: {reason}; with ATPMCP_PRESERVE_EXIF=1 it would be used as it is")
})?;
if !stripped.needs_turning() {
return Ok(Thumb {
data: stripped.bytes,
mime_type: sniffed.to_string(),
note: stripped
.removed
.then(|| format!("{label} had its metadata (EXIF and the like) removed")),
});
}
turned = true;
}
let shrunk =
tokio::task::spawn_blocking(move || crate::thumbnail::shrink(&body, limit, preserve))
.await
.map_err(|error| format!("re-encoding {label} failed: {error}"))?
.map_err(|reason| {
if turned {
format!("{label} is stored turned, and re-encoding it failed: {reason}")
} else {
format!(
"{label} is {size} bytes, over the lexicon's {limit_bytes}-byte limit, \
and {reason}"
)
}
})?;
let note = if turned {
format!(
"{label} is stored turned, which only its EXIF says, so it was re-encoded as a \
{}x{} JPEG of {} bytes with the turn applied and no metadata",
shrunk.width,
shrunk.height,
shrunk.bytes.len()
)
} else {
format!(
"{label} was {size} bytes, {}x{}, so it was shrunk to a {}x{} JPEG of {} bytes, {}",
shrunk.source_width,
shrunk.source_height,
shrunk.width,
shrunk.height,
shrunk.bytes.len(),
if preserve {
"with its EXIF copied in"
} else {
"without its metadata"
}
)
};
Ok(Thumb {
data: shrunk.bytes,
mime_type: "image/jpeg".to_string(),
note: Some(note),
})
}
struct MediaEmbed {
value: Value,
uploaded: Vec<Uploaded>,
}
async fn media_embed(
ctx: &Arc<ServerContext>,
rctx: &mut RequestCtx,
media: &Media,
account: &mut accounts::Account,
notes: &mut Vec<String>,
) -> Result<MediaEmbed, ToolError> {
let failed = |reason: String| ToolError::ImageFailed { reason };
let mut prepared = Vec::with_capacity(media.items.len());
for item in &media.items {
let (body, served) = match &item.source {
ImageSource::Path(path) => (
crate::tools::blob::read_local_file(path, ctx.limits.blob_max_upload_bytes).await?,
None,
),
ImageSource::Url(url) => {
let fetched = fetch_image(ctx, url, &item.label).await.map_err(failed)?;
(fetched.body, fetched.content_type)
}
};
let image = prepare_image(
ctx.limits.preserve_exif,
body,
served.as_deref(),
MAX_MEDIA_IMAGE_BYTES,
&item.label,
)
.await
.map_err(failed)?;
let dimensions = match (
crate::thumbnail::display_dimensions(&image.data),
media.kind,
) {
(Ok(dimensions), _) => Some(dimensions),
(Err(_), MediaKind::Images) => None,
(Err(reason), MediaKind::Gallery) => {
return Err(failed(format!(
"{}: {reason}, and a gallery item needs its aspect ratio",
item.label
)));
}
};
prepared.push((item, image, dimensions));
}
let mut entries = Vec::with_capacity(prepared.len());
let mut uploaded = Vec::with_capacity(prepared.len());
for (item, image, dimensions) in prepared {
if let Some(note) = image.note {
notes.push(note);
}
let blob = put_blob(ctx, rctx, account, image.data, &image.mime_type).await?;
let mut entry = serde_json::json!({ "alt": item.alt, "image": blob.blob });
if let Some((width, height)) = dimensions {
entry["aspectRatio"] = serde_json::json!({ "width": width, "height": height });
}
if media.kind == MediaKind::Gallery {
entry["$type"] = Value::from(format!("{GALLERY_NSID}#image"));
}
entries.push(entry);
uploaded.push(blob);
}
let unlabelled: Vec<String> = media
.items
.iter()
.enumerate()
.filter(|(_, item)| item.alt.is_empty())
.map(|(index, _)| (index + 1).to_string())
.collect();
if !unlabelled.is_empty() {
notes.push(format!(
"{} item{} {} {} no alt text",
media.kind.argument(),
if unlabelled.len() == 1 { "" } else { "s" },
unlabelled.join(", "),
if unlabelled.len() == 1 { "has" } else { "have" }
));
}
let value = match media.kind {
MediaKind::Gallery => serde_json::json!({ "$type": GALLERY_NSID, "items": entries }),
MediaKind::Images => serde_json::json!({ "$type": IMAGES_NSID, "images": entries }),
};
Ok(MediaEmbed { value, uploaded })
}
fn to_short_url(text: &str) -> String {
let Ok(url) = Url::parse(text) else {
return text.to_string();
};
if !matches!(url.scheme(), "http" | "https") {
return text.to_string();
}
let Some(host) = url.host_str() else {
return text.to_string();
};
let host = match url.port() {
Some(port) => format!("{host}:{port}"),
None => host.to_string(),
};
let mut path = if url.path() == "/" {
String::new()
} else {
url.path().to_string()
};
if let Some(query) = url.query().filter(|query| !query.is_empty()) {
path.push('?');
path.push_str(query);
}
if let Some(fragment) = url.fragment().filter(|fragment| !fragment.is_empty()) {
path.push('#');
path.push_str(fragment);
}
if path.encode_utf16().count() > 15 {
format!("{host}{}...", path.chars().take(13).collect::<String>())
} else {
format!("{host}{path}")
}
}
fn shorten_links(text: &str, facets: &[Facet]) -> (String, Vec<Facet>) {
let unchanged = || (text.to_string(), facets.to_vec());
let mut order: Vec<usize> = (0..facets.len()).collect();
order.sort_by_key(|&index| facets[index].index.byte_start);
let mut shortened = String::with_capacity(text.len());
let mut moved = facets.to_vec();
let mut cursor = 0;
for index in order {
let (start, end) = (facets[index].index.byte_start, facets[index].index.byte_end);
if start < cursor
|| end < start
|| end > text.len()
|| !text.is_char_boundary(start)
|| !text.is_char_boundary(end)
{
return unchanged();
}
shortened.push_str(&text[cursor..start]);
let new_start = shortened.len();
let covered = &text[start..end];
match facets[index].features.first() {
Some(FacetFeature::Link(_)) => shortened.push_str(&to_short_url(covered)),
_ => shortened.push_str(covered),
}
moved[index].index.byte_start = new_start;
moved[index].index.byte_end = shortened.len();
cursor = end;
}
shortened.push_str(&text[cursor..]);
(shortened, moved)
}
fn check_url(ctx: &ServerContext, url: &Url) -> Result<(), ToolError> {
let mut bare = url.clone();
bare.set_query(None);
bare.set_fragment(None);
host_policy::check_endpoint(&ctx.limits, bare.as_str())
}
struct Fetched {
url: Url,
content_type: Option<String>,
body: Vec<u8>,
}
#[derive(Clone, Copy)]
enum Overflow {
Truncate,
Refuse,
}
enum FetchError {
TooLarge,
Failed(String),
}
impl std::fmt::Display for FetchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TooLarge => f.write_str("the response is too large"),
Self::Failed(reason) => f.write_str(reason),
}
}
}
async fn fetch(
client: &reqwest::Client,
url: &Url,
accept: &str,
cap: u64,
overflow: Overflow,
) -> Result<Fetched, FetchError> {
let response = client
.get(url.clone())
.header(ACCEPT, accept)
.send()
.await
.map_err(|error| {
tracing::debug!(error = ?error, url = %url, "A link card fetch failed.");
FetchError::Failed(describe(&error))
})?;
let status = response.status();
if !status.is_success() {
return Err(FetchError::Failed(format!(
"{} answered HTTP {}",
response.url(),
status.as_u16()
)));
}
if matches!(overflow, Overflow::Refuse)
&& response
.content_length()
.is_some_and(|declared| declared > cap)
{
return Err(FetchError::TooLarge);
}
let final_url = response.url().clone();
let content_type = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map(str::to_string);
let cap = usize::try_from(cap).unwrap_or(usize::MAX);
let mut body = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|error| {
FetchError::Failed(format!("reading {final_url} failed: {}", describe(&error)))
})?;
let room = cap - body.len();
if chunk.len() > room {
match overflow {
Overflow::Truncate => {
body.extend_from_slice(&chunk[..room]);
break;
}
Overflow::Refuse => return Err(FetchError::TooLarge),
}
}
body.extend_from_slice(&chunk);
}
Ok(Fetched {
url: final_url,
content_type,
body,
})
}
fn describe(error: &dyn std::error::Error) -> String {
let mut text = error.to_string();
let mut source = error.source();
while let Some(next) = source {
text.push_str(": ");
text.push_str(&next.to_string());
source = next.source();
}
text
}
fn base_type(content_type: &str) -> String {
content_type
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
}
fn is_html(content_type: Option<&str>, body: &[u8]) -> bool {
match content_type.map(base_type).as_deref() {
Some("text/html" | "application/xhtml+xml") => true,
Some(_) => false,
None => {
let start = String::from_utf8_lossy(&body[..body.len().min(64)]).to_ascii_lowercase();
let start = start.trim_start_matches('\u{feff}').trim_start();
start.starts_with("<!doctype html") || start.starts_with("<html")
}
}
}
fn decode(body: &[u8], content_type: Option<&str>) -> String {
let encoding = content_type
.and_then(|value| {
value.split(';').skip(1).find_map(|parameter| {
let (name, label) = parameter.split_once('=')?;
name.trim()
.eq_ignore_ascii_case("charset")
.then(|| label.trim().trim_matches('"').to_string())
})
})
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
.unwrap_or(encoding_rs::UTF_8);
encoding.decode(body).0.into_owned()
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use async_trait::async_trait;
use atproto_identity::model::Document;
use super::*;
use crate::tools::test_support::{Route, route_server, test_context, test_request};
async fn call(arguments: Value) -> Value {
let ctx = test_context();
let mut rctx = test_request();
generate_bsky_post(&ctx, &mut rctx, arguments).await
}
fn record_of(result: &Value) -> &Value {
assert_eq!(result["isError"], false, "{result}");
&result["structuredContent"]["record"]
}
fn notes_of(result: &Value) -> Vec<String> {
result["structuredContent"]["notes"]
.as_array()
.expect("notes")
.iter()
.map(|note| note.as_str().unwrap().to_string())
.collect()
}
fn error_of(result: &Value) -> String {
assert_eq!(result["isError"], true, "{result}");
result["content"][0]["text"].as_str().unwrap().to_string()
}
struct FixedResolver(HashMap<&'static str, &'static str>);
#[async_trait]
impl IdentityResolver for FixedResolver {
async fn resolve(&self, subject: &str) -> anyhow::Result<Document> {
let did = self
.0
.get(subject)
.ok_or_else(|| anyhow::anyhow!("unknown handle {subject}"))?;
Ok(Document {
context: vec![],
id: (*did).to_string(),
also_known_as: vec![format!("at://{subject}")],
verification_method: vec![],
service: vec![],
extra: HashMap::new(),
})
}
}
fn resolver() -> FixedResolver {
FixedResolver(HashMap::from([(
"ngerakines.me",
"did:plc:cbkjy5n7bk3ax2wplmtjofq2",
)]))
}
fn allow_mentions(mentions: &[&str]) -> FacetAllowList {
FacetAllowList {
mentions: mentions.iter().map(|m| (*m).to_string()).collect(),
..FacetAllowList::default()
}
}
#[test]
fn every_bundled_lexicon_parses() {
for (nsid, _) in LEXICONS {
assert!(CATALOG.get_schema(nsid).is_some(), "{nsid} did not parse");
}
}
#[test]
fn the_bundled_lexicons_are_atproto_pds_copies() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
for (nsid, json) in LEXICONS {
let path = format!("{}.json", nsid.replace('.', "/"));
let theirs = std::fs::read_to_string(root.join("../atproto-pds/lexicons").join(&path))
.unwrap_or_else(|error| panic!("{path}: {error}"));
assert_eq!(*json, theirs, "{path} differs from atproto-pds's copy");
}
}
#[test]
fn the_catalog_checks_the_link_card() {
let post = |external: Value| {
serde_json::json!({
"$type": POST_NSID,
"text": "x",
"createdAt": "2026-11-18T00:00:00.000Z",
"embed": { "$type": EXTERNAL_NSID, "external": external },
})
};
let valid = |record: &Value| {
validate_record(POST_NSID, record, &*CATALOG, ValidateFlags::empty()).is_ok()
};
let thumb = |size: u64| {
serde_json::json!({
"$type": "blob",
"ref": { "$link": "bafkreidyl3nf2xm3iyswuw5mj42dwz5mogk45kxwcdzufj6oc27e4cpzqy" },
"mimeType": "image/jpeg",
"size": size,
})
};
assert!(valid(&post(serde_json::json!({
"uri": "https://example.com/", "title": "t", "description": "",
"thumb": thumb(166_721),
}))));
assert!(!valid(&post(
serde_json::json!({ "uri": "https://example.com/", "description": "" })
)));
assert!(!valid(&post(serde_json::json!({
"uri": "https://example.com/", "title": "t", "description": "",
"thumb": thumb(MAX_THUMB_BYTES + 1),
}))));
assert!(!valid(&post(serde_json::json!({
"uri": "not a uri", "title": "t", "description": "",
}))));
}
#[tokio::test]
async fn a_plain_text_is_a_plain_post() {
let result = call(serde_json::json!({ "text": "hello world" })).await;
let record = record_of(&result);
assert_eq!(record["$type"], POST_NSID);
assert_eq!(record["text"], "hello world");
assert_eq!(record["langs"], serde_json::json!(["en"]));
assert!(record.get("facets").is_none());
assert!(record.get("embed").is_none());
let created = record["createdAt"].as_str().unwrap();
assert!(
atproto_record::datetime::Datetime::new(created).is_ok(),
"{created}"
);
assert!(created.ends_with('Z') && created.len() == 24, "{created}");
assert!(notes_of(&result).is_empty());
}
#[tokio::test]
async fn the_text_is_kept_exactly() {
let text = "Hello World\n\nwith a ✨ and trailing space ";
let result = call(serde_json::json!({ "text": text })).await;
assert_eq!(record_of(&result)["text"], text);
}
#[tokio::test]
async fn an_absent_or_empty_mention_list_keeps_every_mention() {
for allow in [FacetAllowList::default(), allow_mentions(&[])] {
let (facets, notes) = facets_for("Hello @ngerakines.me", &allow, &resolver()).await;
assert_eq!(facets.len(), 1);
assert_eq!(facets[0].index.byte_start, 6);
assert_eq!(facets[0].index.byte_end, 20);
assert!(matches!(
&facets[0].features[0],
FacetFeature::Mention(mention) if mention.did == "did:plc:cbkjy5n7bk3ax2wplmtjofq2"
));
assert!(notes.is_empty(), "{notes:?}");
}
}
#[tokio::test]
async fn a_mention_list_leaves_out_what_it_does_not_name() {
let (facets, notes) = facets_for(
"Hello @ngerakines.me",
&allow_mentions(&["@mattie.thegem.city"]),
&resolver(),
)
.await;
assert!(facets.is_empty());
assert_eq!(
notes,
vec!["@ngerakines.me has no facet: mention_facet_allow leaves it out"]
);
}
#[tokio::test]
async fn example_four_through_the_tool() {
let result = call(serde_json::json!({
"text": "Hello @ngerakines.me",
"mention_facet_allow": ["@mattie.thegem.city"],
}))
.await;
let record = record_of(&result);
assert_eq!(record["text"], "Hello @ngerakines.me");
assert!(record.get("facets").is_none());
assert_eq!(notes_of(&result).len(), 1);
}
#[tokio::test]
async fn an_unresolved_mention_is_noted() {
let (facets, notes) = facets_for(
"Hi @nobody.example",
&FacetAllowList::default(),
&resolver(),
)
.await;
assert!(facets.is_empty());
assert_eq!(
notes,
vec!["@nobody.example has no facet: it did not resolve to a DID"]
);
}
#[tokio::test]
async fn link_and_tag_lists_filter_their_own_kind() {
let result = call(serde_json::json!({
"text": "see https://a.example and https://b.example #rust #go",
"link_facet_allow": ["https://b.example"],
"tag_facet_allow": ["#Rust"],
}))
.await;
let facets = record_of(&result)["facets"].as_array().unwrap().clone();
assert_eq!(facets.len(), 2);
assert_eq!(facets[0]["features"][0]["uri"], "https://b.example");
assert_eq!(facets[1]["features"][0]["tag"], "rust");
let notes = notes_of(&result);
assert!(
notes
.iter()
.any(|n| n.starts_with("https://a.example has no facet"))
);
assert!(notes.iter().any(|n| n.starts_with("#go has no facet")));
}
#[tokio::test]
async fn links_past_the_limit_are_noted() {
let text = (1..=6)
.map(|n| format!("https://site{n}.example"))
.collect::<Vec<_>>()
.join(" ");
let result = call(serde_json::json!({ "text": text })).await;
assert_eq!(record_of(&result)["facets"].as_array().unwrap().len(), 5);
assert!(
notes_of(&result)
.iter()
.any(|n| n.starts_with("1 of the post's links have no facet"))
);
}
#[tokio::test]
async fn langs_default_to_english_and_can_be_given_or_left_out() {
let given = call(serde_json::json!({ "text": "salut", "langs": ["fr", "en-CA"] })).await;
assert_eq!(
record_of(&given)["langs"],
serde_json::json!(["fr", "en-CA"])
);
let none = call(serde_json::json!({ "text": "salut", "langs": [] })).await;
assert!(record_of(&none).get("langs").is_none());
let null = call(serde_json::json!({ "text": "hi", "langs": null })).await;
assert_eq!(record_of(&null)["langs"], serde_json::json!(["en"]));
}
#[tokio::test]
async fn bad_arguments_are_refused() {
for (arguments, expect) in [
(serde_json::json!({}), "'text'"),
(serde_json::json!({ "text": 5 }), "'text'"),
(
serde_json::json!({ "text": "x", "langs": ["en", "fr", "de", "es"] }),
"at most 3",
),
(serde_json::json!({ "text": "x", "langs": "en" }), "'langs'"),
(
serde_json::json!({ "text": "x", "mention_facet_allow": "@a.example" }),
"'mention_facet_allow'",
),
(
serde_json::json!({ "text": "x", "tag_facet_allow": [1] }),
"'tag_facet_allow'",
),
(
serde_json::json!({ "text": "x", "embed_external": "not a url" }),
"absolute URL",
),
(
serde_json::json!({ "text": "x", "embed_external": "ftp://example.com/" }),
"http or https",
),
] {
let error = error_of(&call(arguments.clone()).await);
assert!(error.starts_with("error-atpmcp-tool-23 "), "{error}");
assert!(error.contains(expect), "{arguments}: {error}");
}
}
#[tokio::test]
async fn a_record_the_lexicon_refuses_is_not_returned() {
let too_long = call(serde_json::json!({ "text": "x".repeat(301) })).await;
assert!(error_of(&too_long).contains("does not validate"));
let bad_lang = call(serde_json::json!({ "text": "x", "langs": ["not a language!"] })).await;
assert!(error_of(&bad_lang).contains("does not validate"));
}
const PAGE: &str = r#"<!doctype html><html><head>
<title>Fallback title</title>
<meta property="og:title" content="A bit about email">
<meta property="og:description" content="Notes & history">
<meta property="og:image" content="/card.png">
</head><body><p>Hello</p></body></html>"#;
#[tokio::test]
async fn a_link_card_comes_from_the_pages_open_graph_metadata() {
let base = route_server(vec![Route::ok("/misc/email/", "text/html", PAGE)]).await;
let page = format!("{base}/misc/email/");
let result = call(serde_json::json!({
"text": format!("Check out {page}"),
"embed_external": page,
}))
.await;
let record = record_of(&result);
assert_eq!(record["embed"]["$type"], EXTERNAL_NSID);
let external = &record["embed"]["external"];
assert_eq!(external["uri"], page);
assert_eq!(external["title"], "A bit about email");
assert_eq!(external["description"], "Notes & history");
assert!(external.get("thumb").is_none());
assert_eq!(record["facets"][0]["features"][0]["uri"], page);
let notes = notes_of(&result);
assert!(
notes[0].contains("pass auth_handle") && notes[0].contains(&format!("{base}/card.png")),
"{notes:?}"
);
}
#[tokio::test]
async fn a_page_with_no_metadata_still_makes_a_valid_card() {
let base = route_server(vec![Route::ok(
"/",
"text/html; charset=utf-8",
"<p>bare</p>",
)])
.await;
let result =
call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/") })).await;
let external = &record_of(&result)["embed"]["external"];
assert_eq!(external["title"], "");
assert_eq!(external["description"], "");
assert!(notes_of(&result)[0].contains("names no image"));
}
#[tokio::test]
async fn a_page_in_another_charset_is_decoded() {
let mut body = b"<head><meta property=\"og:title\" content=\"caf".to_vec();
body.push(0xE9); body.extend_from_slice(b"\"></head>");
let base = route_server(vec![Route::ok(
"/",
"text/html; charset=windows-1252",
body,
)])
.await;
let result =
call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/") })).await;
assert_eq!(record_of(&result)["embed"]["external"]["title"], "café");
}
#[tokio::test]
async fn a_page_past_the_cap_is_read_as_far_as_the_cap() {
let mut body = PAGE.replace("<p>Hello</p>", "").into_bytes();
body.extend(std::iter::repeat_n(b'x', MAX_PAGE_BYTES as usize + 10));
let base = route_server(vec![Route::ok("/", "text/html", body)]).await;
let result =
call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/") })).await;
assert_eq!(
record_of(&result)["embed"]["external"]["title"],
"A bit about email"
);
}
#[tokio::test]
async fn a_page_that_cannot_be_read_is_an_error() {
let base = route_server(vec![
Route::ok("/json", "application/json", "{}"),
Route {
path: "/gone",
status: 410,
headers: vec![],
body: Vec::new(),
},
])
.await;
for (path, expect) in [
("/json", "not HTML"),
("/gone", "HTTP 410"),
("/missing", "HTTP 404"),
] {
let error = error_of(
&call(
serde_json::json!({ "text": "x", "embed_external": format!("{base}{path}") }),
)
.await,
);
assert!(error.starts_with("error-atpmcp-tool-24 "), "{error}");
assert!(error.contains(expect), "{path}: {error}");
}
}
#[tokio::test]
async fn a_redirect_to_a_local_address_is_refused() {
let base = route_server(vec![Route {
path: "/hop",
status: 302,
headers: vec![("Location", "http://127.0.0.1:9/admin".to_string())],
body: Vec::new(),
}])
.await;
let error = error_of(
&call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/hop") }))
.await,
);
assert!(error.starts_with("error-atpmcp-tool-24 "), "{error}");
assert!(error.contains("redirect"), "{error}");
}
#[tokio::test]
async fn a_page_url_with_a_query_is_checked_without_it() {
let base = route_server(vec![Route::ok("/p?id=3", "text/html", PAGE)]).await;
let result =
call(serde_json::json!({ "text": "x", "embed_external": format!("{base}/p?id=3") }))
.await;
assert_eq!(
record_of(&result)["embed"]["external"]["uri"],
format!("{base}/p?id=3")
);
}
#[test]
fn the_media_limits_are_the_lexicons() {
let def = |nsid: &str, name: &str| {
let (_, json) = LEXICONS.iter().find(|(id, _)| *id == nsid).unwrap();
serde_json::from_str::<Value>(json).unwrap()["defs"][name].clone()
};
let images = def(IMAGES_NSID, "main");
assert_eq!(
images["properties"]["images"]["maxLength"],
MAX_IMAGES_ITEMS as u64
);
for nsid in [IMAGES_NSID, GALLERY_NSID] {
assert_eq!(
def(nsid, "image")["properties"]["image"]["maxSize"],
MAX_MEDIA_IMAGE_BYTES,
"{nsid}"
);
}
let gallery_max = def(GALLERY_NSID, "main")["properties"]["items"]["maxLength"]
.as_u64()
.unwrap();
assert!(MAX_GALLERY_ITEMS as u64 <= gallery_max);
assert_eq!(
def(EXTERNAL_NSID, "external")["properties"]["thumb"]["maxSize"],
MAX_THUMB_BYTES
);
}
#[test]
fn the_catalog_checks_gallery_and_images_items() {
let blob = |size: u64| {
serde_json::json!({
"$type": "blob",
"ref": { "$link": "bafkreidyl3nf2xm3iyswuw5mj42dwz5mogk45kxwcdzufj6oc27e4cpzqy" },
"mimeType": "image/jpeg",
"size": size,
})
};
let post = |embed: Value| {
serde_json::json!({
"$type": POST_NSID, "text": "x", "createdAt": "2026-11-18T00:00:00.000Z",
"embed": embed,
})
};
let valid = |record: &Value| {
validate_record(POST_NSID, record, &*CATALOG, ValidateFlags::empty()).is_ok()
};
let gallery_item = |size: u64| {
serde_json::json!({
"$type": "app.bsky.embed.gallery#image", "alt": "",
"aspectRatio": { "width": 446, "height": 248 }, "image": blob(size),
})
};
let gallery =
|items: Vec<Value>| post(serde_json::json!({ "$type": GALLERY_NSID, "items": items }));
let images =
|items: Vec<Value>| post(serde_json::json!({ "$type": IMAGES_NSID, "images": items }));
assert!(valid(&gallery(vec![gallery_item(86_967); 7])));
assert!(!valid(&gallery(vec![gallery_item(86_967); 21])));
assert!(!valid(&gallery(vec![gallery_item(
MAX_MEDIA_IMAGE_BYTES + 1
)])));
let mut no_ratio = gallery_item(1);
no_ratio.as_object_mut().unwrap().remove("aspectRatio");
assert!(
!valid(&gallery(vec![no_ratio])),
"a gallery item needs its ratio"
);
let image = serde_json::json!({ "alt": "", "image": blob(1) });
assert!(
valid(&images(vec![image.clone(); 4])),
"an images item's ratio is optional"
);
assert!(!valid(&images(vec![image.clone(); 5])));
let mut no_alt = image;
no_alt.as_object_mut().unwrap().remove("alt");
assert!(!valid(&images(vec![no_alt])));
}
#[tokio::test]
async fn media_arguments_are_checked_before_anything_is_read() {
let png = serde_json::json!({ "path": "/tmp/a.png" });
let many = |n: usize| Value::from(vec![png.clone(); n]);
for (arguments, expect) in [
(
serde_json::json!({ "text": "x", "gallery": [png], "images": [png] }),
"not both",
),
(
serde_json::json!({ "text": "x", "gallery": [png], "embed_external": "https://example.com/" }),
"'gallery' or 'embed_external'",
),
(serde_json::json!({ "text": "x", "gallery": [] }), "1 to 10"),
(
serde_json::json!({ "text": "x", "gallery": many(11) }),
"1 to 10",
),
(
serde_json::json!({ "text": "x", "images": many(5) }),
"1 to 4",
),
(
serde_json::json!({ "text": "x", "gallery": "a.png" }),
"array of images",
),
(
serde_json::json!({ "text": "x", "gallery": ["/tmp/a.png"] }),
"an object",
),
(
serde_json::json!({ "text": "x", "gallery": [{ "path": "/a", "url": "https://e.com/a" }] }),
"both 'path' and 'url'",
),
(
serde_json::json!({ "text": "x", "gallery": [{ "alt": "a" }] }),
"needs a 'path' or a 'url'",
),
(
serde_json::json!({ "text": "x", "gallery": [{ "data_base64": "AAAA" }] }),
"unknown field 'data_base64'",
),
(
serde_json::json!({ "text": "x", "gallery": [{ "url": "ftp://e.com/a.png" }] }),
"http or https",
),
(
serde_json::json!({ "text": "x", "gallery": [{ "path": "/a", "alt": 3 }] }),
"'alt'",
),
(
serde_json::json!({ "text": "x", "shorten_links": "yes" }),
"'shorten_links'",
),
(
serde_json::json!({ "text": "x", "gallery": [png] }),
"needs auth_handle",
),
] {
let error = error_of(&call(arguments.clone()).await);
assert!(error.starts_with("error-atpmcp-tool-23 "), "{error}");
assert!(error.contains(expect), "{arguments}: {error}");
}
}
#[test]
fn urls_are_shortened_as_the_bluesky_app_shortens_them() {
for (url, short) in [
(
"https://tangled.org/ngerakines.me/wow-break-timer",
"tangled.org/ngerakines.m...",
),
("https://example.com/", "example.com"),
("https://example.com", "example.com"),
("http://example.com/abc", "example.com/abc"),
(
"https://example.com/abcdefghijklmn",
"example.com/abcdefghijklmn",
),
(
"https://example.com/abcdefghijklmno",
"example.com/abcdefghijkl...",
),
("https://example.com/?q=1#top", "example.com?q=1#top"),
("https://example.com:8443/a", "example.com:8443/a"),
("https://EXAMPLE.com/A", "example.com/A"),
("mailto:alice@example.com", "mailto:alice@example.com"),
("not a url", "not a url"),
] {
assert_eq!(to_short_url(url), short, "{url}");
}
}
#[tokio::test]
async fn shorten_links_reproduces_the_bluesky_apps_post() {
let text = "Started playing WoW Forever and wrote a small add-on to remind myself to take \
breaks and stand up.\n\nhttps://tangled.org/ngerakines.me/wow-break-timer";
let result = call(serde_json::json!({ "text": text, "shorten_links": true })).await;
let record = record_of(&result);
assert_eq!(
record["text"],
"Started playing WoW Forever and wrote a small add-on to remind myself to take breaks \
and stand up.\n\ntangled.org/ngerakines.m..."
);
assert_eq!(
record["facets"],
serde_json::json!([{
"features": [{
"$type": "app.bsky.richtext.facet#link",
"uri": "https://tangled.org/ngerakines.me/wow-break-timer"
}],
"index": { "byteStart": 100, "byteEnd": 127 }
}])
);
}
#[tokio::test]
async fn shortening_moves_the_facets_after_a_link() {
let result = call(serde_json::json!({
"text": "see https://example.com/a/very/long/path #rust and https://b.example/x",
"shorten_links": true,
"link_facet_allow": ["https://example.com/a/very/long/path"],
}))
.await;
let record = record_of(&result);
let text = record["text"].as_str().unwrap();
assert_eq!(
text,
"see example.com/a/very/long/... #rust and https://b.example/x"
);
for facet in record["facets"].as_array().unwrap() {
let (start, end) = (
facet["index"]["byteStart"].as_u64().unwrap() as usize,
facet["index"]["byteEnd"].as_u64().unwrap() as usize,
);
let covered = &text[start..end];
match facet["features"][0]["$type"].as_str().unwrap() {
"app.bsky.richtext.facet#tag" => assert_eq!(covered, "#rust"),
_ => {
assert_eq!(covered, "example.com/a/very/long/...");
assert_eq!(
facet["features"][0]["uri"],
"https://example.com/a/very/long/path"
);
}
}
}
}
#[tokio::test]
async fn links_are_left_alone_without_shorten_links() {
let text = "https://tangled.org/ngerakines.me/wow-break-timer";
let result = call(serde_json::json!({ "text": text })).await;
assert_eq!(record_of(&result)["text"], text);
}
#[tokio::test]
async fn a_text_over_the_limit_is_refused_before_any_image_is_read() {
let result = call(serde_json::json!({
"text": "x".repeat(301),
"embed_external": "https://127.0.0.1:1/never-fetched",
}))
.await;
assert!(error_of(&result).contains("does not validate"));
}
async fn thumbnail_from(
ctx: &ServerContext,
content_type: &str,
body: Vec<u8>,
) -> Result<Thumb, String> {
let base = route_server(vec![Route::ok("/image", content_type, body)]).await;
let url = Url::parse(&format!("{base}/image")).unwrap();
thumbnail_bytes(ctx, &url).await
}
fn preserving_context() -> Arc<ServerContext> {
crate::tools::test_support::test_context_with_cache_and_limits(crate::context::Limits {
preserve_exif: true,
..crate::tools::test_support::test_limits()
})
}
#[tokio::test]
async fn an_image_stored_turned_is_re_encoded_turned() {
use crate::image_metadata::tests::{SECRET, jpeg_with_metadata};
let thumb = thumbnail_from(&test_context(), "image/jpeg", jpeg_with_metadata(6))
.await
.expect("a thumbnail");
assert_eq!(thumb.mime_type, "image/jpeg");
assert!(thumb.note.as_deref().unwrap().contains("stored turned"));
assert!(!thumb.data.windows(SECRET.len()).any(|w| w == SECRET));
let decoded = image::load_from_memory(&thumb.data).unwrap();
assert_eq!((decoded.width(), decoded.height()), (16, 24));
}
#[tokio::test]
async fn a_format_that_cannot_be_stripped_needs_the_preserve_setting() {
let mut bmp = Vec::new();
image::DynamicImage::ImageRgb8(image::RgbImage::new(4, 4))
.write_to(&mut std::io::Cursor::new(&mut bmp), image::ImageFormat::Bmp)
.unwrap_or_else(|_| {
bmp.clear();
bmp.extend_from_slice(b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0\x28\0\0\0");
bmp.resize(70, 0);
});
let refused = thumbnail_from(&test_context(), "image/bmp", bmp.clone()).await;
let reason = refused.err().expect("refused while stripping");
assert!(reason.contains("ATPMCP_PRESERVE_EXIF=1"), "{reason}");
let served = thumbnail_from(&preserving_context(), "image/bmp", bmp.clone())
.await
.expect("used as served");
assert_eq!(served.data, bmp);
assert!(served.note.is_none());
}
#[tokio::test]
async fn a_shrunk_image_keeps_its_exif_only_when_preserving() {
use crate::image_metadata::tests::SECRET;
let mut exif = vec![
b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0,
];
exif.extend_from_slice(SECRET);
let png = {
use image::ImageEncoder;
let pixels = crate::thumbnail::tests::noise(800 * 600 * 3, 7);
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
encoder.set_exif_metadata(exif).unwrap();
encoder
.write_image(&pixels, 800, 600, image::ExtendedColorType::Rgb8)
.unwrap();
png
};
assert!(png.len() as u64 > MAX_THUMB_BYTES);
let has_secret = |data: &[u8]| data.windows(SECRET.len()).any(|w| w == SECRET);
let stripped = thumbnail_from(&test_context(), "image/png", png.clone())
.await
.unwrap();
assert!(!has_secret(&stripped.data));
assert!(stripped.note.unwrap().contains("without its metadata"));
let kept = thumbnail_from(&preserving_context(), "image/png", png)
.await
.unwrap();
assert!(has_secret(&kept.data));
assert!(kept.note.unwrap().contains("with its EXIF copied in"));
}
#[test]
fn html_is_recognised_by_type_or_by_its_start() {
assert!(is_html(Some("text/html; charset=utf-8"), b""));
assert!(is_html(Some("Application/XHTML+XML"), b""));
assert!(!is_html(Some("text/plain"), b"<html>"));
assert!(is_html(None, b"\xEF\xBB\xBF <!DOCTYPE html><html>"));
assert!(!is_html(None, b"{\"json\": true}"));
}
}