Skip to main content

node_auth/
yarnrc.rs

1//! Yarn Berry / Yarn Modern (`.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 Modern (`.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.document().ok_or_else(|| {
49        AuthError::Config("Yarn configuration must contain a document".to_string())
50    })?;
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.as_mapping().ok_or_else(|| {
56        AuthError::Config("Yarn configuration must be a YAML mapping".to_string())
57    })?;
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.as_mapping().ok_or_else(|| {
73                AuthError::Config(format!("Yarn scope `{scope_name}` must be a mapping"))
74            })?;
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(
159        &from_content,
160        &to_content,
161        creds,
162        allow_all_domains,
163    )? {
164        Some(dumped) => {
165            transaction.stage(&to_path, &dumped)?;
166            transaction.commit()?;
167            Ok(())
168        }
169        None => Ok(()),
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use std::fs;
177    use tempfile::tempdir;
178
179    #[test]
180    fn test_in_memory_yarnrc_transform() {
181        let from = r#"
182npmScopes:
183  my-scope:
184    npmRegistryServer: "https://us-central1-npm.pkg.dev/my-project/my-repo"
185"#;
186        let res = transform_yarnrc_contents(from, "", "test-token").unwrap();
187        assert!(res.is_some());
188        let out = res.unwrap();
189        assert!(out.contains("npmScopes"));
190        assert!(out.contains("my-scope"));
191        assert!(out.contains("npmAuthToken: test-token"));
192    }
193
194    #[test]
195    fn transform_preserves_unrelated_formatting_and_comments() {
196        let from = r#"npmScopes:
197  my-scope:
198    npmRegistryServer: "https://us-central1-npm.pkg.dev/my-project/my-repo"
199"#;
200        let to = r#"# User-level Yarn settings
201nodeLinker: pnp # keep this inline comment
202
203npmScopes:
204  my-scope:
205    npmRegistryServer: 'https://old.example/my-project/my-repo' # registry note
206    customSetting: "keep-me"
207
208checksumBehavior: 'throw'
209"#;
210
211        let out = transform_yarnrc_contents(from, to, "test-token")
212            .unwrap()
213            .unwrap();
214
215        assert!(out.starts_with("# User-level Yarn settings\n"));
216        assert!(out.contains("nodeLinker: pnp # keep this inline comment\n\n"));
217        assert!(out.contains("# registry note\n"));
218        assert!(out.contains("    customSetting: \"keep-me\"\n"));
219        assert!(out.ends_with("\nchecksumBehavior: 'throw'\n"));
220        assert!(out.contains("npmAlwaysAuth: true"));
221        assert!(out.contains("npmAuthToken: test-token"));
222    }
223
224    #[test]
225    fn transform_quotes_yaml_sensitive_tokens() {
226        let from = r#"npmScopes:
227  my-scope:
228    npmRegistryServer: https://us-central1-npm.pkg.dev/my-project/my-repo
229"#;
230
231        let out = transform_yarnrc_contents(from, "", "token:#value")
232            .unwrap()
233            .unwrap();
234        let parsed = YamlFile::from_str(&out).unwrap().document().unwrap();
235        let token = parsed
236            .get_mapping("npmScopes")
237            .unwrap()
238            .get_mapping("my-scope")
239            .unwrap()
240            .get("npmAuthToken")
241            .unwrap()
242            .as_scalar()
243            .unwrap()
244            .as_string();
245
246        assert_eq!(token, "token:#value");
247    }
248
249    #[test]
250    fn test_update_yarnrc_creates_scope_auth() {
251        let dir = tempdir().unwrap();
252        let project_yarn = dir.path().join("project.yarnrc.yml");
253        let user_yarn = dir.path().join("user.yarnrc.yml");
254
255        fs::write(
256            &project_yarn,
257            r#"
258npmScopes:
259  my-scope:
260    npmRegistryServer: "https://us-central1-npm.pkg.dev/my-project/my-repo"
261"#,
262        )
263        .unwrap();
264
265        let token = "yarn-token-12345";
266        update_yarn_configs(&project_yarn, &user_yarn, token).unwrap();
267
268        let user_out = fs::read_to_string(&user_yarn).unwrap();
269        assert!(user_out.contains("npmScopes"));
270        assert!(user_out.contains("my-scope"));
271        assert!(user_out.contains("https://us-central1-npm.pkg.dev/my-project/my-repo"));
272        assert!(user_out.contains("npmAlwaysAuth: true"));
273        assert!(user_out.contains("npmAuthToken: yarn-token-12345"));
274    }
275}