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    None,
213  )
214}
215
216/// Transform npm configuration using resolved registries when supplied.
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  resolved_registries: Option<&[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  if let Some(registries) = resolved_registries {
282    registries_found.clear();
283    for registry in registries {
284      registries_found.insert(registry.npm_key().to_owned(), None);
285    }
286  }
287
288  if registries_found.is_empty() {
289    return Err(AuthError::NoNpmRegistry);
290  }
291
292  // Prepare credentials to write to to_content
293  let mut to_lines_out = Vec::new();
294  let mut pending_registries = registries_found.clone();
295
296  if !to_content.is_empty() {
297    for line in to_content.lines() {
298      let parsed = parser.parse_line(line)?;
299      match parsed {
300        NpmrcConfigType::AuthToken { registry, .. } => {
301          if registries_found.contains_key(&registry) {
302            if pending_registries.remove(&registry).is_some() {
303              to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
304            }
305          } else {
306            to_lines_out.push(line.to_string());
307          }
308        }
309
310        NpmrcConfigType::Password { registry, .. } => {
311          if registries_found.contains_key(&registry) {
312            if pending_registries.remove(&registry).is_some() {
313              to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
314            }
315          } else {
316            to_lines_out.push(line.to_string());
317          }
318        }
319
320        NpmrcConfigType::Username { registry } => {
321          if !registries_found.contains_key(&registry) {
322            to_lines_out.push(line.to_string());
323          }
324        }
325        _ => {
326          to_lines_out.push(line.to_string());
327        }
328      }
329    }
330  }
331
332  // Append auth tokens for registries not yet present in to_content
333  for (registry, _) in pending_registries {
334    log::debug!("Adding auth token for registry {registry}");
335    to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
336  }
337
338  let to_output = to_lines_out.join("\n") + "\n";
339  let from_output = from_lines_out.join("\n") + "\n";
340
341  Ok((from_output, to_output))
342}
343
344/// Updates `.npmrc` configuration files with the given access token.
345///
346/// # Arguments
347///
348/// * `from_path` - Path to `.npmrc` file to read registry settings from (e.g. project `.npmrc`).
349/// * `to_path` - Path to `.npmrc` file to write credentials to (e.g. user `~/.npmrc` or local `./.npmrc`).
350/// * `creds` - The OAuth2 access token string.
351/// * `allow_all_domains` - Whether to allow non-pkg.dev domains.
352/// # Errors
353///
354/// Returns [`AuthError::Io`] if reading or writing files fails, or [`AuthError::NoNpmRegistry`] if no registry was found.
355pub fn update_npmrc_configs(
356  from_path: &Path,
357  to_path: &Path,
358  creds: &str,
359  allow_all_domains: bool,
360) -> Result<(), AuthError> {
361  let from_path = resolve(from_path)?;
362  let to_path = resolve(to_path)?;
363  let same_file = from_path == to_path;
364  let mut transaction = FileTransaction::new(&[from_path.clone(), to_path.clone()])?;
365  let from_content = transaction.contents(&from_path)?.to_owned();
366  let to_content = transaction.contents(&to_path)?.to_owned();
367
368  let (from_output, to_output) = transform_npmrc_contents(
369    &from_content,
370    if same_file {
371      &from_content
372    } else {
373      &to_content
374    },
375    creds,
376    allow_all_domains,
377    same_file,
378  )?;
379
380  transaction.stage(&to_path, &to_output)?;
381
382  if !same_file && transaction.existed(&from_path)? && from_output != from_content {
383    transaction.stage(&from_path, &from_output)?;
384  }
385
386  transaction.commit()?;
387
388  Ok(())
389}
390
391#[cfg(test)]
392mod tests {
393  use super::*;
394  use std::fs;
395  use tempfile::tempdir;
396
397  #[test]
398  fn missing_registry_returns_dedicated_error() {
399    assert!(matches!(
400      transform_npmrc_contents("", "", "valid-token", false, false),
401      Err(AuthError::NoNpmRegistry)
402    ));
403  }
404
405  #[test]
406  fn test_parser_standard_ar() {
407    let parser = NpmrcParser::new(false).unwrap();
408
409    let line = "@my-org:registry=https://us-central1-npm.pkg.dev/my-project/my-repo/";
410    let parsed = parser.parse_line(line).unwrap();
411    match parsed {
412      NpmrcConfigType::Registry {
413        scope, registry, ..
414      } => {
415        assert_eq!(scope.as_deref(), Some("@my-org"));
416        assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
417      }
418      _ => panic!("Expected Registry variant"),
419    }
420  }
421
422  #[test]
423  fn test_parser_unscoped_ar() {
424    let parser = NpmrcParser::new(false).unwrap();
425
426    let line = "registry=https://europe-west1-npm.pkg.dev/google-cloud/demo-repo/";
427    let parsed = parser.parse_line(line).unwrap();
428    match parsed {
429      NpmrcConfigType::Registry {
430        scope, registry, ..
431      } => {
432        assert_eq!(scope, None);
433        assert_eq!(
434          registry,
435          "//europe-west1-npm.pkg.dev/google-cloud/demo-repo/"
436        );
437      }
438      _ => panic!("Expected Registry variant"),
439    }
440  }
441
442  #[test]
443  fn test_parser_existing_auth_token() {
444    let parser = NpmrcParser::new(false).unwrap();
445
446    let line = "//us-central1-npm.pkg.dev/my-project/my-repo/:_authToken=\"ya29.sample-token\"";
447    let parsed = parser.parse_line(line).unwrap();
448    match parsed {
449      NpmrcConfigType::AuthToken { registry, token } => {
450        assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
451        assert_eq!(token, "ya29.sample-token");
452      }
453      _ => panic!("Expected AuthToken variant"),
454    }
455  }
456
457  #[test]
458  fn test_in_memory_transform() {
459    let from = "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\nstrict-ssl=true\n";
460    let to = "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n";
461    let token = "fresh-adc-token-12345";
462
463    let (from_out, to_out) = transform_npmrc_contents(from, to, token, false, false).unwrap();
464    assert!(from_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
465    assert!(from_out.contains("strict-ssl=true"));
466    assert!(to_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
467    assert!(
468      to_out
469        .contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\"")
470    );
471  }
472
473  #[test]
474  fn duplicate_legacy_credentials_are_removed() {
475    let source = "@corp:registry=https://us-npm.pkg.dev/project/repo/\n";
476    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";
477    let (_, updated) = transform_npmrc_contents(source, target, "new", false, false).unwrap();
478    assert_eq!(updated.matches(":_authToken=").count(), 1);
479    assert!(!updated.contains("old"));
480    assert!(!updated.contains(":username="));
481  }
482
483  #[test]
484  fn test_update_npmrc_moves_token_to_user_config() {
485    let dir = tempdir().unwrap();
486    let project_npmrc = dir.path().join("project.npmrc");
487    let user_npmrc = dir.path().join("user.npmrc");
488
489    fs::write(
490      &project_npmrc,
491      "# Project configuration\n\
492             @corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
493             //us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"old-expired-token\"\n\
494             strict-ssl=true\n",
495    )
496    .unwrap();
497
498    fs::write(
499      &user_npmrc,
500      "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n",
501    )
502    .unwrap();
503
504    let token = "fresh-adc-token-12345";
505    update_npmrc_configs(&project_npmrc, &user_npmrc, token, false).unwrap();
506
507    let project_out = fs::read_to_string(&project_npmrc).unwrap();
508    let user_out = fs::read_to_string(&user_npmrc).unwrap();
509
510    assert!(project_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
511    assert!(project_out.contains("strict-ssl=true"));
512    assert!(!project_out.contains("_authToken"));
513
514    assert!(user_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
515    assert!(
516      user_out
517        .contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\"")
518    );
519  }
520
521  #[test]
522  fn test_update_npmrc_legacy_password_conversion() {
523    let dir = tempdir().unwrap();
524    let project_npmrc = dir.path().join("project.npmrc");
525    let user_npmrc = dir.path().join("user.npmrc");
526
527    fs::write(
528      &project_npmrc,
529      "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
530             //us-central1-npm.pkg.dev/my-corp/my-npm/:_password=base64pass\n\
531             //us-central1-npm.pkg.dev/my-corp/my-npm/:username=oauth2accesstoken\n",
532    )
533    .unwrap();
534
535    update_npmrc_configs(&project_npmrc, &user_npmrc, "new-token", false).unwrap();
536
537    let project_out = fs::read_to_string(&project_npmrc).unwrap();
538    let user_out = fs::read_to_string(&user_npmrc).unwrap();
539
540    assert!(!project_out.contains("_password"));
541    assert!(!project_out.contains("username=oauth2accesstoken"));
542    assert!(
543      user_out.contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"new-token\"")
544    );
545  }
546
547  #[test]
548  fn test_update_npmrc_single_file_local_credential() {
549    let dir = tempdir().unwrap();
550    let local_npmrc = dir.path().join(".npmrc");
551
552    fs::write(
553      &local_npmrc,
554      "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
555             save-exact=true\n",
556    )
557    .unwrap();
558
559    let token = "local-token-999";
560    update_npmrc_configs(&local_npmrc, &local_npmrc, token, false).unwrap();
561
562    let out = fs::read_to_string(&local_npmrc).unwrap();
563    assert!(out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
564    assert!(out.contains("save-exact=true"));
565    assert!(
566      out.contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"local-token-999\"")
567    );
568  }
569}