1 use crate::error::{LemmyError, LemmyResult};
2 use itertools::Itertools;
3 use once_cell::sync::Lazy;
5 use totp_rs::{Secret, TOTP};
8 static VALID_ACTOR_NAME_REGEX: Lazy<Regex> =
9 Lazy::new(|| Regex::new(r"^[a-zA-Z0-9_]{3,}$").expect("compile regex"));
10 static VALID_POST_TITLE_REGEX: Lazy<Regex> =
11 Lazy::new(|| Regex::new(r".*\S{3,}.*").expect("compile regex"));
12 static VALID_MATRIX_ID_REGEX: Lazy<Regex> = Lazy::new(|| {
13 Regex::new(r"^@[A-Za-z0-9._=-]+:[A-Za-z0-9.-]+\.[A-Za-z]{2,}$").expect("compile regex")
15 // taken from https://en.wikipedia.org/wiki/UTM_parameters
16 static CLEAN_URL_PARAMS_REGEX: Lazy<Regex> = Lazy::new(|| {
17 Regex::new(r"^utm_source|utm_medium|utm_campaign|utm_term|utm_content|gclid|gclsrc|dclid|fbclid$")
18 .expect("compile regex")
20 const BODY_MAX_LENGTH: usize = 10000;
21 const BIO_MAX_LENGTH: usize = 300;
23 fn has_newline(name: &str) -> bool {
27 pub fn is_valid_actor_name(name: &str, actor_name_max_length: usize) -> LemmyResult<()> {
28 let check = name.chars().count() <= actor_name_max_length
29 && VALID_ACTOR_NAME_REGEX.is_match(name)
30 && !has_newline(name);
32 Err(LemmyError::from_message("invalid_name"))
38 // Can't do a regex here, reverse lookarounds not supported
39 pub fn is_valid_display_name(name: &str, actor_name_max_length: usize) -> LemmyResult<()> {
40 let check = !name.starts_with('@')
41 && !name.starts_with('\u{200b}')
42 && name.chars().count() >= 3
43 && name.chars().count() <= actor_name_max_length
44 && !has_newline(name);
46 Err(LemmyError::from_message("invalid_username"))
52 pub fn is_valid_matrix_id(matrix_id: &str) -> LemmyResult<()> {
53 let check = VALID_MATRIX_ID_REGEX.is_match(matrix_id) && !has_newline(matrix_id);
55 Err(LemmyError::from_message("invalid_matrix_id"))
61 pub fn is_valid_post_title(title: &str) -> LemmyResult<()> {
62 let check = VALID_POST_TITLE_REGEX.is_match(title) && !has_newline(title);
64 Err(LemmyError::from_message("invalid_post_title"))
70 /// This could be post bodies, comments, or any description field
71 pub fn is_valid_body_field(body: &Option<String>) -> LemmyResult<()> {
72 if let Some(body) = body {
73 let check = body.chars().count() <= BODY_MAX_LENGTH;
75 Err(LemmyError::from_message("invalid_body_field"))
84 pub fn is_valid_bio_field(bio: &str) -> LemmyResult<()> {
85 let check = bio.chars().count() <= BIO_MAX_LENGTH;
87 Err(LemmyError::from_message("bio_length_overflow"))
93 pub fn clean_url_params(url: &Url) -> Url {
94 let mut url_out = url.clone();
95 if url.query().is_some() {
98 .filter(|q| !CLEAN_URL_PARAMS_REGEX.is_match(&q.0))
99 .map(|q| format!("{}={}", q.0, q.1))
101 url_out.set_query(Some(&new_query));
106 pub fn check_totp_2fa_valid(
107 totp_secret: &Option<String>,
108 totp_token: &Option<String>,
111 ) -> LemmyResult<()> {
112 // Check only if they have a totp_secret in the DB
113 if let Some(totp_secret) = totp_secret {
114 // Throw an error if their token is missing
115 let token = totp_token
117 .ok_or_else(|| LemmyError::from_message("missing_totp_token"))?;
119 let totp = build_totp_2fa(site_name, username, totp_secret)?;
121 let check_passed = totp.check_current(token)?;
123 return Err(LemmyError::from_message("incorrect_totp token"));
130 pub fn generate_totp_2fa_secret() -> String {
131 Secret::generate_secret().to_string()
134 pub fn build_totp_2fa(site_name: &str, username: &str, secret: &str) -> Result<TOTP, LemmyError> {
135 let sec = Secret::Raw(secret.as_bytes().to_vec());
138 .map_err(|_| LemmyError::from_message("Couldnt parse totp secret"))?;
141 totp_rs::Algorithm::SHA256,
146 Some(site_name.to_string()),
147 username.to_string(),
149 .map_err(|e| LemmyError::from_error_message(e, "Couldnt generate TOTP"))
154 use super::build_totp_2fa;
155 use crate::utils::validation::{
157 generate_totp_2fa_secret,
159 is_valid_display_name,
166 fn test_clean_url_params() {
167 let url = Url::parse("https://example.com/path/123?utm_content=buffercf3b2&utm_medium=social&username=randomuser&id=123").unwrap();
168 let cleaned = clean_url_params(&url);
169 let expected = Url::parse("https://example.com/path/123?username=randomuser&id=123").unwrap();
170 assert_eq!(expected.to_string(), cleaned.to_string());
172 let url = Url::parse("https://example.com/path/123").unwrap();
173 let cleaned = clean_url_params(&url);
174 assert_eq!(url.to_string(), cleaned.to_string());
179 assert!(is_valid_post_title("hi").is_err());
180 assert!(is_valid_post_title("him").is_ok());
181 assert!(is_valid_post_title("n\n\n\n\nanother").is_err());
182 assert!(is_valid_post_title("hello there!\n this is a test.").is_err());
183 assert!(is_valid_post_title("hello there! this is a test.").is_ok());
187 fn test_valid_actor_name() {
188 let actor_name_max_length = 20;
189 assert!(is_valid_actor_name("Hello_98", actor_name_max_length).is_ok());
190 assert!(is_valid_actor_name("ten", actor_name_max_length).is_ok());
191 assert!(is_valid_actor_name("Hello-98", actor_name_max_length).is_err());
192 assert!(is_valid_actor_name("a", actor_name_max_length).is_err());
193 assert!(is_valid_actor_name("", actor_name_max_length).is_err());
197 fn test_valid_display_name() {
198 let actor_name_max_length = 20;
199 assert!(is_valid_display_name("hello @there", actor_name_max_length).is_ok());
200 assert!(is_valid_display_name("@hello there", actor_name_max_length).is_err());
202 // Make sure zero-space with an @ doesn't work
204 is_valid_display_name(&format!("{}@my name is", '\u{200b}'), actor_name_max_length).is_err()
209 fn test_valid_post_title() {
210 assert!(is_valid_post_title("Post Title").is_ok());
211 assert!(is_valid_post_title(" POST TITLE 😃😃😃😃😃").is_ok());
212 assert!(is_valid_post_title("\n \n \n \n ").is_err()); // tabs/spaces/newlines
216 fn test_valid_matrix_id() {
217 assert!(is_valid_matrix_id("@dess:matrix.org").is_ok());
218 assert!(is_valid_matrix_id("dess:matrix.org").is_err());
219 assert!(is_valid_matrix_id(" @dess:matrix.org").is_err());
220 assert!(is_valid_matrix_id("@dess:matrix.org t").is_err());
224 fn test_build_totp() {
225 let generated_secret = generate_totp_2fa_secret();
226 let totp = build_totp_2fa("lemmy", "my_name", &generated_secret);
227 assert!(totp.is_ok());