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