Skip to main content

node_auth/
npmrc.rs

1//! `.npmrc` configuration parsing, formatting, and transformation.
2//!
3//! Handles scoped and unscoped Artifact Registry repository definitions, `_authToken` credential lines,
4//! legacy basic auth password and username cleanup, and comment/formatting preservation.
5
6use crate::error::AuthError;
7use crate::fs::{FileTransaction, resolve};
8use crate::registry::RegistryPolicy;
9use crate::token::validate_token;
10use regex::Regex;
11use std::collections::BTreeMap;
12use std::path::Path;
13
14/// Recognized line configurations in `.npmrc` files.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum NpmrcConfigType {
17    /// Registry URL specification (e.g. `@scope:registry=https://...` or `registry=https://...`).
18    Registry {
19        /// Optional npm package scope (e.g. `@my-org`).
20        scope: Option<String>,
21        /// Normalized registry URL (e.g. `//us-central1-npm.pkg.dev/proj/repo/`).
22        registry: String,
23        /// Original unmodified raw line content.
24        raw: String,
25    },
26    /// Auth token credential line (e.g. `//...:_authToken="..."`).
27    AuthToken {
28        /// Normalized registry URL associated with this token.
29        registry: String,
30        /// Extracted authentication token string.
31        token: String,
32    },
33    /// Legacy basic auth password line (e.g. `//...:_password=...`).
34    Password {
35        /// Normalized registry URL associated with this password.
36        registry: String,
37        /// Base64-encoded password value.
38        password: String,
39    },
40    /// Legacy basic auth username line (e.g. `//...:username=oauth2accesstoken`).
41    Username {
42        /// Normalized registry URL.
43        registry: String,
44    },
45    /// Comments, blank lines, or other unrecognized configuration keys.
46    Other(String),
47}
48
49impl NpmrcConfigType {
50    /// Formats the configuration entry back into an `.npmrc` line.
51    pub fn to_line(&self) -> String {
52        match self {
53            NpmrcConfigType::Registry { raw, .. } => raw.clone(),
54            NpmrcConfigType::AuthToken { registry, token } => {
55                format!("{registry}:_authToken=\"{token}\"")
56            }
57            NpmrcConfigType::Password { registry, password } => {
58                format!("{registry}:_password={password}")
59            }
60            NpmrcConfigType::Username { registry } => {
61                format!("{registry}:username=oauth2accesstoken")
62            }
63            NpmrcConfigType::Other(line) => line.clone(),
64        }
65    }
66}
67
68/// Regular-expression-based parser for `.npmrc` lines.
69pub struct NpmrcParser {
70    policy: RegistryPolicy,
71    registry_re: Regex,
72    auth_token_re: Regex,
73    password_re: Regex,
74    username_re: Regex,
75}
76
77impl NpmrcParser {
78    /// Creates a new parser instance.
79    ///
80    /// If `allow_all_domains` is false, only `*-npm.pkg.dev` Artifact Registry domains match.
81    pub fn new(allow_all_domains: bool) -> Result<Self, AuthError> {
82        Ok(Self {
83            policy: RegistryPolicy { allow_all_domains },
84            registry_re: Regex::new(
85                r"^(@[a-zA-Z0-9-*~][a-zA-Z0-9-*._~]*:)?registry=(https://[^ \t\r\n]+)$",
86            )?,
87            auth_token_re: Regex::new(r"^(//[^ \t\r\n]+):_authToken=.*$")?,
88            password_re: Regex::new(r"^(//[^ \t\r\n]+):_password=.*$")?,
89            username_re: Regex::new(r"^(//[^ \t\r\n]+):username=oauth2accesstoken$")?,
90        })
91    }
92
93    /// Parses a single `.npmrc` configuration line into a [`NpmrcConfigType`].
94    pub fn parse_line(&self, line: &str) -> Result<NpmrcConfigType, AuthError> {
95        let trimmed = line.trim();
96
97        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
98            return Ok(NpmrcConfigType::Other(line.to_string()));
99        }
100
101        if let Some(caps) = self.registry_re.captures(trimmed) {
102            let scope = caps
103                .get(1)
104                .map(|m| m.as_str().trim_end_matches(':').to_string());
105            let registry_raw = caps.get(2).map(|m| m.as_str()).unwrap_or("");
106            if let Some(registry) = self.policy.parse(registry_raw)? {
107                return Ok(NpmrcConfigType::Registry {
108                    scope,
109                    registry: registry.npm_key().to_string(),
110                    raw: line.to_string(),
111                });
112            }
113        }
114
115        if let Some(caps) = self.auth_token_re.captures(trimmed) {
116            let key = caps.get(1).map(|m| m.as_str()).unwrap_or("");
117            if let Some(registry) = self.policy.parse_npm_key(key)? {
118                let token_part = trimmed
119                    .split_once(":_authToken=")
120                    .map(|(_, t)| t.trim().trim_matches('"').trim_matches('\'').to_string())
121                    .unwrap_or_default();
122                return Ok(NpmrcConfigType::AuthToken {
123                    registry: registry.npm_key().to_string(),
124                    token: token_part,
125                });
126            }
127        }
128
129        if let Some(caps) = self.password_re.captures(trimmed) {
130            let key = caps.get(1).map(|m| m.as_str()).unwrap_or("");
131            if let Some(registry) = self.policy.parse_npm_key(key)? {
132                let pass_part = trimmed
133                    .split_once(":_password=")
134                    .map(|(_, p)| p.trim().to_string())
135                    .unwrap_or_default();
136                return Ok(NpmrcConfigType::Password {
137                    registry: registry.npm_key().to_string(),
138                    password: pass_part,
139                });
140            }
141        }
142
143        if let Some(caps) = self.username_re.captures(trimmed) {
144            let key = caps.get(1).map(|m| m.as_str()).unwrap_or("");
145            if let Some(registry) = self.policy.parse_npm_key(key)? {
146                return Ok(NpmrcConfigType::Username {
147                    registry: registry.npm_key().to_string(),
148                });
149            }
150        }
151
152        Ok(NpmrcConfigType::Other(line.to_string()))
153    }
154}
155
156/// Whether either npm configuration contains an eligible registry definition.
157pub fn has_registry(
158    from_content: &str,
159    to_content: &str,
160    allow_all_domains: bool,
161) -> Result<bool, AuthError> {
162    let parser = NpmrcParser::new(allow_all_domains)?;
163    for line in from_content.lines().chain(to_content.lines()) {
164        if matches!(parser.parse_line(line)?, NpmrcConfigType::Registry { .. }) {
165            return Ok(true);
166        }
167    }
168    Ok(false)
169}
170
171/// Pure in-memory transformation of `.npmrc` contents.
172///
173/// Strips out legacy passwords and usernames, strips sensitive tokens from project configuration
174/// when writing to user configuration, and inserts the fresh auth token for each Artifact Registry scope.
175///
176/// # Arguments
177///
178/// * `from_content` - Raw text of the source repository `.npmrc`.
179/// * `to_content` - Raw text of the target credential `.npmrc`.
180/// * `creds` - The OAuth2 access token to insert.
181/// * `allow_all_domains` - Whether non-GAR domains are allowed for authentication.
182/// * `same_file` - True if reading and writing to the exact same file (e.g. `--local-credential`).
183///
184/// # Returns
185///
186/// Returns `(cleaned_from_content, updated_to_content)`.
187///
188/// # Errors
189///
190/// Returns [`AuthError::Config`] if no Artifact Registry configurations were found in the input.
191pub fn transform_npmrc_contents(
192    from_content: &str,
193    to_content: &str,
194    creds: &str,
195    allow_all_domains: bool,
196    same_file: bool,
197) -> Result<(String, String), AuthError> {
198    validate_token(creds)?;
199    let parser = NpmrcParser::new(allow_all_domains)?;
200    let mut registries_found = BTreeMap::new();
201    let mut from_lines_out = Vec::new();
202
203    // Parse source config
204    for line in from_content.lines() {
205        match parser.parse_line(line)? {
206            NpmrcConfigType::Registry {
207                scope,
208                registry,
209                raw,
210            } => {
211                registries_found.insert(registry.clone(), scope);
212                from_lines_out.push(raw);
213            }
214            NpmrcConfigType::AuthToken { registry, .. } => {
215                if same_file {
216                    // Updating same file: will be refreshed below
217                } else {
218                    log::debug!(
219                        "Moving existing _authToken for {registry} from project .npmrc to credential .npmrc"
220                    );
221                    // Strip from project config so secrets aren't checked into git
222                }
223            }
224            NpmrcConfigType::Password { registry, .. } => {
225                if !same_file {
226                    log::debug!("Removing legacy password for {registry} from project .npmrc");
227                }
228            }
229            NpmrcConfigType::Username { .. } => {
230                // Strip legacy oauth username line
231            }
232            NpmrcConfigType::Other(other) => {
233                from_lines_out.push(other);
234            }
235        }
236    }
237
238    if !same_file {
239        for line in to_content.lines() {
240            if let NpmrcConfigType::Registry {
241                scope, registry, ..
242            } = parser.parse_line(line)?
243            {
244                registries_found.entry(registry).or_insert(scope);
245            }
246        }
247    }
248
249    if registries_found.is_empty() {
250        return Err(AuthError::Config(
251            "No Artifact Registry configuration found.\n\
252             Ensure your .npmrc contains a registry line such as:\n\
253             @my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n\
254             Run `gcloud artifacts print-settings npm` to generate configuration."
255                .to_string(),
256        ));
257    }
258
259    // Prepare credentials to write to to_content
260    let mut to_lines_out = Vec::new();
261    let mut pending_registries = registries_found.clone();
262
263    if !to_content.is_empty() {
264        for line in to_content.lines() {
265            let parsed = parser.parse_line(line)?;
266            match parsed {
267                NpmrcConfigType::AuthToken { registry, .. } => {
268                    if registries_found.contains_key(&registry) {
269                        if pending_registries.remove(&registry).is_some() {
270                            to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
271                        }
272                    } else {
273                        to_lines_out.push(line.to_string());
274                    }
275                }
276                NpmrcConfigType::Password { registry, .. } => {
277                    if registries_found.contains_key(&registry) {
278                        if pending_registries.remove(&registry).is_some() {
279                            to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
280                        }
281                    } else {
282                        to_lines_out.push(line.to_string());
283                    }
284                }
285                NpmrcConfigType::Username { registry } => {
286                    if !registries_found.contains_key(&registry) {
287                        to_lines_out.push(line.to_string());
288                    }
289                }
290                _ => {
291                    to_lines_out.push(line.to_string());
292                }
293            }
294        }
295    }
296
297    // Append auth tokens for registries not yet present in to_content
298    for (registry, _) in pending_registries {
299        log::debug!("Adding auth token for registry {registry}");
300        to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
301    }
302
303    let to_output = to_lines_out.join("\n") + "\n";
304    let from_output = from_lines_out.join("\n") + "\n";
305
306    Ok((from_output, to_output))
307}
308
309/// Updates `.npmrc` configuration files with the given access token.
310///
311/// # Arguments
312///
313/// * `from_path` - Path to `.npmrc` file to read registry settings from (e.g. project `.npmrc`).
314/// * `to_path` - Path to `.npmrc` file to write credentials to (e.g. user `~/.npmrc` or local `./.npmrc`).
315/// * `creds` - The OAuth2 access token string.
316/// * `allow_all_domains` - Whether to allow non-pkg.dev domains.
317/// # Errors
318///
319/// Returns [`AuthError::Io`] if reading or writing files fails, or [`AuthError::Config`] if no registry was found.
320pub fn update_npmrc_configs(
321    from_path: &Path,
322    to_path: &Path,
323    creds: &str,
324    allow_all_domains: bool,
325) -> Result<(), AuthError> {
326    let from_path = resolve(from_path)?;
327    let to_path = resolve(to_path)?;
328    let same_file = from_path == to_path;
329    let mut transaction = FileTransaction::new(&[from_path.clone(), to_path.clone()])?;
330    let from_content = transaction.contents(&from_path)?.to_owned();
331    let to_content = transaction.contents(&to_path)?.to_owned();
332
333    let (from_output, to_output) = transform_npmrc_contents(
334        &from_content,
335        if same_file {
336            &from_content
337        } else {
338            &to_content
339        },
340        creds,
341        allow_all_domains,
342        same_file,
343    )?;
344
345    transaction.stage(&to_path, &to_output)?;
346    if !same_file && transaction.existed(&from_path)? && from_output != from_content {
347        transaction.stage(&from_path, &from_output)?;
348    }
349    transaction.commit()?;
350    Ok(())
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use std::fs;
357    use tempfile::tempdir;
358
359    #[test]
360    fn test_parser_standard_ar() {
361        let parser = NpmrcParser::new(false).unwrap();
362
363        let line = "@my-org:registry=https://us-central1-npm.pkg.dev/my-project/my-repo/";
364        let parsed = parser.parse_line(line).unwrap();
365        match parsed {
366            NpmrcConfigType::Registry {
367                scope, registry, ..
368            } => {
369                assert_eq!(scope.as_deref(), Some("@my-org"));
370                assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
371            }
372            _ => panic!("Expected Registry variant"),
373        }
374    }
375
376    #[test]
377    fn test_parser_unscoped_ar() {
378        let parser = NpmrcParser::new(false).unwrap();
379
380        let line = "registry=https://europe-west1-npm.pkg.dev/google-cloud/demo-repo/";
381        let parsed = parser.parse_line(line).unwrap();
382        match parsed {
383            NpmrcConfigType::Registry {
384                scope, registry, ..
385            } => {
386                assert_eq!(scope, None);
387                assert_eq!(
388                    registry,
389                    "//europe-west1-npm.pkg.dev/google-cloud/demo-repo/"
390                );
391            }
392            _ => panic!("Expected Registry variant"),
393        }
394    }
395
396    #[test]
397    fn test_parser_existing_auth_token() {
398        let parser = NpmrcParser::new(false).unwrap();
399
400        let line = "//us-central1-npm.pkg.dev/my-project/my-repo/:_authToken=\"ya29.sample-token\"";
401        let parsed = parser.parse_line(line).unwrap();
402        match parsed {
403            NpmrcConfigType::AuthToken { registry, token } => {
404                assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
405                assert_eq!(token, "ya29.sample-token");
406            }
407            _ => panic!("Expected AuthToken variant"),
408        }
409    }
410
411    #[test]
412    fn test_in_memory_transform() {
413        let from =
414            "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\nstrict-ssl=true\n";
415        let to = "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n";
416        let token = "fresh-adc-token-12345";
417
418        let (from_out, to_out) = transform_npmrc_contents(from, to, token, false, false).unwrap();
419        assert!(
420            from_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/")
421        );
422        assert!(from_out.contains("strict-ssl=true"));
423        assert!(to_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
424        assert!(to_out.contains(
425            "//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\""
426        ));
427    }
428
429    #[test]
430    fn duplicate_legacy_credentials_are_removed() {
431        let source = "@corp:registry=https://us-npm.pkg.dev/project/repo/\n";
432        let target = "//us-npm.pkg.dev/project/repo/:_authToken=old\n//us-npm.pkg.dev/project/repo/:_password=old\n//us-npm.pkg.dev/project/repo/:username=oauth2accesstoken\n";
433        let (_, updated) = transform_npmrc_contents(source, target, "new", false, false).unwrap();
434        assert_eq!(updated.matches(":_authToken=").count(), 1);
435        assert!(!updated.contains("old"));
436        assert!(!updated.contains(":username="));
437    }
438
439    #[test]
440    fn test_update_npmrc_moves_token_to_user_config() {
441        let dir = tempdir().unwrap();
442        let project_npmrc = dir.path().join("project.npmrc");
443        let user_npmrc = dir.path().join("user.npmrc");
444
445        fs::write(
446            &project_npmrc,
447            "# Project configuration\n\
448             @corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
449             //us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"old-expired-token\"\n\
450             strict-ssl=true\n",
451        )
452        .unwrap();
453
454        fs::write(
455            &user_npmrc,
456            "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n",
457        )
458        .unwrap();
459
460        let token = "fresh-adc-token-12345";
461        update_npmrc_configs(&project_npmrc, &user_npmrc, token, false).unwrap();
462
463        let project_out = fs::read_to_string(&project_npmrc).unwrap();
464        let user_out = fs::read_to_string(&user_npmrc).unwrap();
465
466        assert!(
467            project_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/")
468        );
469        assert!(project_out.contains("strict-ssl=true"));
470        assert!(!project_out.contains("_authToken"));
471
472        assert!(user_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
473        assert!(user_out.contains(
474            "//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\""
475        ));
476    }
477
478    #[test]
479    fn test_update_npmrc_legacy_password_conversion() {
480        let dir = tempdir().unwrap();
481        let project_npmrc = dir.path().join("project.npmrc");
482        let user_npmrc = dir.path().join("user.npmrc");
483
484        fs::write(
485            &project_npmrc,
486            "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
487             //us-central1-npm.pkg.dev/my-corp/my-npm/:_password=base64pass\n\
488             //us-central1-npm.pkg.dev/my-corp/my-npm/:username=oauth2accesstoken\n",
489        )
490        .unwrap();
491
492        update_npmrc_configs(&project_npmrc, &user_npmrc, "new-token", false).unwrap();
493
494        let project_out = fs::read_to_string(&project_npmrc).unwrap();
495        let user_out = fs::read_to_string(&user_npmrc).unwrap();
496
497        assert!(!project_out.contains("_password"));
498        assert!(!project_out.contains("username=oauth2accesstoken"));
499        assert!(
500            user_out.contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"new-token\"")
501        );
502    }
503
504    #[test]
505    fn test_update_npmrc_single_file_local_credential() {
506        let dir = tempdir().unwrap();
507        let local_npmrc = dir.path().join(".npmrc");
508
509        fs::write(
510            &local_npmrc,
511            "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
512             save-exact=true\n",
513        )
514        .unwrap();
515
516        let token = "local-token-999";
517        update_npmrc_configs(&local_npmrc, &local_npmrc, token, false).unwrap();
518
519        let out = fs::read_to_string(&local_npmrc).unwrap();
520        assert!(out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
521        assert!(out.contains("save-exact=true"));
522        assert!(
523            out.contains(
524                "//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"local-token-999\""
525            )
526        );
527    }
528}