1 use crate::error::LemmyError;
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")
21 fn has_newline(name: &str) -> bool {
25 pub fn is_valid_actor_name(name: &str, actor_name_max_length: usize) -> bool {
26 name.chars().count() <= actor_name_max_length
27 && VALID_ACTOR_NAME_REGEX.is_match(name)
31 // Can't do a regex here, reverse lookarounds not supported
32 pub fn is_valid_display_name(name: &str, actor_name_max_length: usize) -> bool {
33 !name.starts_with('@')
34 && !name.starts_with('\u{200b}')
35 && name.chars().count() >= 3
36 && name.chars().count() <= actor_name_max_length
40 pub fn is_valid_matrix_id(matrix_id: &str) -> bool {
41 VALID_MATRIX_ID_REGEX.is_match(matrix_id) && !has_newline(matrix_id)
44 pub fn is_valid_post_title(title: &str) -> bool {
45 VALID_POST_TITLE_REGEX.is_match(title) && !has_newline(title)
48 pub fn clean_url_params(url: &Url) -> Url {
49 let mut url_out = url.clone();
50 if url.query().is_some() {
53 .filter(|q| !CLEAN_URL_PARAMS_REGEX.is_match(&q.0))
54 .map(|q| format!("{}={}", q.0, q.1))
56 url_out.set_query(Some(&new_query));
61 pub fn check_totp_2fa_valid(
62 totp_secret: &Option<String>,
63 totp_token: &Option<String>,
66 ) -> Result<(), LemmyError> {
67 // Check only if they have a totp_secret in the DB
68 if let Some(totp_secret) = totp_secret {
69 // Throw an error if their token is missing
70 let token = totp_token
72 .ok_or_else(|| LemmyError::from_message("missing_totp_token"))?;
74 let totp = build_totp_2fa(site_name, username, totp_secret)?;
76 let check_passed = totp.check_current(token)?;
78 return Err(LemmyError::from_message("incorrect_totp token"));
85 pub fn generate_totp_2fa_secret() -> String {
86 Secret::generate_secret().to_string()
89 pub fn build_totp_2fa(site_name: &str, username: &str, secret: &str) -> Result<TOTP, LemmyError> {
90 let sec = Secret::Raw(secret.as_bytes().to_vec());
93 .map_err(|_| LemmyError::from_message("Couldnt parse totp secret"))?;
96 totp_rs::Algorithm::SHA256,
101 Some(site_name.to_string()),
102 username.to_string(),
104 .map_err(|e| LemmyError::from_error_message(e, "Couldnt generate TOTP"))
109 use super::build_totp_2fa;
110 use crate::utils::validation::{
112 generate_totp_2fa_secret,
114 is_valid_display_name,
121 fn test_clean_url_params() {
122 let url = Url::parse("https://example.com/path/123?utm_content=buffercf3b2&utm_medium=social&username=randomuser&id=123").unwrap();
123 let cleaned = clean_url_params(&url);
124 let expected = Url::parse("https://example.com/path/123?username=randomuser&id=123").unwrap();
125 assert_eq!(expected.to_string(), cleaned.to_string());
127 let url = Url::parse("https://example.com/path/123").unwrap();
128 let cleaned = clean_url_params(&url);
129 assert_eq!(url.to_string(), cleaned.to_string());
134 assert!(!is_valid_post_title("hi"));
135 assert!(is_valid_post_title("him"));
136 assert!(!is_valid_post_title("n\n\n\n\nanother"));
137 assert!(!is_valid_post_title("hello there!\n this is a test."));
138 assert!(is_valid_post_title("hello there! this is a test."));
142 fn test_valid_actor_name() {
143 let actor_name_max_length = 20;
144 assert!(is_valid_actor_name("Hello_98", actor_name_max_length));
145 assert!(is_valid_actor_name("ten", actor_name_max_length));
146 assert!(!is_valid_actor_name("Hello-98", actor_name_max_length));
147 assert!(!is_valid_actor_name("a", actor_name_max_length));
148 assert!(!is_valid_actor_name("", actor_name_max_length));
152 fn test_valid_display_name() {
153 let actor_name_max_length = 20;
154 assert!(is_valid_display_name("hello @there", actor_name_max_length));
155 assert!(!is_valid_display_name(
157 actor_name_max_length
160 // Make sure zero-space with an @ doesn't work
161 assert!(!is_valid_display_name(
162 &format!("{}@my name is", '\u{200b}'),
163 actor_name_max_length
168 fn test_valid_post_title() {
169 assert!(is_valid_post_title("Post Title"));
170 assert!(is_valid_post_title(" POST TITLE 😃😃😃😃😃"));
171 assert!(!is_valid_post_title("\n \n \n \n ")); // tabs/spaces/newlines
175 fn test_valid_matrix_id() {
176 assert!(is_valid_matrix_id("@dess:matrix.org"));
177 assert!(!is_valid_matrix_id("dess:matrix.org"));
178 assert!(!is_valid_matrix_id(" @dess:matrix.org"));
179 assert!(!is_valid_matrix_id("@dess:matrix.org t"));
183 fn test_build_totp() {
184 let generated_secret = generate_totp_2fa_secret();
185 let totp = build_totp_2fa("lemmy", "my_name", &generated_secret);
186 assert!(totp.is_ok());