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;
58pub mod token;
59pub mod vcs;
60pub mod yarnrc;
61
62pub use error::AuthError;
63use std::path::{Path, PathBuf};
64
65/// Result of a library authentication run.
66pub enum RunOutcome {
67  /// The requested token, with no configuration files modified.
68  Token(String),
69  /// Paths replaced, and the Git safety status for local credentials if applicable.
70  Updated {
71    /// Absolute paths successfully replaced.
72    paths: Vec<PathBuf>,
73    /// Git status of the local `.npmrc` when `local_credential` was requested.
74    git_status: Option<vcs::GitStatus>,
75    /// Git safety status for `.env.local` when `bun_env` was requested.
76    bun_env_git_status: Option<vcs::GitStatus>,
77  },
78}
79
80impl std::fmt::Debug for RunOutcome {
81  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82    match self {
83      Self::Token(_) => formatter.write_str("Token([redacted])"),
84      Self::Updated {
85        paths,
86        git_status,
87        bun_env_git_status,
88      } => formatter
89        .debug_struct("Updated")
90        .field("paths", paths)
91        .field("git_status", git_status)
92        .field("bun_env_git_status", bun_env_git_status)
93        .finish(),
94    }
95  }
96}
97
98/// Configuration options for configuring Node authentication.
99#[derive(Clone, Default)]
100pub struct Options {
101  /// Path to the `.npmrc` file to read registry configs from.
102  /// Defaults to project-level `.npmrc` if present, otherwise user-level `~/.npmrc`.
103  pub repo_config: Option<PathBuf>,
104
105  /// Path to the `.npmrc` file to write credentials to.
106  /// Defaults to user-level `~/.npmrc`.
107  pub credential_config: Option<PathBuf>,
108
109  /// Path to the `.yarnrc.yml` file to read registry configs from.
110  /// Defaults to project-level `.yarnrc.yml` if present, otherwise user-level `~/.yarnrc.yml`.
111  pub repo_config_yarn: Option<PathBuf>,
112
113  /// Path to the `.yarnrc.yml` file to write credentials to.
114  /// Defaults to user-level `~/.yarnrc.yml`.
115  pub credential_config_yarn: Option<PathBuf>,
116
117  /// Path to the project `bunfig.toml` used to discover Bun registry configuration.
118  /// Defaults to `./bunfig.toml`.
119  pub repo_config_bun: Option<PathBuf>,
120
121  /// Forces writing credentials to the current directory's `.npmrc`.
122  pub local_credential: bool,
123
124  /// Explicit OAuth2 access token to use instead of querying ADC or `gcloud`.
125  pub token: Option<String>,
126
127  /// Allow all HTTPS registry domains to receive the auth token (not only `*-npm.pkg.dev`).
128  pub allow_all_domains: bool,
129
130  /// Explicitly enable (`Some(true)`) or disable (`Some(false)`) updating `.yarnrc.yml`.
131  /// When `None`, Yarn updating is auto-detected based on `.yarnrc.yml` presence.
132  pub yarn: Option<bool>,
133
134  /// Explicitly enable (`Some(true)`) or disable (`Some(false)`) reading `bunfig.toml`.
135  /// When `None`, Bun support is auto-detected from `./bunfig.toml`.
136  pub bun: Option<bool>,
137
138  /// Write Bun's token to `.env.local` and reference it from the project `bunfig.toml`.
139  pub bun_env: bool,
140
141  /// Only retrieve and print the access token to standard output without modifying files.
142  pub print_token: bool,
143}
144
145impl std::fmt::Debug for Options {
146  fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147    formatter
148      .debug_struct("Options")
149      .field("repo_config", &self.repo_config)
150      .field("credential_config", &self.credential_config)
151      .field("repo_config_yarn", &self.repo_config_yarn)
152      .field("credential_config_yarn", &self.credential_config_yarn)
153      .field("repo_config_bun", &self.repo_config_bun)
154      .field("local_credential", &self.local_credential)
155      .field("token", &self.token.as_ref().map(|_| "[redacted]"))
156      .field("allow_all_domains", &self.allow_all_domains)
157      .field("yarn", &self.yarn)
158      .field("bun", &self.bun)
159      .field("bun_env", &self.bun_env)
160      .field("print_token", &self.print_token)
161      .finish()
162  }
163}
164
165/// Executes authentication and updates `.npmrc` and `.yarnrc.yml` configuration files.
166///
167/// # Arguments
168///
169/// * `options` - Parameters controlling file paths, tokens, and domain restrictions.
170///
171/// # Errors
172///
173/// Returns [`AuthError`] if authentication fails, files cannot be read/written,
174/// or no Artifact Registry configuration is discovered.
175pub async fn run(options: &Options) -> Result<RunOutcome, AuthError> {
176  if options.bun_env && options.local_credential {
177    return Err(AuthError::BunEnvLocalCredentialConflict);
178  }
179
180  if options.bun_env && options.bun == Some(false) {
181    return Err(AuthError::BunEnvDisabledConflict);
182  }
183
184  let token = auth::get_credentials(options.token.as_deref()).await?;
185
186  token::validate_token(&token)?;
187
188  if options.print_token {
189    return Ok(RunOutcome::Token(token));
190  }
191
192  let home_dir = dirs::home_dir()
193    .ok_or_else(|| AuthError::Config("Unable to determine user home directory".to_string()))?;
194
195  // Determine npmrc paths
196  let (repo_npmrc, cred_npmrc, git_status) = if options.local_credential {
197    let cwd = std::env::current_dir()?;
198    let git_status = vcs::check_git_status(&cwd);
199
200    let local_npmrc = cwd.join(".npmrc");
201
202    let repo = if let Some(ref r) = options.repo_config {
203      r.clone()
204    } else if local_npmrc.exists() {
205      local_npmrc.clone()
206    } else {
207      home_dir.join(".npmrc")
208    };
209
210    (repo, local_npmrc, Some(git_status))
211  } else {
212    let repo = options.repo_config.clone().unwrap_or_else(|| {
213      let local = Path::new(".npmrc");
214      if local.exists() {
215        local.to_path_buf()
216      } else {
217        home_dir.join(".npmrc")
218      }
219    });
220
221    let cred = options
222      .credential_config
223      .clone()
224      .unwrap_or_else(|| home_dir.join(".npmrc"));
225
226    (repo, cred, None)
227  };
228
229  // Determine yarnrc paths
230  let repo_yarn = options.repo_config_yarn.clone().unwrap_or_else(|| {
231    let local = Path::new(".yarnrc.yml");
232    if local.exists() {
233      local.to_path_buf()
234    } else {
235      home_dir.join(".yarnrc.yml")
236    }
237  });
238
239  let cred_yarn = options
240    .credential_config_yarn
241    .clone()
242    .unwrap_or_else(|| home_dir.join(".yarnrc.yml"));
243
244  let should_update_yarn = match options.yarn {
245    Some(explicit) => explicit,
246    None => {
247      options.repo_config_yarn.is_some()
248        || options.credential_config_yarn.is_some()
249        || Path::new(".yarnrc.yml").exists()
250    }
251  };
252
253  let repo_bun = options
254    .repo_config_bun
255    .clone()
256    .unwrap_or_else(|| PathBuf::from("bunfig.toml"));
257  let should_update_bun = options.bun_env
258    || match options.bun {
259      Some(explicit) => explicit,
260      None => options.repo_config_bun.is_some() || Path::new("bunfig.toml").exists(),
261    };
262
263  let repo_npmrc = fs::resolve(&repo_npmrc)?;
264  let cred_npmrc = fs::resolve(&cred_npmrc)?;
265
266  let repo_yarn = if should_update_yarn {
267    Some(fs::resolve(&repo_yarn)?)
268  } else {
269    None
270  };
271  let cred_yarn = if should_update_yarn {
272    Some(fs::resolve(&cred_yarn)?)
273  } else {
274    None
275  };
276
277  let repo_bun = if should_update_bun {
278    Some(fs::resolve(&repo_bun)?)
279  } else {
280    None
281  };
282  let bun_env_path = if options.bun_env {
283    let parent = repo_bun
284      .as_ref()
285      .and_then(|path| path.parent())
286      .ok_or_else(|| AuthError::Config("bunfig.toml has no parent directory".to_string()))?;
287    Some(fs::resolve(&parent.join(".env.local"))?)
288  } else {
289    None
290  };
291  let bun_env_git_status = bun_env_path
292    .as_ref()
293    .map(|path| vcs::check_path_status(path.parent().unwrap(), Path::new(".env.local")));
294
295  let mut paths = vec![repo_npmrc.clone(), cred_npmrc.clone()];
296
297  if let Some(path) = &repo_yarn {
298    paths.push(path.clone());
299  }
300
301  if let Some(path) = &cred_yarn {
302    paths.push(path.clone());
303  }
304
305  if let Some(path) = &repo_bun {
306    paths.push(path.clone());
307  }
308
309  if let Some(path) = &bun_env_path {
310    paths.push(path.clone());
311  }
312
313  let mut transaction = fs::FileTransaction::new(&paths)?;
314
315  let bun_registries = if let Some(path) = &repo_bun {
316    if !transaction.existed(path)? {
317      return Err(AuthError::Config(format!(
318        "Bun configuration does not exist: {}",
319        path.display()
320      )));
321    }
322
323    bunfig::registry_urls(transaction.contents(path)?, options.allow_all_domains)?
324  } else {
325    Vec::new()
326  };
327
328  let npm_source = transaction.contents(&repo_npmrc)?.to_owned();
329  let npm_target = transaction.contents(&cred_npmrc)?.to_owned();
330  let npm_has_registry = npmrc::has_registry(&npm_source, &npm_target, options.allow_all_domains)?;
331  let bun_npm_registries = if options.local_credential || options.bun_env {
332    &[][..]
333  } else {
334    bun_registries.as_slice()
335  };
336
337  if npm_has_registry || !bun_npm_registries.is_empty() {
338    let same_file = repo_npmrc == cred_npmrc;
339    let (cleaned, updated) = npmrc::transform_npmrc_contents_with_registries(
340      &npm_source,
341      &npm_target,
342      &token,
343      options.allow_all_domains,
344      same_file,
345      bun_npm_registries,
346    )?;
347
348    transaction.stage(&cred_npmrc, &updated)?;
349
350    if !same_file && transaction.existed(&repo_npmrc)? && cleaned != npm_source {
351      transaction.stage(&repo_npmrc, &cleaned)?;
352    }
353  }
354
355  if let (Some(source), Some(target)) = (repo_yarn, cred_yarn) {
356    let source_content = transaction.contents(&source)?.to_owned();
357    let target_content = transaction.contents(&target)?.to_owned();
358    if let Some(updated) = yarnrc::transform_yarnrc_contents_with_policy(
359      &source_content,
360      &target_content,
361      &token,
362      options.allow_all_domains,
363    )? {
364      transaction.stage(&target, &updated)?;
365    }
366  }
367
368  if options.bun_env {
369    let bun_path = repo_bun.as_ref().unwrap();
370    let bun_content = transaction.contents(bun_path)?.to_owned();
371    let updated_bun = bunfig::transform_bunfig_for_env(&bun_content, options.allow_all_domains)?
372      .ok_or_else(|| {
373        AuthError::Config("No eligible registry configuration found in bunfig.toml".to_string())
374      })?;
375
376    if updated_bun != bun_content {
377      transaction.stage(bun_path, &updated_bun)?;
378    }
379
380    let env_path = bun_env_path.as_ref().unwrap();
381    let env_content = transaction.contents(env_path)?.to_owned();
382    let updated_env = bunfig::transform_env_local(&env_content, &token)?;
383    if updated_env != env_content {
384      transaction.stage(env_path, &updated_env)?;
385    }
386  }
387
388  let paths = transaction.commit()?;
389  if paths.is_empty() {
390    return Err(AuthError::Config(
391      "No eligible Artifact Registry configuration found".to_string(),
392    ));
393  }
394
395  Ok(RunOutcome::Updated {
396    paths,
397    git_status,
398    bun_env_git_status,
399  })
400}
401
402/// Executes authentication synchronously using a temporary Tokio runtime.
403///
404/// This helper works without the `cli` feature or any runtime setup by the caller.
405/// Each call creates a current-thread runtime with I/O and timers enabled, runs
406/// [`run`], and drops the runtime before returning. It does not initialize logging
407/// or print the outcome.
408///
409/// Call this from synchronous code. Within an async Tokio context, use [`run`]
410/// directly. Threads entered into a Tokio runtime, including `spawn_blocking`
411/// threads, are rejected.
412///
413/// # Errors
414///
415/// Returns [`AuthError::Config`] when called within an active Tokio runtime,
416/// [`AuthError::Io`] if runtime creation fails, or any error returned by [`run`].
417///
418/// # Example
419///
420/// ```no_run
421/// use node_auth::{run_blocking, Options};
422///
423/// fn main() -> Result<(), node_auth::AuthError> {
424///     let outcome = run_blocking(&Options::default())?;
425///     // Handle the returned token or updated configuration paths.
426///     Ok(())
427/// }
428/// ```
429pub fn run_blocking(options: &Options) -> Result<RunOutcome, AuthError> {
430  if tokio::runtime::Handle::try_current().is_ok() {
431    return Err(AuthError::Config(
432      "run_blocking cannot be called within an active Tokio runtime; use run().await".to_string(),
433    ));
434  }
435
436  let runtime = tokio::runtime::Builder::new_current_thread()
437    .enable_all()
438    .build()?;
439  runtime.block_on(run(options))
440}
441
442#[cfg(test)]
443mod tests {
444  use super::*;
445
446  #[tokio::test]
447  async fn bun_option_conflicts_return_dedicated_errors() {
448    let options = Options {
449      bun_env: true,
450      local_credential: true,
451      ..Options::default()
452    };
453    assert!(matches!(
454      run(&options).await,
455      Err(AuthError::BunEnvLocalCredentialConflict)
456    ));
457
458    let options = Options {
459      local_credential: false,
460      bun: Some(false),
461      ..options
462    };
463    assert!(matches!(
464      run(&options).await,
465      Err(AuthError::BunEnvDisabledConflict)
466    ));
467  }
468
469  #[test]
470  fn blocking_run_returns_token_and_propagates_errors() {
471    let mut options = Options {
472      token: Some("valid-token".to_string()),
473      print_token: true,
474      ..Default::default()
475    };
476    assert!(
477      matches!(run_blocking(&options).unwrap(), RunOutcome::Token(token) if token == "valid-token")
478    );
479
480    options.token = Some("invalid\ntoken".to_string());
481    assert!(run_blocking(&options).is_err());
482  }
483
484  #[test]
485  fn blocking_run_updates_configuration_without_cli() {
486    let dir = tempfile::tempdir().unwrap();
487    let source = dir.path().join("project.npmrc");
488    let target = dir.path().join("user.npmrc");
489
490    std::fs::write(&source, "registry=https://us-npm.pkg.dev/project/repo/\n").unwrap();
491
492    let options = Options {
493      token: Some("valid-token".to_string()),
494      repo_config: Some(source),
495      credential_config: Some(target.clone()),
496      yarn: Some(false),
497      bun: Some(false),
498      ..Default::default()
499    };
500    assert!(
501      matches!(run_blocking(&options).unwrap(), RunOutcome::Updated { paths, .. } if paths.contains(&fs::resolve(&target).unwrap()))
502    );
503    assert!(
504      std::fs::read_to_string(target)
505        .unwrap()
506        .contains("//us-npm.pkg.dev/project/repo/:_authToken=\"valid-token\"")
507    );
508  }
509
510  #[tokio::test]
511  async fn blocking_run_rejects_nested_runtime_without_panicking() {
512    let options = Options {
513      token: Some("valid-token".to_string()),
514      print_token: true,
515      ..Default::default()
516    };
517    assert!(
518      matches!(run_blocking(&options), Err(AuthError::Config(message)) if message.contains("active Tokio runtime"))
519    );
520    assert!(matches!(run(&options).await.unwrap(), RunOutcome::Token(_)));
521  }
522}