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  Ok(())
18}
19
20#[cfg(test)]
21mod tests {
22  use super::*;
23
24  #[test]
25  fn accepts_safe_token() {
26    assert!(validate_token("safe-token_123.abc").is_ok());
27  }
28
29  #[test]
30  fn rejects_empty_or_unsafe_tokens() {
31    for token in ["", "has space", "has\nnewline", "has\"quote", "has\\slash"] {
32      assert!(validate_token(token).is_err(), "accepted {token:?}");
33    }
34  }
35}