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