Skip to main content

node_auth/
token.rs

1//! Access-token validation.
2
3use crate::AuthError;
4
5/// Reject tokens that cannot safely be represented in a quoted `.npmrc` value.
6pub fn validate_token(token: &str) -> Result<(), AuthError> {
7  if token.is_empty()
8    || token
9      .chars()
10      .any(|c| c.is_control() || c.is_whitespace() || c == '"' || c == '\\')
11  {
12    return Err(AuthError::Config(
13      "Access token is empty or contains whitespace, control, quote, or backslash characters"
14        .to_string(),
15    ));
16  }
17
18  Ok(())
19}
20
21#[cfg(test)]
22mod tests {
23  use super::*;
24
25  #[test]
26  fn accepts_safe_token() {
27    assert!(validate_token("safe-token_123.abc").is_ok());
28  }
29
30  #[test]
31  fn rejects_empty_or_unsafe_tokens() {
32    for token in ["", "has space", "has\nnewline", "has\"quote", "has\\slash"] {
33      assert!(validate_token(token).is_err(), "accepted {token:?}");
34    }
35  }
36}