]> Untitled Git - lemmy.git/blob - lemmy_utils/src/apub.rs
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / lemmy_utils / src / apub.rs
1 use crate::settings::Settings;
2 use openssl::{pkey::PKey, rsa::Rsa};
3 use std::io::{Error, ErrorKind};
4 use url::Url;
5
6 pub struct Keypair {
7   pub private_key: String,
8   pub public_key: String,
9 }
10
11 /// Generate the asymmetric keypair for ActivityPub HTTP signatures.
12 pub fn generate_actor_keypair() -> Result<Keypair, Error> {
13   let rsa = Rsa::generate(2048)?;
14   let pkey = PKey::from_rsa(rsa)?;
15   let public_key = pkey.public_key_to_pem()?;
16   let private_key = pkey.private_key_to_pem_pkcs8()?;
17   let key_to_string = |key| match String::from_utf8(key) {
18     Ok(s) => Ok(s),
19     Err(e) => Err(Error::new(
20       ErrorKind::Other,
21       format!("Failed converting key to string: {}", e),
22     )),
23   };
24   Ok(Keypair {
25     private_key: key_to_string(private_key)?,
26     public_key: key_to_string(public_key)?,
27   })
28 }
29
30 pub enum EndpointType {
31   Community,
32   User,
33   Post,
34   Comment,
35   PrivateMessage,
36 }
37
38 pub fn get_apub_protocol_string() -> &'static str {
39   if Settings::get().federation.tls_enabled {
40     "https"
41   } else {
42     "http"
43   }
44 }
45
46 /// Generates the ActivityPub ID for a given object type and ID.
47 pub fn make_apub_endpoint(endpoint_type: EndpointType, name: &str) -> Url {
48   let point = match endpoint_type {
49     EndpointType::Community => "c",
50     EndpointType::User => "u",
51     EndpointType::Post => "post",
52     EndpointType::Comment => "comment",
53     EndpointType::PrivateMessage => "private_message",
54   };
55
56   Url::parse(&format!(
57     "{}://{}/{}/{}",
58     get_apub_protocol_string(),
59     Settings::get().hostname,
60     point,
61     name
62   ))
63   .unwrap()
64 }