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