docsrs_cli/config/
validate.rs1use crate::domain::AllowedOrigin;
7use crate::error::{AppError, AppResult, ErrorKind};
8
9use super::constants::{APP_NAME, APP_VERSION, DEFAULT_CONTACT_URL, MAX_USER_AGENT_CHARS};
10
11pub use crate::domain::is_stdlib_name as is_stdlib_crate;
13
14pub fn default_user_agent(contact: Option<&str>) -> String {
16 match contact {
17 Some(c) if !c.is_empty() => {
18 if c.starts_with("http://") || c.starts_with("https://") {
19 format!("{APP_NAME}/{APP_VERSION} (+{c})")
20 } else {
21 format!("{APP_NAME}/{APP_VERSION} ({c})")
22 }
23 }
24 _ => format!("{APP_NAME}/{APP_VERSION} (+{DEFAULT_CONTACT_URL})"),
25 }
26}
27
28pub fn validate_origin(raw: &str) -> AppResult<AllowedOrigin> {
36 AllowedOrigin::parse(raw)
37}
38
39pub fn validate_origin_with(raw: &str, allow_loopback: bool) -> AppResult<AllowedOrigin> {
45 AllowedOrigin::parse_with(raw, allow_loopback)
46}
47
48pub fn validate_user_agent(ua: &str) -> AppResult<()> {
55 if ua.is_empty() {
56 return Err(AppError::new(
57 ErrorKind::Config,
58 "user-agent must not be empty",
59 ));
60 }
61 if ua.chars().count() > MAX_USER_AGENT_CHARS {
62 return Err(AppError::new(
63 ErrorKind::Config,
64 format!("user-agent exceeds {MAX_USER_AGENT_CHARS} characters"),
65 ));
66 }
67 if !ua.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
69 return Err(AppError::new(
70 ErrorKind::Config,
71 "user-agent must be visible ASCII (no control characters or non-ASCII)",
72 ));
73 }
74 Ok(())
75}
76
77pub fn validate_contact(contact: &str) -> AppResult<()> {
87 if contact.is_empty() {
88 return Err(AppError::new(
89 ErrorKind::Config,
90 "contact must not be empty when set",
91 ));
92 }
93 if contact.chars().count() > MAX_USER_AGENT_CHARS {
94 return Err(AppError::new(
95 ErrorKind::Config,
96 format!("contact exceeds {MAX_USER_AGENT_CHARS} characters"),
97 ));
98 }
99 if !contact.bytes().all(|b| (0x20..=0x7e).contains(&b)) {
100 return Err(AppError::new(
101 ErrorKind::Config,
102 "contact must be visible ASCII (no control characters or non-ASCII)",
103 ));
104 }
105 Ok(())
106}