nickserv.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. str::{FromStr, SplitAsciiWhitespace},
  20. sync::Arc,
  21. };
  22. use darkfi::Result;
  23. use darkfi_sdk::crypto::SecretKey;
  24. use darkfi_serial::serialize_async;
  25. use smol::lock::RwLock;
  26. use super::{
  27. super::{client::ReplyType, rpl::*},
  28. rln::RlnIdentity,
  29. };
  30. use crate::IrcServer;
  31. const ACCOUNTS_DB_PREFIX: &str = "darkirc_account_";
  32. const ACCOUNTS_KEY_RLN_IDENTITY: &[u8] = b"rln_identity";
  33. const NICKSERV_USAGE: &str = r#"***** NickServ Help *****
  34. NickServ allows a client to perform account management on DarkIRC.
  35. The following commands are available:
  36. INFO Displays information on registrations.
  37. REGISTER Register an account.
  38. DEREGISTER Deregister an account.
  39. SET Select an account to use.
  40. For more information on a NickServ command, type:
  41. /msg NickServ HELP <command>
  42. ***** End of Help *****
  43. "#;
  44. /// NickServ implementation used for IRC account management
  45. pub struct NickServ {
  46. /// Client username
  47. pub _username: Arc<RwLock<String>>,
  48. /// Client nickname
  49. pub nickname: Arc<RwLock<String>>,
  50. /// Pointer to parent `IrcServer`
  51. pub server: Arc<IrcServer>,
  52. }
  53. impl NickServ {
  54. /// Instantiate a new `NickServ` for a client. This should be called after
  55. /// the user/nick are successfully registered.
  56. pub async fn new(
  57. _username: Arc<RwLock<String>>,
  58. nickname: Arc<RwLock<String>>,
  59. server: Arc<IrcServer>,
  60. ) -> Result<Self> {
  61. Ok(Self { _username, nickname, server })
  62. }
  63. /// Handle a `NickServ` query. This is the main command handler.
  64. /// Called from `command::handle_cmd_privmsg`.
  65. pub async fn handle_query(&self, query: &str) -> Result<Vec<ReplyType>> {
  66. let nick = self.nickname.read().await.to_string();
  67. let mut tokens = query.split_ascii_whitespace();
  68. let Some(command) = tokens.next() else {
  69. return Ok(vec![ReplyType::Server((
  70. ERR_NOTEXTTOSEND,
  71. format!("{nick} :No text to send"),
  72. ))])
  73. };
  74. match command.to_uppercase().as_str() {
  75. "INFO" => self.handle_info(&nick, &mut tokens).await,
  76. "REGISTER" => self.handle_register(&nick, &mut tokens).await,
  77. "DEREGISTER" => self.handle_deregister(&nick, &mut tokens).await,
  78. "SET" => self.handle_set(&nick, &mut tokens).await,
  79. "HELP" => self.handle_help(&nick).await,
  80. _ => self.handle_invalid(&nick).await,
  81. }
  82. }
  83. /// Handle the INFO command
  84. pub async fn handle_info(
  85. &self,
  86. _nick: &str,
  87. _tokens: &mut SplitAsciiWhitespace<'_>,
  88. ) -> Result<Vec<ReplyType>> {
  89. todo!()
  90. }
  91. /// Handle the REGISTER command
  92. pub async fn handle_register(
  93. &self,
  94. nick: &str,
  95. tokens: &mut SplitAsciiWhitespace<'_>,
  96. ) -> Result<Vec<ReplyType>> {
  97. // Gather the tokens
  98. let account_name = tokens.next();
  99. let identity_nullifier = tokens.next();
  100. let identity_trapdoor = tokens.next();
  101. let leaf_pos = tokens.next();
  102. if account_name.is_none() ||
  103. identity_nullifier.is_none() ||
  104. identity_trapdoor.is_none() ||
  105. leaf_pos.is_none()
  106. {
  107. return Ok(vec![
  108. ReplyType::Notice((
  109. "NickServ".to_string(),
  110. nick.to_string(),
  111. "Invalid syntax.".to_string(),
  112. )),
  113. ReplyType::Notice((
  114. "NickServ".to_string(),
  115. nick.to_string(),
  116. "Use `REGISTER <account_name> <identity_nullifier> <identity_trapdoor> <leaf_pos>`."
  117. .to_string(),
  118. )),
  119. ])
  120. };
  121. let account_name = account_name.unwrap();
  122. let identity_nullifier = identity_nullifier.unwrap();
  123. let identity_trapdoor = identity_trapdoor.unwrap();
  124. let leaf_pos = leaf_pos.unwrap();
  125. // Open the sled tree
  126. let db =
  127. self.server.darkirc.sled.open_tree(format!("{ACCOUNTS_DB_PREFIX}{account_name}"))?;
  128. if !db.is_empty() {
  129. return Ok(vec![ReplyType::Notice((
  130. "NickServ".to_string(),
  131. nick.to_string(),
  132. "This account name is already registered.".to_string(),
  133. ))])
  134. }
  135. // TODO: WIF
  136. // Parse the secrets
  137. let identity_nullifier = match SecretKey::from_str(identity_nullifier) {
  138. Ok(v) => v,
  139. Err(e) => {
  140. return Ok(vec![ReplyType::Notice((
  141. "NickServ".to_string(),
  142. nick.to_string(),
  143. format!("Invalid identity_nullifier: {e}"),
  144. ))])
  145. }
  146. };
  147. let identity_trapdoor = match SecretKey::from_str(identity_trapdoor) {
  148. Ok(v) => v,
  149. Err(e) => {
  150. return Ok(vec![ReplyType::Notice((
  151. "NickServ".to_string(),
  152. nick.to_string(),
  153. format!("Invalid identity_trapdoor: {e}"),
  154. ))])
  155. }
  156. };
  157. let leaf_pos = match u64::from_str(leaf_pos) {
  158. Ok(v) => v,
  159. Err(e) => {
  160. return Ok(vec![ReplyType::Notice((
  161. "NickServ".to_string(),
  162. nick.to_string(),
  163. format!("Invalid leaf_pos: {e}"),
  164. ))])
  165. }
  166. };
  167. // Create a new RLN identity and insert it into the db tree
  168. let rln_identity =
  169. RlnIdentity { identity_nullifier, identity_trapdoor, leaf_pos: leaf_pos.into() };
  170. db.insert(ACCOUNTS_KEY_RLN_IDENTITY, serialize_async(&rln_identity).await)?;
  171. Ok(vec![ReplyType::Notice((
  172. "NickServ".to_string(),
  173. nick.to_string(),
  174. format!("Successfully registered account \"{account_name}\""),
  175. ))])
  176. }
  177. /// Handle the DEREGISTER command
  178. pub async fn handle_deregister(
  179. &self,
  180. nick: &str,
  181. tokens: &mut SplitAsciiWhitespace<'_>,
  182. ) -> Result<Vec<ReplyType>> {
  183. let Some(account_name) = tokens.next() else {
  184. return Ok(vec![ReplyType::Notice((
  185. "NickServ".to_string(),
  186. nick.to_string(),
  187. "Invalid syntax. Use `DEREGISTER <account_name>`.".to_string(),
  188. ))])
  189. };
  190. // Drop the tree
  191. self.server.darkirc.sled.drop_tree(format!("{ACCOUNTS_DB_PREFIX}{account_name}"))?;
  192. Ok(vec![ReplyType::Notice((
  193. "NickServ".to_string(),
  194. nick.to_string(),
  195. format!("Successfully deregistered account \"{account_name}\""),
  196. ))])
  197. }
  198. /// Handle the SET command
  199. pub async fn handle_set(
  200. &self,
  201. _nick: &str,
  202. _tokens: &mut SplitAsciiWhitespace<'_>,
  203. ) -> Result<Vec<ReplyType>> {
  204. todo!()
  205. }
  206. /// Reply to the HELP command
  207. pub async fn handle_help(&self, nick: &str) -> Result<Vec<ReplyType>> {
  208. let replies = NICKSERV_USAGE
  209. .lines()
  210. .map(|x| ReplyType::Notice(("NickServ".to_string(), nick.to_string(), x.to_string())))
  211. .collect();
  212. Ok(replies)
  213. }
  214. /// Reply to an invalid command
  215. pub async fn handle_invalid(&self, nick: &str) -> Result<Vec<ReplyType>> {
  216. let replies = vec![
  217. ReplyType::Notice((
  218. "NickServ".to_string(),
  219. nick.to_string(),
  220. "Invalid NickServ command.".to_string(),
  221. )),
  222. ReplyType::Notice((
  223. "NickServ".to_string(),
  224. nick.to_string(),
  225. "Use /msg NickServ HELP for a NickServ command listing.".to_string(),
  226. )),
  227. ];
  228. Ok(replies)
  229. }
  230. }