sentinelpass_protocol/
token.rs1use crate::paths::default_ipc_token_path;
4use crate::{ProtocolError, Result};
5use rand::{rngs::OsRng, RngCore};
6use std::io::Write;
7use zeroize::Zeroize;
8
9pub fn load_ipc_token() -> Result<String> {
11 let token_path = default_ipc_token_path();
12 let token = std::fs::read_to_string(&token_path)?.trim().to_string();
13 if token.is_empty() {
14 return Err(ProtocolError::Ipc(format!(
15 "IPC token file is empty: {:?}",
16 token_path
17 )));
18 }
19 Ok(token)
20}
21
22pub fn load_or_create_ipc_token() -> Result<String> {
24 let token_path = default_ipc_token_path();
25
26 if let Some(parent) = token_path.parent() {
27 std::fs::create_dir_all(parent)?;
28 }
29
30 if token_path.exists() {
31 return load_ipc_token();
32 }
33
34 let mut token_bytes = [0u8; 32];
35 OsRng.fill_bytes(&mut token_bytes);
36 let token = hex::encode(token_bytes);
37 token_bytes.zeroize();
38
39 let mut file = std::fs::OpenOptions::new()
40 .write(true)
41 .create_new(true)
42 .open(&token_path)?;
43 file.write_all(token.as_bytes())?;
44
45 #[cfg(unix)]
46 {
47 use std::os::unix::fs::PermissionsExt;
48 std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600))?;
49 }
50
51 Ok(token)
52}