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