Skip to main content

node_auth/
lib.rs

1//! # `node-auth`
2//!
3//! A fast, lightweight, standalone Rust CLI and library that authenticates JavaScript package managers
4//! (**npm**, **yarn**, **pnpm**, and **Bun**) to private **Google Artifact Registry (GAR)** npm repositories
5//! using **Google Cloud Application Default Credentials (ADC)**.
6//!
7//! ## Overview
8//!
9//! `node-auth` replicates and improves upon Google's `@google-cloud/artifact-registry-npm-tools`
10//! without requiring a JavaScript runtime or package manager to be installed beforehand.
11//!
12//! ### Key Features
13//! - **Automatic Credential Discovery**: Searches for explicit tokens, Application Default Credentials (ADC),
14//!   and falls back to `gcloud auth print-access-token`.
15//! - **Credential Isolation**: Reads registry endpoints from project-level `.npmrc` and writes secrets to
16//!   user-level `~/.npmrc` by default, preventing sensitive tokens from being checked into source control.
17//! - **Git Safety Checks**: Reports Git ignore status when local credentials are requested,
18//!   allowing callers to warn when `.npmrc` is not properly ignored.
19//! - **Yarn Support**: Detects and updates `npmScopes` authentication in `.yarnrc.yml`.
20//! - **Bun Support**: Discovers registries in `bunfig.toml` and optionally manages a local
21//!   `.env.local` token reference.
22//!
23//! The `cli` feature is enabled by default and provides the interactive CLIs and CLI modules.
24//! The token-only executable also builds without this feature.
25//! Library consumers can disable it with `default-features = false` to omit CLI dependencies.
26//! The example below requires Tokio with the `macros` and `rt-multi-thread` features in the
27//! consuming application.
28//!
29//! ### Library Usage Example
30//!
31//! ```no_run
32//! use node_auth::{run, Options};
33//!
34//! #[tokio::main]
35//! async fn main() -> Result<(), node_auth::AuthError> {
36//!     let options = Options {
37//!         token: Some("custom-token".to_string()),
38//!         ..Default::default()
39//!     };
40//!     run(&options).await?;
41//!     Ok(())
42//! }
43//! ```
44
45#![warn(missing_docs)]
46
47pub mod auth;
48pub mod bunfig;
49#[cfg(feature = "cli")]
50pub mod cli;
51pub mod error;
52pub mod fs;
53#[cfg(feature = "cli")]
54pub mod logger;
55pub mod npmrc;
56pub mod pnpm;
57pub mod registry;
58mod registry_query;
59pub mod token;
60pub mod vcs;
61pub mod yarnrc;
62
63pub use error::AuthError;
64use std::path::{Path, PathBuf};
65
66/// Result of a library authentication run.
67pub enum RunOutcome {
68  /// The requested token, with no configuration files modified.
69  Token(String),
70  /// Paths replaced, and the Git safety status for local credentials if applicable.
71  Updated {
72    /// Absolute paths successfully replaced.
73    paths: Vec<PathBuf>,
74    /// Git status of the local `.npmrc` when `local_credential` was requested.
75    git_status: Option<vcs::GitStatus>,
76    /// Git safety status for `.env.local` when `bun_env` was requested.
77    bun_env_git_status: Option<vcs::GitStatus>,
78  },
79}
80
81impl std::fmt::Debug for RunOutcome {
82  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83    match self {
84      Self::Token(_) => formatter.write_str("Token([redacted])"),
85      Self::Updated {
86        paths,
87        git_status,
88        bun_env_git_status,
89      } => formatter
90        .debug_struct("Updated")
91        .field("paths", paths)
92        .field("git_status", git_status)
93        .field("bun_env_git_status", bun_env_git_status)
94        .finish(),
95    }
96  }
97}
98
99/// Configuration options for configuring Node authentication.
100#[derive(Clone, Default)]
101pub struct Options {
102  /// Path to the `.npmrc` file to read registry configs from.
103  /// Defaults to project-level `.npmrc` if present, otherwise user-level `~/.npmrc`.
104  pub repo_config: Option<PathBuf>,
105
106  /// Path to the `.npmrc` file to write credentials to.
107  /// Defaults to user-level `~/.npmrc`.
108  pub credential_config: Option<PathBuf>,
109
110  /// Path to the `.yarnrc.yml` file to read registry configs from.
111  /// Defaults to project-level `.yarnrc.yml` if present, otherwise user-level `~/.yarnrc.yml`.
112  pub repo_config_yarn: Option<PathBuf>,
113
114  /// Path to the `.yarnrc.yml` file to write credentials to.
115  /// Defaults to user-level `~/.yarnrc.yml`.
116  pub credential_config_yarn: Option<PathBuf>,
117
118  /// Path to the project `bunfig.toml` used to discover Bun registry configuration.
119  /// Defaults to `./bunfig.toml`.
120  pub repo_config_bun: Option<PathBuf>,
121
122  /// Forces writing credentials to the current directory's `.npmrc`.
123  pub local_credential: bool,
124
125  /// Explicit OAuth2 access token to use instead of querying ADC or `gcloud`.
126  pub token: Option<String>,
127
128  /// Allow all HTTPS registry domains to receive the auth token (not only `*-npm.pkg.dev`).
129  pub allow_all_domains: bool,
130
131  /// Explicitly enable (`Some(true)`) or disable (`Some(false)`) updating `.yarnrc.yml`.
132  /// When `None`, Yarn updating is auto-detected based on `.yarnrc.yml` presence.
133  pub yarn: Option<bool>,
134
135  /// Explicitly enable (`Some(true)`) or disable (`Some(false)`) reading `bunfig.toml`.
136  /// When `None`, Bun support is auto-detected from `./bunfig.toml`.
137  pub bun: Option<bool>,
138
139  /// Write Bun's token to `.env.local` and reference it from the project `bunfig.toml`.
140  pub bun_env: bool,
141
142  /// Only retrieve and print the access token to standard output without modifying files.
143  pub print_token: bool,
144}
145
146impl std::fmt::Debug for Options {
147  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148    formatter
149      .debug_struct("Options")
150      .field("repo_config", &self.repo_config)
151      .field("credential_config", &self.credential_config)
152      .field("repo_config_yarn", &self.repo_config_yarn)
153      .field("credential_config_yarn", &self.credential_config_yarn)
154      .field("repo_config_bun", &self.repo_config_bun)
155      .field("local_credential", &self.local_credential)
156      .field("token", &self.token.as_ref().map(|_| "[redacted]"))
157      .field("allow_all_domains", &self.allow_all_domains)
158      .field("yarn", &self.yarn)
159      .field("bun", &self.bun)
160      .field("bun_env", &self.bun_env)
161      .field("print_token", &self.print_token)
162      .finish()
163  }
164}
165
166/// Executes authentication and updates `.npmrc` and `.yarnrc.yml` configuration files.
167///
168/// # Arguments
169///
170/// * `options` - Parameters controlling file paths, tokens, and domain restrictions.
171///
172/// # Errors
173///
174/// Returns [`AuthError`] if authentication fails, files cannot be read/written,
175/// or no Artifact Registry configuration is discovered.
176pub async fn run(options: &Options) -> Result<RunOutcome, AuthError> {
177  if options.bun_env && options.local_credential {
178    return Err(AuthError::BunEnvLocalCredentialConflict);
179  }
180
181  if options.bun_env && options.bun == Some(false) {
182    return Err(AuthError::BunEnvDisabledConflict);
183  }
184
185  let token = auth::get_credentials(options.token.as_deref()).await?;
186
187  token::validate_token(&token)?;
188
189  if options.print_token {
190    return Ok(RunOutcome::Token(token));
191  }
192
193  let discovery = if options.repo_config.is_none() && options.repo_config_yarn.is_none() {
194    let manager = registry_query::detect(&std::env::current_dir()?)?;
195    if manager == registry_query::Manager::Yarn && options.yarn == Some(false) {
196      None
197    } else {
198      registry_query::query(manager)?
199    }
200  } else {
201    None
202  };
203  let modern_yarn = discovery.as_ref().is_some_and(|d| d.modern_yarn);
204
205  let home_dir = dirs::home_dir()
206    .ok_or_else(|| AuthError::Config("Unable to determine user home directory".to_string()))?;
207
208  let discovered_npmrc = discovery
209    .as_ref()
210    .map(|d| d.project_root.join(".npmrc"))
211    .filter(|p| p.is_file());
212
213  // Determine npmrc paths
214  let (repo_npmrc, cred_npmrc, git_status) = if options.local_credential {
215    let cwd = std::env::current_dir()?;
216    let git_status = vcs::check_git_status(&cwd);
217
218    let local_npmrc = cwd.join(".npmrc");
219
220    let repo = if let Some(ref r) = options.repo_config {
221      r.clone()
222    } else if let Some(source) = &discovered_npmrc {
223      source.clone()
224    } else if local_npmrc.exists() {
225      local_npmrc.clone()
226    } else {
227      home_dir.join(".npmrc")
228    };
229
230    (repo, local_npmrc, Some(git_status))
231  } else {
232    let repo = options.repo_config.clone().unwrap_or_else(|| {
233      let local = Path::new(".npmrc");
234      if let Some(source) = &discovered_npmrc {
235        source.clone()
236      } else if local.exists() {
237        local.to_path_buf()
238      } else {
239        home_dir.join(".npmrc")
240      }
241    });
242
243    let cred = options
244      .credential_config
245      .clone()
246      .unwrap_or_else(|| home_dir.join(".npmrc"));
247
248    (repo, cred, None)
249  };
250
251  // Determine yarnrc paths
252  let repo_yarn = options.repo_config_yarn.clone().unwrap_or_else(|| {
253    let local = Path::new(".yarnrc.yml");
254    if local.exists() {
255      local.to_path_buf()
256    } else {
257      home_dir.join(".yarnrc.yml")
258    }
259  });
260
261  let cred_yarn = options
262    .credential_config_yarn
263    .clone()
264    .unwrap_or_else(|| home_dir.join(".yarnrc.yml"));
265
266  let should_update_yarn = modern_yarn
267    || match options.yarn {
268      Some(explicit) => explicit,
269      None => {
270        options.repo_config_yarn.is_some()
271          || options.credential_config_yarn.is_some()
272          || Path::new(".yarnrc.yml").exists()
273      }
274    };
275
276  let repo_bun = options
277    .repo_config_bun
278    .clone()
279    .unwrap_or_else(|| PathBuf::from("bunfig.toml"));
280  let should_update_bun = options.bun_env
281    || match options.bun {
282      Some(explicit) => explicit,
283      None => options.repo_config_bun.is_some() || Path::new("bunfig.toml").exists(),
284    };
285
286  let repo_npmrc = fs::resolve(&repo_npmrc)?;
287  let cred_npmrc = fs::resolve(&cred_npmrc)?;
288
289  let repo_yarn = if should_update_yarn {
290    Some(fs::resolve(&repo_yarn)?)
291  } else {
292    None
293  };
294  let cred_yarn = if should_update_yarn {
295    Some(fs::resolve(&cred_yarn)?)
296  } else {
297    None
298  };
299
300  let repo_bun = if should_update_bun {
301    Some(fs::resolve(&repo_bun)?)
302  } else {
303    None
304  };
305  let bun_env_path = if options.bun_env {
306    let parent = repo_bun
307      .as_ref()
308      .and_then(|path| path.parent())
309      .ok_or_else(|| AuthError::Config("bunfig.toml has no parent directory".to_string()))?;
310    Some(fs::resolve(&parent.join(".env.local"))?)
311  } else {
312    None
313  };
314  let bun_env_git_status = bun_env_path
315    .as_ref()
316    .map(|path| vcs::check_path_status(path.parent().unwrap(), Path::new(".env.local")));
317
318  let mut paths = vec![repo_npmrc.clone(), cred_npmrc.clone()];
319
320  if let Some(path) = &repo_yarn {
321    paths.push(path.clone());
322  }
323
324  if let Some(path) = &cred_yarn {
325    paths.push(path.clone());
326  }
327
328  if let Some(path) = &repo_bun {
329    paths.push(path.clone());
330  }
331
332  if let Some(path) = &bun_env_path {
333    paths.push(path.clone());
334  }
335
336  let mut transaction = fs::FileTransaction::new(&paths)?;
337
338  let bun_registries = if let Some(path) = &repo_bun {
339    if !transaction.existed(path)? {
340      return Err(AuthError::Config(format!(
341        "Bun configuration does not exist: {}",
342        path.display()
343      )));
344    }
345
346    bunfig::registry_urls(transaction.contents(path)?, options.allow_all_domains)?
347  } else {
348    Vec::new()
349  };
350
351  let npm_source = transaction.contents(&repo_npmrc)?.to_owned();
352  let npm_target = transaction.contents(&cred_npmrc)?.to_owned();
353  let mut npm_registries = if let Some(discovery) = discovery.as_ref().filter(|_| !modern_yarn) {
354    discovery.registries(options.allow_all_domains)?
355  } else {
356    None
357  };
358  if !options.local_credential && !options.bun_env && !bun_registries.is_empty() {
359    if npm_registries.is_none() {
360      let parser = npmrc::NpmrcParser::new(options.allow_all_domains)?;
361      let policy = registry::RegistryPolicy {
362        allow_all_domains: options.allow_all_domains,
363      };
364      let mut registries = Vec::new();
365      for line in npm_source.lines().chain(npm_target.lines()) {
366        if let npmrc::NpmrcConfigType::Registry { registry, .. } = parser.parse_line(line)?
367          && let Some(registry) = policy.parse_npm_key(&registry)?
368        {
369          registries.push(registry);
370        }
371      }
372      npm_registries = Some(registries);
373    }
374    npm_registries.as_mut().unwrap().extend(bun_registries);
375  }
376  let npm_has_registry = match &npm_registries {
377    Some(registries) => !registries.is_empty(),
378    None => npmrc::has_registry(&npm_source, &npm_target, options.allow_all_domains)?,
379  };
380
381  if npm_has_registry {
382    let same_file = repo_npmrc == cred_npmrc;
383    let (cleaned, updated) = npmrc::transform_npmrc_contents_with_registries(
384      &npm_source,
385      &npm_target,
386      &token,
387      options.allow_all_domains,
388      same_file,
389      npm_registries.as_deref(),
390    )?;
391
392    transaction.stage(&cred_npmrc, &updated)?;
393
394    if !same_file && transaction.existed(&repo_npmrc)? && cleaned != npm_source {
395      transaction.stage(&repo_npmrc, &cleaned)?;
396    }
397  }
398
399  if let (Some(source), Some(target)) = (repo_yarn, cred_yarn) {
400    let source_content = transaction.contents(&source)?.to_owned();
401    let target_content = transaction.contents(&target)?.to_owned();
402    let updated = if modern_yarn {
403      yarnrc::transform_resolved_registries(
404        &target_content,
405        &token,
406        &discovery
407          .as_ref()
408          .unwrap()
409          .registries(options.allow_all_domains)?
410          .unwrap_or_default(),
411        &discovery.as_ref().unwrap().yarn_scopes,
412      )?
413    } else {
414      yarnrc::transform_yarnrc_contents_with_policy(
415        &source_content,
416        &target_content,
417        &token,
418        options.allow_all_domains,
419      )?
420    };
421    if let Some(updated) = updated {
422      transaction.stage(&target, &updated)?;
423    }
424  }
425
426  if options.bun_env {
427    let bun_path = repo_bun.as_ref().unwrap();
428    let bun_content = transaction.contents(bun_path)?.to_owned();
429    let updated_bun = bunfig::transform_bunfig_for_env(&bun_content, options.allow_all_domains)?
430      .ok_or_else(|| {
431        AuthError::Config("No eligible registry configuration found in bunfig.toml".to_string())
432      })?;
433
434    if updated_bun != bun_content {
435      transaction.stage(bun_path, &updated_bun)?;
436    }
437
438    let env_path = bun_env_path.as_ref().unwrap();
439    let env_content = transaction.contents(env_path)?.to_owned();
440    let updated_env = bunfig::transform_env_local(&env_content, &token)?;
441    if updated_env != env_content {
442      transaction.stage(env_path, &updated_env)?;
443    }
444  }
445
446  let paths = transaction.commit()?;
447  if paths.is_empty() {
448    return Err(AuthError::Config(
449      "No eligible Artifact Registry configuration found".to_string(),
450    ));
451  }
452
453  if let Some(discovery) = discovery {
454    discovery.save();
455  }
456
457  Ok(RunOutcome::Updated {
458    paths,
459    git_status,
460    bun_env_git_status,
461  })
462}
463
464/// Executes authentication synchronously using a temporary Tokio runtime.
465///
466/// This helper works without the `cli` feature or any runtime setup by the caller.
467/// Each call creates a current-thread runtime with I/O and timers enabled, runs
468/// [`run`], and drops the runtime before returning. It does not initialize logging
469/// or print the outcome.
470///
471/// Call this from synchronous code. Within an async Tokio context, use [`run`]
472/// directly. Threads entered into a Tokio runtime, including `spawn_blocking`
473/// threads, are rejected.
474///
475/// # Errors
476///
477/// Returns [`AuthError::Config`] when called within an active Tokio runtime,
478/// [`AuthError::Io`] if runtime creation fails, or any error returned by [`run`].
479///
480/// # Example
481///
482/// ```no_run
483/// use node_auth::{run_blocking, Options};
484///
485/// fn main() -> Result<(), node_auth::AuthError> {
486///     let outcome = run_blocking(&Options::default())?;
487///     // Handle the returned token or updated configuration paths.
488///     Ok(())
489/// }
490/// ```
491pub fn run_blocking(options: &Options) -> Result<RunOutcome, AuthError> {
492  if tokio::runtime::Handle::try_current().is_ok() {
493    return Err(AuthError::Config(
494      "run_blocking cannot be called within an active Tokio runtime; use run().await".to_string(),
495    ));
496  }
497
498  let runtime = tokio::runtime::Builder::new_current_thread()
499    .enable_all()
500    .build()?;
501  runtime.block_on(run(options))
502}
503
504#[cfg(test)]
505mod tests {
506  use super::*;
507
508  #[tokio::test]
509  async fn bun_option_conflicts_return_dedicated_errors() {
510    let options = Options {
511      bun_env: true,
512      local_credential: true,
513      ..Options::default()
514    };
515    assert!(matches!(
516      run(&options).await,
517      Err(AuthError::BunEnvLocalCredentialConflict)
518    ));
519
520    let options = Options {
521      local_credential: false,
522      bun: Some(false),
523      ..options
524    };
525    assert!(matches!(
526      run(&options).await,
527      Err(AuthError::BunEnvDisabledConflict)
528    ));
529  }
530
531  #[test]
532  fn blocking_run_returns_token_and_propagates_errors() {
533    let mut options = Options {
534      token: Some("valid-token".to_string()),
535      print_token: true,
536      ..Default::default()
537    };
538    assert!(
539      matches!(run_blocking(&options).unwrap(), RunOutcome::Token(token) if token == "valid-token")
540    );
541
542    options.token = Some("invalid\ntoken".to_string());
543    assert!(run_blocking(&options).is_err());
544  }
545
546  #[test]
547  fn blocking_run_updates_configuration_without_cli() {
548    let dir = tempfile::tempdir().unwrap();
549    let source = dir.path().join("project.npmrc");
550    let target = dir.path().join("user.npmrc");
551
552    std::fs::write(&source, "registry=https://us-npm.pkg.dev/project/repo/\n").unwrap();
553
554    let options = Options {
555      token: Some("valid-token".to_string()),
556      repo_config: Some(source),
557      credential_config: Some(target.clone()),
558      yarn: Some(false),
559      bun: Some(false),
560      ..Default::default()
561    };
562    assert!(
563      matches!(run_blocking(&options).unwrap(), RunOutcome::Updated { paths, .. } if paths.contains(&fs::resolve(&target).unwrap()))
564    );
565    assert!(
566      std::fs::read_to_string(target)
567        .unwrap()
568        .contains("//us-npm.pkg.dev/project/repo/:_authToken=\"valid-token\"")
569    );
570  }
571
572  #[tokio::test]
573  async fn blocking_run_rejects_nested_runtime_without_panicking() {
574    let options = Options {
575      token: Some("valid-token".to_string()),
576      print_token: true,
577      ..Default::default()
578    };
579    assert!(
580      matches!(run_blocking(&options), Err(AuthError::Config(message)) if message.contains("active Tokio runtime"))
581    );
582    assert!(matches!(run(&options).await.unwrap(), RunOutcome::Token(_)));
583  }
584}