Skip to main content

node_auth/
yarnrc.rs

1//! Yarn (`.yarnrc.yml`) configuration management.
2//!
3//! Handles parsing, updating, and writing `npmScopes` authentication entries
4//! (`npmAlwaysAuth` and `npmAuthToken`) in `.yarnrc.yml` files.
5
6use crate::error::AuthError;
7use crate::fs::{FileTransaction, resolve};
8use crate::registry::RegistryPolicy;
9use crate::token::validate_token;
10use std::path::Path;
11use std::str::FromStr;
12use yaml_edit::{Mapping, YamlFile};
13
14/// Transforms Yarn (`.yarnrc.yml`) content in memory to insert authentication tokens for detected scopes.
15///
16/// # Arguments
17///
18/// * `from_content` - Raw YAML text of the source/repository `.yarnrc.yml`.
19/// * `to_content` - Raw YAML text of the destination `.yarnrc.yml` (e.g. user-level config).
20/// * `creds` - The OAuth2 access token to insert into `npmAuthToken`.
21///
22/// # Returns
23///
24/// * `Ok(Some(updated_yaml))` if any `npmScopes` were found and updated.
25/// * `Ok(None)` if no scopes were found.
26///
27/// # Errors
28///
29/// Returns [`AuthError::YamlInput`] if either input is invalid YAML.
30pub fn transform_yarnrc_contents(
31  from_content: &str,
32  to_content: &str,
33  creds: &str,
34) -> Result<Option<String>, AuthError> {
35  transform_yarnrc_contents_with_policy(from_content, to_content, creds, false)
36}
37
38/// Transform Yarn configuration using the same registry policy as npm.
39pub fn transform_yarnrc_contents_with_policy(
40  from_content: &str,
41  to_content: &str,
42  creds: &str,
43  allow_all_domains: bool,
44) -> Result<Option<String>, AuthError> {
45  validate_token(creds)?;
46  let from_file = parse_yarnrc(from_content, "source .yarnrc.yml")?;
47  let to_file = parse_yarnrc(to_content, "credential .yarnrc.yml")?;
48  let from_doc = from_file
49    .document()
50    .ok_or_else(|| AuthError::Config("Yarn configuration must contain a document".to_string()))?;
51  let to_doc = to_file.document().ok_or_else(|| {
52    AuthError::Config("Yarn credential configuration must contain a document".to_string())
53  })?;
54  let policy = RegistryPolicy { allow_all_domains };
55  let from_root = from_doc
56    .as_mapping()
57    .ok_or_else(|| AuthError::Config("Yarn configuration must be a YAML mapping".to_string()))?;
58  let to_root = to_doc.as_mapping().ok_or_else(|| {
59    AuthError::Config("Yarn credential configuration must be a YAML mapping".to_string())
60  })?;
61  let mut found_any = false;
62
63  if let Some(from_scopes_value) = from_root.get("npmScopes") {
64    let from_scopes = from_scopes_value
65      .as_mapping()
66      .ok_or_else(|| AuthError::Config("Yarn npmScopes must be a mapping".to_string()))?;
67    for (scope_key, scope_val) in from_scopes.iter() {
68      let scope_name = scope_key
69        .as_scalar()
70        .map(|key| key.as_string())
71        .ok_or_else(|| AuthError::Config("Yarn scope name must be a string".to_string()))?;
72      let scope = scope_val
73        .as_mapping()
74        .ok_or_else(|| AuthError::Config(format!("Yarn scope `{scope_name}` must be a mapping")))?;
75      let Some(raw_registry) = scope.get("npmRegistryServer") else {
76        continue;
77      };
78      let registry = raw_registry
79        .as_scalar()
80        .map(|value| value.as_string())
81        .ok_or_else(|| {
82          AuthError::Config(format!(
83            "Yarn scope `{scope_name}` registry must be a string"
84          ))
85        })?;
86      if policy.parse(&registry)?.is_none() {
87        continue;
88      }
89      found_any = true;
90
91      let target_scopes = ensure_mapping(&to_root, "npmScopes").ok_or_else(|| {
92        AuthError::Config("Destination Yarn npmScopes must be a mapping".to_string())
93      })?;
94      let target_scope = ensure_mapping(&target_scopes, &scope_name).ok_or_else(|| {
95        AuthError::Config(format!(
96          "Destination Yarn scope `{scope_name}` must be a mapping"
97        ))
98      })?;
99      target_scope.set("npmRegistryServer", registry);
100      target_scope.set("npmAlwaysAuth", true);
101      target_scope.set("npmAuthToken", creds);
102    }
103  }
104
105  if !found_any {
106    return Ok(None);
107  }
108  Ok(Some(to_file.to_string()))
109}
110
111fn parse_yarnrc(content: &str, input: &'static str) -> Result<YamlFile, AuthError> {
112  if content.trim().is_empty() {
113    let file = YamlFile::new();
114    file.ensure_document();
115    Ok(file)
116  } else {
117    YamlFile::from_str(content).map_err(|source| AuthError::YamlInput { input, source })
118  }
119}
120
121fn ensure_mapping(parent: &Mapping, key: &str) -> Option<Mapping> {
122  match parent.get(key) {
123    Some(value) => value.as_mapping().cloned(),
124    None => {
125      parent.set(key, Mapping::new_pending_block());
126      parent.get_mapping(key)
127    }
128  }
129}
130
131/// Updates `.yarnrc.yml` files with the access token.
132///
133/// # Arguments
134///
135/// * `from_path` - Path to project `.yarnrc.yml` to read scope configurations from.
136/// * `to_path` - Path to user `.yarnrc.yml` to write credentials to.
137/// * `creds` - Google OAuth2 access token string.
138/// # Errors
139///
140/// Returns [`AuthError::Io`] if reading or writing files fails, or
141/// [`AuthError::YamlInput`] if YAML parsing fails.
142pub fn update_yarn_configs(from_path: &Path, to_path: &Path, creds: &str) -> Result<(), AuthError> {
143  update_yarn_configs_with_policy(from_path, to_path, creds, false)
144}
145
146/// Update Yarn configuration with an explicit registry-domain policy.
147pub fn update_yarn_configs_with_policy(
148  from_path: &Path,
149  to_path: &Path,
150  creds: &str,
151  allow_all_domains: bool,
152) -> Result<(), AuthError> {
153  let from_path = resolve(from_path)?;
154  let to_path = resolve(to_path)?;
155  let mut transaction = FileTransaction::new(&[from_path.clone(), to_path.clone()])?;
156  let from_content = transaction.contents(&from_path)?.to_owned();
157  let to_content = transaction.contents(&to_path)?.to_owned();
158  match transform_yarnrc_contents_with_policy(&from_content, &to_content, creds, allow_all_domains)?
159  {
160    Some(dumped) => {
161      transaction.stage(&to_path, &dumped)?;
162      transaction.commit()?;
163      Ok(())
164    }
165    None => Ok(()),
166  }
167}
168
169#[cfg(test)]
170mod tests {
171  use super::*;
172  use std::fs;
173  use tempfile::tempdir;
174
175  #[test]
176  fn test_in_memory_yarnrc_transform() {
177    let from = r#"
178npmScopes:
179  my-scope:
180    npmRegistryServer: "https://us-central1-npm.pkg.dev/my-project/my-repo"
181"#;
182    let res = transform_yarnrc_contents(from, "", "test-token").unwrap();
183    assert!(res.is_some());
184    let out = res.unwrap();
185    assert!(out.contains("npmScopes"));
186    assert!(out.contains("my-scope"));
187    assert!(out.contains("npmAuthToken: test-token"));
188  }
189
190  #[test]
191  fn transform_preserves_unrelated_formatting_and_comments() {
192    let from = r#"npmScopes:
193  my-scope:
194    npmRegistryServer: "https://us-central1-npm.pkg.dev/my-project/my-repo"
195"#;
196    let to = r#"# User-level Yarn settings
197nodeLinker: pnp # keep this inline comment
198
199npmScopes:
200  my-scope:
201    npmRegistryServer: 'https://old.example/my-project/my-repo' # registry note
202    customSetting: "keep-me"
203
204checksumBehavior: 'throw'
205"#;
206
207    let out = transform_yarnrc_contents(from, to, "test-token")
208      .unwrap()
209      .unwrap();
210
211    assert!(out.starts_with("# User-level Yarn settings\n"));
212    assert!(out.contains("nodeLinker: pnp # keep this inline comment\n\n"));
213    assert!(out.contains("# registry note\n"));
214    assert!(out.contains("    customSetting: \"keep-me\"\n"));
215    assert!(out.ends_with("\nchecksumBehavior: 'throw'\n"));
216    assert!(out.contains("npmAlwaysAuth: true"));
217    assert!(out.contains("npmAuthToken: test-token"));
218  }
219
220  #[test]
221  fn transform_quotes_yaml_sensitive_tokens() {
222    let from = r#"npmScopes:
223  my-scope:
224    npmRegistryServer: https://us-central1-npm.pkg.dev/my-project/my-repo
225"#;
226
227    let out = transform_yarnrc_contents(from, "", "token:#value")
228      .unwrap()
229      .unwrap();
230    let parsed = YamlFile::from_str(&out).unwrap().document().unwrap();
231    let token = parsed
232      .get_mapping("npmScopes")
233      .unwrap()
234      .get_mapping("my-scope")
235      .unwrap()
236      .get("npmAuthToken")
237      .unwrap()
238      .as_scalar()
239      .unwrap()
240      .as_string();
241
242    assert_eq!(token, "token:#value");
243  }
244
245  #[test]
246  fn test_update_yarnrc_creates_scope_auth() {
247    let dir = tempdir().unwrap();
248    let project_yarn = dir.path().join("project.yarnrc.yml");
249    let user_yarn = dir.path().join("user.yarnrc.yml");
250
251    fs::write(
252      &project_yarn,
253      r#"
254npmScopes:
255  my-scope:
256    npmRegistryServer: "https://us-central1-npm.pkg.dev/my-project/my-repo"
257"#,
258    )
259    .unwrap();
260
261    let token = "yarn-token-12345";
262    update_yarn_configs(&project_yarn, &user_yarn, token).unwrap();
263
264    let user_out = fs::read_to_string(&user_yarn).unwrap();
265    assert!(user_out.contains("npmScopes"));
266    assert!(user_out.contains("my-scope"));
267    assert!(user_out.contains("https://us-central1-npm.pkg.dev/my-project/my-repo"));
268    assert!(user_out.contains("npmAlwaysAuth: true"));
269    assert!(user_out.contains("npmAuthToken: yarn-token-12345"));
270  }
271}