separation of activitypub
This commit is contained in:
341
crates/adapters/activitypub-base/src/activities.rs
Normal file
341
crates/adapters/activitypub-base/src/activities.rs
Normal file
@@ -0,0 +1,341 @@
|
||||
use activitypub_federation::{
|
||||
config::Data,
|
||||
fetch::object_id::ObjectId,
|
||||
kinds::activity::{AcceptType, CreateType, DeleteType, FollowType, RejectType, UndoType, UpdateType},
|
||||
traits::Activity,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::actors::DbActor;
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
use crate::repository::{FollowerStatus, FollowingStatus};
|
||||
|
||||
// --- Follow ---
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FollowActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: FollowType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: ObjectId<DbActor>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for FollowActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let target_url = self.object.inner();
|
||||
let target_domain = match (target_url.host_str(), target_url.port()) {
|
||||
(Some(host), Some(port)) => format!("{}:{}", host, port),
|
||||
(Some(host), None) => host.to_string(),
|
||||
_ => return Err(Error::bad_request(anyhow::anyhow!("invalid follow target URL"))),
|
||||
};
|
||||
if target_domain != data.domain {
|
||||
return Err(Error::bad_request(anyhow::anyhow!("follow target is not a local actor")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let _follower = self.actor.dereference(data).await?;
|
||||
let local_actor = self.object.dereference(data).await?;
|
||||
|
||||
data.federation_repo
|
||||
.add_follower(
|
||||
local_actor.user_id,
|
||||
self.actor.inner().as_str(),
|
||||
FollowerStatus::Pending,
|
||||
self.id.as_str(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
tracing::info!(
|
||||
follower = %self.actor.inner(),
|
||||
local_user = %local_actor.user_id,
|
||||
"follow request pending approval"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Accept ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AcceptActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: AcceptType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: FollowActivity,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for AcceptActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let local_user_id = crate::urls::extract_user_id_from_url(self.object.actor.inner())
|
||||
.ok_or_else(|| Error::bad_request(anyhow::anyhow!("invalid actor URL in Follow")))?;
|
||||
data.federation_repo
|
||||
.update_following_status(local_user_id, self.actor.inner().as_str(), FollowingStatus::Accepted)
|
||||
.await?;
|
||||
tracing::info!(remote_actor = %self.actor.inner(), "follow accepted by remote");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reject ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RejectActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: RejectType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: FollowActivity,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for RejectActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
if let Some(user_id) = crate::urls::extract_user_id_from_url(self.object.actor.inner()) {
|
||||
data.federation_repo
|
||||
.remove_following(user_id, self.actor.inner().as_str())
|
||||
.await?;
|
||||
}
|
||||
tracing::info!(actor = %self.actor.inner(), "follow rejected");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Undo ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UndoActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: UndoType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: FollowActivity,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for UndoActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
if let Some(user_id) = crate::urls::extract_user_id_from_url(self.object.object.inner()) {
|
||||
data.federation_repo
|
||||
.remove_follower(user_id, self.actor.inner().as_str())
|
||||
.await?;
|
||||
}
|
||||
data.object_handler
|
||||
.on_actor_removed(self.actor.inner())
|
||||
.await
|
||||
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||
tracing::info!(actor = %self.actor.inner(), "unfollowed");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Create ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: CreateType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: serde_json::Value,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for CreateActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let ap_id = self.id.clone();
|
||||
let actor_url = self.actor.inner().clone();
|
||||
data.object_handler
|
||||
.on_create(&ap_id, &actor_url, self.object)
|
||||
.await
|
||||
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||
tracing::info!(actor = %actor_url, "received create activity");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Delete ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: DeleteType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: Url,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for DeleteActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let actor_url = self.actor.inner().clone();
|
||||
data.object_handler
|
||||
.on_delete(&self.object, &actor_url)
|
||||
.await
|
||||
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||
tracing::info!(object = %self.object, "received delete activity");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Update ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateActivity {
|
||||
pub(crate) id: Url,
|
||||
#[serde(rename = "type", default)]
|
||||
pub(crate) kind: UpdateType,
|
||||
pub(crate) actor: ObjectId<DbActor>,
|
||||
pub(crate) object: serde_json::Value,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Activity for UpdateActivity {
|
||||
type DataType = FederationData;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn actor(&self) -> &Url {
|
||||
self.actor.inner()
|
||||
}
|
||||
|
||||
async fn verify(&self, _data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(self, data: &Data<Self::DataType>) -> Result<(), Self::Error> {
|
||||
let ap_id = self.id.clone();
|
||||
let actor_url = self.actor.inner().clone();
|
||||
data.object_handler
|
||||
.on_update(&ap_id, &actor_url, self.object)
|
||||
.await
|
||||
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||
tracing::info!(actor = %actor_url, "received update activity");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- Inbox dispatch enum ---
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(tag = "type")]
|
||||
#[enum_delegate::implement(Activity)]
|
||||
pub enum InboxActivities {
|
||||
#[serde(rename = "Follow")]
|
||||
Follow(FollowActivity),
|
||||
#[serde(rename = "Accept")]
|
||||
Accept(AcceptActivity),
|
||||
#[serde(rename = "Reject")]
|
||||
Reject(RejectActivity),
|
||||
#[serde(rename = "Undo")]
|
||||
Undo(UndoActivity),
|
||||
#[serde(rename = "Create")]
|
||||
Create(CreateActivity),
|
||||
#[serde(rename = "Delete")]
|
||||
Delete(DeleteActivity),
|
||||
#[serde(rename = "Update")]
|
||||
Update(UpdateActivity),
|
||||
}
|
||||
21
crates/adapters/activitypub-base/src/actor_handler.rs
Normal file
21
crates/adapters/activitypub-base/src/actor_handler.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use activitypub_federation::{
|
||||
axum::json::FederationJson, config::Data, protocol::context::WithContext, traits::Object,
|
||||
};
|
||||
use axum::extract::Path;
|
||||
|
||||
use crate::actors::{get_local_actor, Person};
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
|
||||
pub async fn actor_handler(
|
||||
Path(user_id_str): Path<String>,
|
||||
data: Data<FederationData>,
|
||||
) -> Result<FederationJson<WithContext<Person>>, Error> {
|
||||
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||
|
||||
let db_actor = get_local_actor(uuid, &data).await?;
|
||||
let person = db_actor.into_json(&data).await?;
|
||||
|
||||
Ok(FederationJson(WithContext::new_default(person)))
|
||||
}
|
||||
230
crates/adapters/activitypub-base/src/actors.rs
Normal file
230
crates/adapters/activitypub-base/src/actors.rs
Normal file
@@ -0,0 +1,230 @@
|
||||
use activitypub_federation::{
|
||||
config::Data,
|
||||
fetch::object_id::ObjectId,
|
||||
http_signatures::generate_actor_keypair,
|
||||
kinds::actor::PersonType,
|
||||
protocol::{public_key::PublicKey, verification::verify_domains_match},
|
||||
traits::{Actor, Object},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
use crate::repository::RemoteActor;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DbActor {
|
||||
pub user_id: uuid::Uuid,
|
||||
pub username: String,
|
||||
pub public_key_pem: String,
|
||||
pub private_key_pem: Option<String>,
|
||||
pub inbox_url: Url,
|
||||
pub outbox_url: Url,
|
||||
pub followers_url: Url,
|
||||
pub following_url: Url,
|
||||
pub ap_id: Url,
|
||||
pub last_refreshed_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Person {
|
||||
#[serde(rename = "type")]
|
||||
kind: PersonType,
|
||||
id: ObjectId<DbActor>,
|
||||
preferred_username: String,
|
||||
inbox: Url,
|
||||
outbox: Url,
|
||||
followers: Url,
|
||||
following: Url,
|
||||
public_key: PublicKey,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn get_local_actor(
|
||||
user_id: uuid::Uuid,
|
||||
data: &Data<FederationData>,
|
||||
) -> Result<DbActor, Error> {
|
||||
let user = data
|
||||
.user_repo
|
||||
.find_by_id(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found: {}", user_id)))?;
|
||||
|
||||
let (public_key, private_key) = match data
|
||||
.federation_repo
|
||||
.get_local_actor_keypair(user_id)
|
||||
.await?
|
||||
{
|
||||
Some(kp) => kp,
|
||||
None => {
|
||||
let kp = generate_actor_keypair()?;
|
||||
data.federation_repo
|
||||
.save_local_actor_keypair(
|
||||
user_id,
|
||||
kp.public_key.clone(),
|
||||
kp.private_key.clone(),
|
||||
)
|
||||
.await?;
|
||||
(kp.public_key, kp.private_key)
|
||||
}
|
||||
};
|
||||
|
||||
let ap_id = crate::urls::actor_url(&data.base_url, user_id);
|
||||
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid inbox url");
|
||||
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid outbox url");
|
||||
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid followers url");
|
||||
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid following url");
|
||||
|
||||
Ok(DbActor {
|
||||
user_id,
|
||||
username: user.username,
|
||||
public_key_pem: public_key,
|
||||
private_key_pem: Some(private_key),
|
||||
inbox_url,
|
||||
outbox_url,
|
||||
followers_url,
|
||||
following_url,
|
||||
ap_id,
|
||||
last_refreshed_at: Utc::now(),
|
||||
})
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Object for DbActor {
|
||||
type DataType = FederationData;
|
||||
type Kind = Person;
|
||||
type Error = Error;
|
||||
|
||||
fn id(&self) -> &Url {
|
||||
&self.ap_id
|
||||
}
|
||||
|
||||
fn last_refreshed_at(&self) -> Option<DateTime<Utc>> {
|
||||
Some(self.last_refreshed_at)
|
||||
}
|
||||
|
||||
async fn read_from_id(
|
||||
object_id: Url,
|
||||
data: &Data<Self::DataType>,
|
||||
) -> Result<Option<Self>, Self::Error> {
|
||||
let user_id = match crate::urls::extract_user_id_from_url(&object_id) {
|
||||
Some(id) => id,
|
||||
None => return Ok(None),
|
||||
};
|
||||
let user = match data.user_repo.find_by_id(user_id).await {
|
||||
Ok(Some(u)) => u,
|
||||
_ => return Ok(None),
|
||||
};
|
||||
|
||||
let keypair = data
|
||||
.federation_repo
|
||||
.get_local_actor_keypair(user_id)
|
||||
.await?;
|
||||
|
||||
let (public_key, private_key) = match keypair {
|
||||
Some(kp) => (kp.0, Some(kp.1)),
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let ap_id = crate::urls::actor_url(&data.base_url, user_id);
|
||||
let inbox_url = Url::parse(&format!("{}/inbox", &ap_id)).expect("valid url");
|
||||
let outbox_url = Url::parse(&format!("{}/outbox", &ap_id)).expect("valid url");
|
||||
let followers_url = Url::parse(&format!("{}/followers", &ap_id)).expect("valid url");
|
||||
let following_url = Url::parse(&format!("{}/following", &ap_id)).expect("valid url");
|
||||
|
||||
Ok(Some(DbActor {
|
||||
user_id,
|
||||
username: user.username,
|
||||
public_key_pem: public_key,
|
||||
private_key_pem: private_key,
|
||||
inbox_url,
|
||||
outbox_url,
|
||||
followers_url,
|
||||
following_url,
|
||||
ap_id,
|
||||
last_refreshed_at: Utc::now(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn into_json(self, _data: &Data<Self::DataType>) -> Result<Self::Kind, Self::Error> {
|
||||
let public_key = PublicKey {
|
||||
id: format!("{}#main-key", &self.ap_id),
|
||||
owner: self.ap_id.clone(),
|
||||
public_key_pem: self.public_key_pem.clone(),
|
||||
};
|
||||
|
||||
Ok(Person {
|
||||
kind: Default::default(),
|
||||
id: self.ap_id.clone().into(),
|
||||
preferred_username: self.username.clone(),
|
||||
inbox: self.inbox_url.clone(),
|
||||
outbox: self.outbox_url.clone(),
|
||||
followers: self.followers_url.clone(),
|
||||
following: self.following_url.clone(),
|
||||
public_key,
|
||||
name: Some(self.username.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn verify(
|
||||
json: &Self::Kind,
|
||||
expected_domain: &Url,
|
||||
_data: &Data<Self::DataType>,
|
||||
) -> Result<(), Self::Error> {
|
||||
verify_domains_match(json.id.inner(), expected_domain)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn from_json(
|
||||
json: Self::Kind,
|
||||
data: &Data<Self::DataType>,
|
||||
) -> Result<Self, Self::Error> {
|
||||
let actor = RemoteActor {
|
||||
url: json.id.inner().to_string(),
|
||||
handle: json.preferred_username.clone(),
|
||||
inbox_url: json.inbox.to_string(),
|
||||
shared_inbox_url: None,
|
||||
display_name: json.name.clone(),
|
||||
};
|
||||
data.federation_repo.upsert_remote_actor(actor).await?;
|
||||
|
||||
let url_str = json.id.inner().to_string();
|
||||
let user_id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, url_str.as_bytes());
|
||||
let ap_id = json.id.inner().clone();
|
||||
let inbox_url = json.inbox.clone();
|
||||
let outbox_url = json.outbox.clone();
|
||||
let followers_url = json.followers.clone();
|
||||
let following_url = json.following.clone();
|
||||
|
||||
Ok(DbActor {
|
||||
user_id,
|
||||
username: json.preferred_username.clone(),
|
||||
public_key_pem: json.public_key.public_key_pem,
|
||||
private_key_pem: None,
|
||||
inbox_url,
|
||||
outbox_url,
|
||||
followers_url,
|
||||
following_url,
|
||||
ap_id,
|
||||
last_refreshed_at: Utc::now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for DbActor {
|
||||
fn public_key_pem(&self) -> &str {
|
||||
&self.public_key_pem
|
||||
}
|
||||
|
||||
fn private_key_pem(&self) -> Option<String> {
|
||||
self.private_key_pem.clone()
|
||||
}
|
||||
|
||||
fn inbox(&self) -> Url {
|
||||
self.inbox_url.clone()
|
||||
}
|
||||
}
|
||||
34
crates/adapters/activitypub-base/src/content.rs
Normal file
34
crates/adapters/activitypub-base/src/content.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use async_trait::async_trait;
|
||||
use url::Url;
|
||||
|
||||
#[async_trait]
|
||||
pub trait ApObjectHandler: Send + Sync {
|
||||
/// Returns (ap_id, serialized object) for all local content owned by this user.
|
||||
/// Used by outbox (count) and backfill (delivery). Must only return locally-authored content.
|
||||
async fn get_local_objects_for_user(
|
||||
&self,
|
||||
user_id: uuid::Uuid,
|
||||
) -> anyhow::Result<Vec<(Url, serde_json::Value)>>;
|
||||
|
||||
/// Incoming Create activity — persist remote content.
|
||||
async fn on_create(
|
||||
&self,
|
||||
ap_id: &Url,
|
||||
actor_url: &Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()>;
|
||||
|
||||
/// Incoming Update activity — update existing remote content.
|
||||
async fn on_update(
|
||||
&self,
|
||||
ap_id: &Url,
|
||||
actor_url: &Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()>;
|
||||
|
||||
/// Incoming Delete activity — remove specific remote content.
|
||||
async fn on_delete(&self, ap_id: &Url, actor_url: &Url) -> anyhow::Result<()>;
|
||||
|
||||
/// Actor unfollowed/was removed — clean up all their remote content.
|
||||
async fn on_actor_removed(&self, actor_url: &Url) -> anyhow::Result<()>;
|
||||
}
|
||||
38
crates/adapters/activitypub-base/src/data.rs
Normal file
38
crates/adapters/activitypub-base/src/data.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::content::ApObjectHandler;
|
||||
use crate::repository::FederationRepository;
|
||||
use crate::user::ApUserRepository;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FederationData {
|
||||
pub(crate) federation_repo: Arc<dyn FederationRepository>,
|
||||
pub(crate) user_repo: Arc<dyn ApUserRepository>,
|
||||
pub(crate) object_handler: Arc<dyn ApObjectHandler>,
|
||||
pub(crate) base_url: String,
|
||||
pub(crate) domain: String,
|
||||
}
|
||||
|
||||
impl FederationData {
|
||||
pub fn new(
|
||||
federation_repo: Arc<dyn FederationRepository>,
|
||||
user_repo: Arc<dyn ApUserRepository>,
|
||||
object_handler: Arc<dyn ApObjectHandler>,
|
||||
base_url: String,
|
||||
) -> Self {
|
||||
let domain = base_url
|
||||
.trim_start_matches("https://")
|
||||
.trim_start_matches("http://")
|
||||
.split('/')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
Self {
|
||||
federation_repo,
|
||||
user_repo,
|
||||
object_handler,
|
||||
base_url,
|
||||
domain,
|
||||
}
|
||||
}
|
||||
}
|
||||
48
crates/adapters/activitypub-base/src/error.rs
Normal file
48
crates/adapters/activitypub-base/src/error.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use axum::http::StatusCode;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error(pub(crate) anyhow::Error, pub(crate) StatusCode);
|
||||
|
||||
impl Error {
|
||||
pub fn not_found(e: impl Into<anyhow::Error>) -> Self {
|
||||
Self(e.into(), StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
pub fn bad_request(e: impl Into<anyhow::Error>) -> Self {
|
||||
Self(e.into(), StatusCode::BAD_REQUEST)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
std::fmt::Display::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for Error
|
||||
where
|
||||
T: Into<anyhow::Error>,
|
||||
{
|
||||
fn from(t: T) -> Self {
|
||||
Error(t.into(), StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
}
|
||||
|
||||
impl axum::response::IntoResponse for Error {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
let status = self.1;
|
||||
if status.is_server_error() {
|
||||
tracing::error!(error = %self.0, status = status.as_u16(), "federation error");
|
||||
} else {
|
||||
tracing::debug!(error = %self.0, status = status.as_u16(), "federation response");
|
||||
}
|
||||
let body = if status.is_server_error() {
|
||||
"internal server error".to_string()
|
||||
} else {
|
||||
self.0.to_string()
|
||||
};
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
50
crates/adapters/activitypub-base/src/federation.rs
Normal file
50
crates/adapters/activitypub-base/src/federation.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use activitypub_federation::config::{Data, FederationConfig, FederationMiddleware, UrlVerifier};
|
||||
use activitypub_federation::error::Error as FedError;
|
||||
use url::Url;
|
||||
|
||||
use crate::data::FederationData;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PermissiveVerifier;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UrlVerifier for PermissiveVerifier {
|
||||
async fn verify(&self, _url: &Url) -> Result<(), FedError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ApFederationConfig(pub FederationConfig<FederationData>);
|
||||
|
||||
impl ApFederationConfig {
|
||||
pub async fn new(data: FederationData, debug: bool) -> anyhow::Result<Self> {
|
||||
let config = if debug {
|
||||
FederationConfig::builder()
|
||||
.domain(&data.domain)
|
||||
.app_data(data)
|
||||
.debug(true)
|
||||
.http_signature_compat(true)
|
||||
.url_verifier(Box::new(PermissiveVerifier))
|
||||
.build()
|
||||
.await?
|
||||
} else {
|
||||
FederationConfig::builder()
|
||||
.domain(&data.domain)
|
||||
.app_data(data)
|
||||
.debug(false)
|
||||
.http_signature_compat(true)
|
||||
.build()
|
||||
.await?
|
||||
};
|
||||
Ok(Self(config))
|
||||
}
|
||||
|
||||
pub fn to_request_data(&self) -> Data<FederationData> {
|
||||
self.0.to_request_data()
|
||||
}
|
||||
|
||||
pub fn middleware(&self) -> FederationMiddleware<FederationData> {
|
||||
FederationMiddleware::new(self.0.clone())
|
||||
}
|
||||
}
|
||||
71
crates/adapters/activitypub-base/src/followers_handler.rs
Normal file
71
crates/adapters/activitypub-base/src/followers_handler.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||
use axum::extract::Path;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
use crate::repository::FollowerStatus;
|
||||
|
||||
fn ordered_collection(id: String, total: usize, items: Vec<String>) -> serde_json::Value {
|
||||
json!({
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"type": "OrderedCollection",
|
||||
"id": id,
|
||||
"totalItems": total,
|
||||
"orderedItems": items,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn followers_handler(
|
||||
Path(user_id_str): Path<String>,
|
||||
data: Data<FederationData>,
|
||||
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||
let user_id = uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||
|
||||
data.user_repo
|
||||
.find_by_id(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let followers = data
|
||||
.federation_repo
|
||||
.get_followers(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
||||
let items: Vec<String> = followers
|
||||
.into_iter()
|
||||
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||
.map(|f| f.actor.url)
|
||||
.collect();
|
||||
|
||||
let id = format!("{}/users/{}/followers", data.base_url, user_id_str);
|
||||
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||
}
|
||||
|
||||
pub async fn following_handler(
|
||||
Path(user_id_str): Path<String>,
|
||||
data: Data<FederationData>,
|
||||
) -> Result<FederationJson<serde_json::Value>, Error> {
|
||||
let user_id = uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||
|
||||
data.user_repo
|
||||
.find_by_id(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let following = data
|
||||
.federation_repo
|
||||
.get_following(user_id)
|
||||
.await
|
||||
.map_err(Error::from)?;
|
||||
|
||||
let items: Vec<String> = following.into_iter().map(|a| a.url).collect();
|
||||
|
||||
let id = format!("{}/users/{}/following", data.base_url, user_id_str);
|
||||
Ok(FederationJson(ordered_collection(id, items.len(), items)))
|
||||
}
|
||||
20
crates/adapters/activitypub-base/src/inbox.rs
Normal file
20
crates/adapters/activitypub-base/src/inbox.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use activitypub_federation::{
|
||||
axum::inbox::{receive_activity, ActivityData},
|
||||
config::Data,
|
||||
protocol::context::WithContext,
|
||||
};
|
||||
|
||||
use crate::activities::InboxActivities;
|
||||
use crate::actors::DbActor;
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
|
||||
pub async fn inbox_handler(
|
||||
data: Data<FederationData>,
|
||||
activity_data: ActivityData,
|
||||
) -> Result<(), Error> {
|
||||
receive_activity::<WithContext<InboxActivities>, DbActor, FederationData>(
|
||||
activity_data, &data,
|
||||
)
|
||||
.await
|
||||
}
|
||||
23
crates/adapters/activitypub-base/src/lib.rs
Normal file
23
crates/adapters/activitypub-base/src/lib.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
pub mod activities;
|
||||
pub mod actor_handler;
|
||||
pub mod actors;
|
||||
pub mod content;
|
||||
pub mod data;
|
||||
pub mod error;
|
||||
pub mod federation;
|
||||
pub mod followers_handler;
|
||||
pub mod inbox;
|
||||
pub mod outbox;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
pub mod user;
|
||||
pub mod webfinger;
|
||||
pub(crate) mod urls;
|
||||
|
||||
pub use content::ApObjectHandler;
|
||||
pub use data::FederationData;
|
||||
pub use error::Error;
|
||||
pub use federation::ApFederationConfig;
|
||||
pub use repository::{FederationRepository, Follower, FollowerStatus, FollowingStatus, RemoteActor};
|
||||
pub use service::ActivityPubService;
|
||||
pub use user::{ApUser, ApUserRepository};
|
||||
48
crates/adapters/activitypub-base/src/outbox.rs
Normal file
48
crates/adapters/activitypub-base/src/outbox.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use activitypub_federation::{axum::json::FederationJson, config::Data};
|
||||
use axum::extract::Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OrderedCollection {
|
||||
#[serde(rename = "@context")]
|
||||
context: String,
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
id: String,
|
||||
total_items: u64,
|
||||
ordered_items: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
pub async fn outbox_handler(
|
||||
Path(user_id_str): Path<String>,
|
||||
data: Data<FederationData>,
|
||||
) -> Result<FederationJson<OrderedCollection>, Error> {
|
||||
let uuid = uuid::Uuid::parse_str(&user_id_str)
|
||||
.map_err(|_| Error::bad_request(anyhow::anyhow!("invalid user id")))?;
|
||||
|
||||
data.user_repo
|
||||
.find_by_id(uuid)
|
||||
.await
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let objects = data
|
||||
.object_handler
|
||||
.get_local_objects_for_user(uuid)
|
||||
.await
|
||||
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||
|
||||
let outbox_url = format!("{}/users/{}/outbox", data.base_url, user_id_str);
|
||||
|
||||
Ok(FederationJson(OrderedCollection {
|
||||
context: "https://www.w3.org/ns/activitystreams".to_string(),
|
||||
kind: "OrderedCollection".to_string(),
|
||||
id: outbox_url,
|
||||
total_items: objects.len() as u64,
|
||||
ordered_items: vec![],
|
||||
}))
|
||||
}
|
||||
50
crates/adapters/activitypub-base/src/repository.rs
Normal file
50
crates/adapters/activitypub-base/src/repository.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FollowerStatus {
|
||||
Pending,
|
||||
Accepted,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FollowingStatus {
|
||||
Pending,
|
||||
Accepted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemoteActor {
|
||||
pub url: String,
|
||||
pub handle: String,
|
||||
pub inbox_url: String,
|
||||
pub shared_inbox_url: Option<String>,
|
||||
pub display_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Follower {
|
||||
pub actor: RemoteActor,
|
||||
pub status: FollowerStatus,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait FederationRepository: Send + Sync {
|
||||
async fn add_follower(&self, local_user_id: uuid::Uuid, remote_actor_url: &str, status: FollowerStatus, follow_activity_id: &str) -> Result<()>;
|
||||
async fn get_follower_follow_activity_id(&self, local_user_id: uuid::Uuid, remote_actor_url: &str) -> Result<Option<String>>;
|
||||
async fn remove_follower(&self, local_user_id: uuid::Uuid, remote_actor_url: &str) -> Result<()>;
|
||||
async fn get_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<Follower>>;
|
||||
async fn update_follower_status(&self, local_user_id: uuid::Uuid, remote_actor_url: &str, status: FollowerStatus) -> Result<()>;
|
||||
async fn add_following(&self, local_user_id: uuid::Uuid, actor: RemoteActor, follow_activity_id: &str) -> Result<()>;
|
||||
async fn get_follow_activity_id(&self, local_user_id: uuid::Uuid, remote_actor_url: &str) -> Result<Option<String>>;
|
||||
async fn remove_following(&self, local_user_id: uuid::Uuid, actor_url: &str) -> Result<()>;
|
||||
async fn get_following(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>>;
|
||||
async fn count_following(&self, local_user_id: uuid::Uuid) -> Result<usize>;
|
||||
async fn upsert_remote_actor(&self, actor: RemoteActor) -> Result<()>;
|
||||
async fn get_remote_actor(&self, actor_url: &str) -> Result<Option<RemoteActor>>;
|
||||
async fn get_local_actor_keypair(&self, user_id: uuid::Uuid) -> Result<Option<(String, String)>>;
|
||||
async fn save_local_actor_keypair(&self, user_id: uuid::Uuid, public_key: String, private_key: String) -> Result<()>;
|
||||
async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> Result<Vec<RemoteActor>>;
|
||||
async fn update_following_status(&self, local_user_id: uuid::Uuid, remote_actor_url: &str, status: FollowingStatus) -> Result<()>;
|
||||
}
|
||||
470
crates/adapters/activitypub-base/src/service.rs
Normal file
470
crates/adapters/activitypub-base/src/service.rs
Normal file
@@ -0,0 +1,470 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use activitypub_federation::{
|
||||
activity_sending::SendActivityTask,
|
||||
fetch::{object_id::ObjectId, webfinger::webfinger_resolve_actor},
|
||||
protocol::context::WithContext,
|
||||
traits::Actor,
|
||||
};
|
||||
use axum::{routing::get, routing::post, Router};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
activities::{AcceptActivity, CreateActivity, FollowActivity, RejectActivity, UndoActivity},
|
||||
actor_handler::actor_handler,
|
||||
actors::{get_local_actor, DbActor},
|
||||
content::ApObjectHandler,
|
||||
data::FederationData,
|
||||
federation::ApFederationConfig,
|
||||
followers_handler::{followers_handler, following_handler},
|
||||
inbox::inbox_handler,
|
||||
outbox::outbox_handler,
|
||||
repository::{FederationRepository, FollowerStatus, RemoteActor},
|
||||
user::ApUserRepository,
|
||||
urls::activity_url,
|
||||
webfinger::webfinger_handler,
|
||||
};
|
||||
|
||||
pub(crate) async fn send_with_retry(
|
||||
sends: Vec<SendActivityTask>,
|
||||
data: &activitypub_federation::config::Data<FederationData>,
|
||||
) -> Vec<anyhow::Error> {
|
||||
let mut failures = vec![];
|
||||
for send in sends {
|
||||
let mut delay = std::time::Duration::from_secs(1);
|
||||
for attempt in 1..=3u32 {
|
||||
match send.clone().sign_and_send(data).await {
|
||||
Ok(()) => break,
|
||||
Err(e) if attempt < 3 => {
|
||||
tracing::warn!(attempt, error = %e, "delivery failed, retrying");
|
||||
tokio::time::sleep(delay).await;
|
||||
delay *= 2;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(attempt, error = %e, "delivery failed permanently");
|
||||
failures.push(anyhow::anyhow!(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
failures
|
||||
}
|
||||
|
||||
pub struct ActivityPubService {
|
||||
federation_config: ApFederationConfig,
|
||||
base_url: String,
|
||||
}
|
||||
|
||||
impl ActivityPubService {
|
||||
pub async fn new(
|
||||
repo: Arc<dyn FederationRepository>,
|
||||
user_repo: Arc<dyn ApUserRepository>,
|
||||
object_handler: Arc<dyn ApObjectHandler>,
|
||||
base_url: String,
|
||||
debug: bool,
|
||||
) -> anyhow::Result<Self> {
|
||||
let data = FederationData::new(repo, user_repo, object_handler, base_url.clone());
|
||||
let federation_config = ApFederationConfig::new(data, debug).await?;
|
||||
Ok(Self { federation_config, base_url })
|
||||
}
|
||||
|
||||
pub fn federation_config(&self) -> &ApFederationConfig {
|
||||
&self.federation_config
|
||||
}
|
||||
|
||||
pub fn request_data(&self) -> activitypub_federation::config::Data<FederationData> {
|
||||
self.federation_config.to_request_data()
|
||||
}
|
||||
|
||||
pub async fn actor_json(&self, user_id_str: &str) -> anyhow::Result<String> {
|
||||
use activitypub_federation::traits::Object;
|
||||
let uuid = uuid::Uuid::parse_str(user_id_str)?;
|
||||
let data = self.federation_config.to_request_data();
|
||||
let actor = get_local_actor(uuid, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let person = actor.into_json(&data).await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
Ok(serde_json::to_string(&WithContext::new_default(person))?)
|
||||
}
|
||||
|
||||
pub fn router(&self) -> Router {
|
||||
Router::new()
|
||||
.route("/.well-known/webfinger", get(webfinger_handler))
|
||||
.route("/users/{user_id}", get(actor_handler))
|
||||
.route("/users/{user_id}/inbox", post(inbox_handler))
|
||||
.route("/users/{user_id}/outbox", get(outbox_handler))
|
||||
.route("/users/{user_id}/followers", get(followers_handler))
|
||||
.route("/users/{user_id}/following", get(following_handler))
|
||||
.layer(self.federation_config.middleware())
|
||||
}
|
||||
|
||||
pub async fn follow(&self, local_user_id: uuid::Uuid, handle: &str) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
|
||||
let remote_actor: DbActor = webfinger_resolve_actor(handle, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let local_actor = get_local_actor(local_user_id, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let follow_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let follow_id_str = follow_id.to_string();
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: ObjectId::from(remote_actor.ap_id.clone()),
|
||||
};
|
||||
let follow_with_ctx = WithContext::new_default(follow);
|
||||
|
||||
let sends = SendActivityTask::prepare(
|
||||
&follow_with_ctx,
|
||||
&local_actor,
|
||||
vec![remote_actor.inbox()],
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
let remote = RemoteActor {
|
||||
url: remote_actor.ap_id.to_string(),
|
||||
handle: remote_actor.username.clone(),
|
||||
inbox_url: remote_actor.inbox_url.to_string(),
|
||||
shared_inbox_url: None,
|
||||
display_name: Some(remote_actor.username.clone()),
|
||||
};
|
||||
data.federation_repo
|
||||
.add_following(local_user_id, remote, &follow_id_str)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn unfollow(&self, local_user_id: uuid::Uuid, actor_url_str: &str) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
|
||||
let remote = data
|
||||
.federation_repo
|
||||
.get_remote_actor(actor_url_str)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("remote actor not found: {}", actor_url_str))?;
|
||||
|
||||
let local_actor = get_local_actor(local_user_id, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let remote_ap_id = Url::parse(actor_url_str)?;
|
||||
let inbox = Url::parse(&remote.inbox_url)?;
|
||||
|
||||
let follow_activity_id_str = data
|
||||
.federation_repo
|
||||
.get_follow_activity_id(local_user_id, actor_url_str)
|
||||
.await?;
|
||||
let follow_id = match follow_activity_id_str {
|
||||
Some(id) => Url::parse(&id)?,
|
||||
None => activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||
};
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: ObjectId::from(remote_ap_id),
|
||||
};
|
||||
|
||||
let undo_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let undo = UndoActivity {
|
||||
id: undo_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: follow,
|
||||
};
|
||||
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(undo),
|
||||
&local_actor,
|
||||
vec![inbox],
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
data.federation_repo
|
||||
.remove_following(local_user_id, actor_url_str)
|
||||
.await?;
|
||||
|
||||
data.object_handler
|
||||
.on_actor_removed(&Url::parse(actor_url_str)?)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn accept_follower(
|
||||
&self,
|
||||
local_user_id: uuid::Uuid,
|
||||
remote_actor_url: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let local_actor = get_local_actor(local_user_id, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let remote_actor = data
|
||||
.federation_repo
|
||||
.get_remote_actor(remote_actor_url)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||
|
||||
let follow_id_str = data
|
||||
.federation_repo
|
||||
.get_follower_follow_activity_id(local_user_id, remote_actor_url)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("follow activity id not found for {}", remote_actor_url))?;
|
||||
let follow_id = Url::parse(&follow_id_str)?;
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||
};
|
||||
let accept = AcceptActivity {
|
||||
id: activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: follow,
|
||||
};
|
||||
|
||||
data.federation_repo
|
||||
.update_follower_status(local_user_id, remote_actor_url, FollowerStatus::Accepted)
|
||||
.await?;
|
||||
|
||||
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(accept),
|
||||
&local_actor,
|
||||
vec![inbox.clone()],
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!("failed to deliver Accept activity, but follower is marked accepted locally");
|
||||
}
|
||||
|
||||
self.spawn_backfill(local_user_id, remote_actor.inbox_url.clone());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn reject_follower(
|
||||
&self,
|
||||
local_user_id: uuid::Uuid,
|
||||
remote_actor_url: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let local_actor = get_local_actor(local_user_id, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let remote_actor = data
|
||||
.federation_repo
|
||||
.get_remote_actor(remote_actor_url)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("remote actor not found"))?;
|
||||
|
||||
let follow_id = activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let follow = FollowActivity {
|
||||
id: follow_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(Url::parse(remote_actor_url)?),
|
||||
object: ObjectId::from(local_actor.ap_id.clone()),
|
||||
};
|
||||
let reject = RejectActivity {
|
||||
id: activity_url(&self.base_url).map_err(|e| anyhow::anyhow!("{e}"))?,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: follow,
|
||||
};
|
||||
|
||||
let inbox = Url::parse(&remote_actor.inbox_url)?;
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(reject),
|
||||
&local_actor,
|
||||
vec![inbox],
|
||||
&data,
|
||||
)
|
||||
.await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
data.federation_repo
|
||||
.remove_follower(local_user_id, remote_actor_url)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_pending_followers(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
data.federation_repo.get_pending_followers(local_user_id).await
|
||||
}
|
||||
|
||||
pub async fn get_accepted_followers(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||
Ok(followers
|
||||
.into_iter()
|
||||
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||
.map(|f| f.actor)
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn count_accepted_followers(&self, local_user_id: uuid::Uuid) -> anyhow::Result<usize> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||
Ok(followers.into_iter().filter(|f| f.status == FollowerStatus::Accepted).count())
|
||||
}
|
||||
|
||||
pub async fn get_following(&self, local_user_id: uuid::Uuid) -> anyhow::Result<Vec<RemoteActor>> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
data.federation_repo.get_following(local_user_id).await
|
||||
}
|
||||
|
||||
pub async fn count_following(&self, local_user_id: uuid::Uuid) -> anyhow::Result<usize> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
data.federation_repo.count_following(local_user_id).await
|
||||
}
|
||||
|
||||
pub async fn remove_follower(&self, local_user_id: uuid::Uuid, actor_url: &str) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
data.federation_repo.remove_follower(local_user_id, actor_url).await
|
||||
}
|
||||
|
||||
/// Broadcast a single object to all accepted followers as a Create activity.
|
||||
/// Called by project-specific event handlers when new content is created.
|
||||
pub async fn broadcast_to_followers(
|
||||
&self,
|
||||
local_user_id: uuid::Uuid,
|
||||
ap_id: Url,
|
||||
object: serde_json::Value,
|
||||
) -> anyhow::Result<()> {
|
||||
let data = self.federation_config.to_request_data();
|
||||
let local_actor = get_local_actor(local_user_id, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
|
||||
let followers = data.federation_repo.get_followers(local_user_id).await?;
|
||||
let accepted: Vec<_> = followers
|
||||
.into_iter()
|
||||
.filter(|f| f.status == FollowerStatus::Accepted)
|
||||
.collect();
|
||||
|
||||
if accepted.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let create = CreateActivity {
|
||||
id: ap_id.clone(),
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object,
|
||||
};
|
||||
let create_with_ctx = WithContext::new_default(create);
|
||||
|
||||
let inboxes: Vec<Url> = accepted
|
||||
.iter()
|
||||
.filter_map(|f| Url::parse(&f.actor.inbox_url).ok())
|
||||
.collect();
|
||||
|
||||
let sends = SendActivityTask::prepare(&create_with_ctx, &local_actor, inboxes, &data).await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if !failures.is_empty() {
|
||||
tracing::warn!(count = failures.len(), "some activity deliveries failed permanently");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn spawn_backfill(&self, owner_user_id: uuid::Uuid, follower_inbox_url: String) {
|
||||
let config = self.federation_config.clone();
|
||||
let base_url = self.base_url.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = ActivityPubService::run_backfill(config, base_url, owner_user_id, follower_inbox_url).await {
|
||||
tracing::warn!(error = %e, "backfill: task failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn run_backfill(
|
||||
config: ApFederationConfig,
|
||||
base_url: String,
|
||||
owner_user_id: uuid::Uuid,
|
||||
follower_inbox_url: String,
|
||||
) -> anyhow::Result<()> {
|
||||
const BATCH_SIZE: usize = 20;
|
||||
|
||||
let data = config.to_request_data();
|
||||
let local_actor = get_local_actor(owner_user_id, &data)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||
let inbox = Url::parse(&follower_inbox_url)?;
|
||||
|
||||
let mut objects = data.object_handler.get_local_objects_for_user(owner_user_id).await?;
|
||||
objects.reverse(); // oldest first → chronological feed
|
||||
|
||||
let total = objects.len();
|
||||
let mut success_count = 0usize;
|
||||
let mut failure_count = 0usize;
|
||||
|
||||
for chunk in objects.chunks(BATCH_SIZE) {
|
||||
for (ap_id, object_json) in chunk {
|
||||
// Use a stable Create activity ID derived from the object's ap_id
|
||||
let create_id = Url::parse(&format!("{}/activities/create/{}", base_url,
|
||||
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, ap_id.as_str().as_bytes())
|
||||
))?;
|
||||
|
||||
let create = CreateActivity {
|
||||
id: create_id,
|
||||
kind: Default::default(),
|
||||
actor: ObjectId::from(local_actor.ap_id.clone()),
|
||||
object: object_json.clone(),
|
||||
};
|
||||
|
||||
let sends = SendActivityTask::prepare(
|
||||
&WithContext::new_default(create),
|
||||
&local_actor,
|
||||
vec![inbox.clone()],
|
||||
&data,
|
||||
).await?;
|
||||
let failures = send_with_retry(sends, &data).await;
|
||||
if failures.is_empty() {
|
||||
success_count += 1;
|
||||
} else {
|
||||
failure_count += 1;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
user_id = %owner_user_id,
|
||||
follower = %follower_inbox_url,
|
||||
sent = success_count,
|
||||
failed = failure_count,
|
||||
total = total,
|
||||
"backfill complete"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
20
crates/adapters/activitypub-base/src/urls.rs
Normal file
20
crates/adapters/activitypub-base/src/urls.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use url::Url;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
pub fn extract_user_id_from_url(url: &Url) -> Option<uuid::Uuid> {
|
||||
let path = url.path();
|
||||
path.strip_prefix("/users/")
|
||||
.and_then(|s| s.split('/').next())
|
||||
.and_then(|s| uuid::Uuid::parse_str(s).ok())
|
||||
}
|
||||
|
||||
pub fn activity_url(base_url: &str) -> Result<Url, Error> {
|
||||
Url::parse(&format!("{}/activities/{}", base_url, uuid::Uuid::new_v4()))
|
||||
.map_err(|e| Error::bad_request(anyhow::anyhow!(e)))
|
||||
}
|
||||
|
||||
pub fn actor_url(base_url: &str, user_id: uuid::Uuid) -> Url {
|
||||
Url::parse(&format!("{}/users/{}", base_url, user_id))
|
||||
.expect("base_url is always a valid URL prefix")
|
||||
}
|
||||
13
crates/adapters/activitypub-base/src/user.rs
Normal file
13
crates/adapters/activitypub-base/src/user.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApUser {
|
||||
pub id: uuid::Uuid,
|
||||
pub username: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ApUserRepository: Send + Sync {
|
||||
async fn find_by_id(&self, id: uuid::Uuid) -> anyhow::Result<Option<ApUser>>;
|
||||
async fn find_by_username(&self, username: &str) -> anyhow::Result<Option<ApUser>>;
|
||||
}
|
||||
42
crates/adapters/activitypub-base/src/webfinger.rs
Normal file
42
crates/adapters/activitypub-base/src/webfinger.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use activitypub_federation::{
|
||||
config::Data,
|
||||
fetch::webfinger::{build_webfinger_response, extract_webfinger_name, Webfinger},
|
||||
};
|
||||
use axum::{
|
||||
extract::Query,
|
||||
http::header,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::data::FederationData;
|
||||
use crate::error::Error;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct WebfingerQuery {
|
||||
resource: String,
|
||||
}
|
||||
|
||||
pub async fn webfinger_handler(
|
||||
Query(query): Query<WebfingerQuery>,
|
||||
data: Data<FederationData>,
|
||||
) -> Result<Response, Error> {
|
||||
let name = extract_webfinger_name(&query.resource, &data)?;
|
||||
|
||||
let user = data
|
||||
.user_repo
|
||||
.find_by_username(name)
|
||||
.await
|
||||
.map_err(Error::from)?
|
||||
.ok_or_else(|| Error::not_found(anyhow::anyhow!("user not found")))?;
|
||||
|
||||
let ap_id = crate::urls::actor_url(&data.base_url, user.id);
|
||||
|
||||
let wf: Webfinger = build_webfinger_response(query.resource, ap_id);
|
||||
let body = serde_json::to_string(&wf)
|
||||
.map_err(|e| Error::from(anyhow::anyhow!(e)))?;
|
||||
Ok((
|
||||
[(header::CONTENT_TYPE, "application/jrd+json")],
|
||||
body,
|
||||
).into_response())
|
||||
}
|
||||
Reference in New Issue
Block a user