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/// Useful result of a library authentication run, with presentation left to callers.
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  if options.bun_env && options.bun == Some(false) {
180    return Err(AuthError::BunEnvDisabledConflict);
181  }
182  let token = auth::get_credentials(options.token.as_deref()).await?;
183  token::validate_token(&token)?;
184  if options.print_token {
185    return Ok(RunOutcome::Token(token));
186  }
187
188  let home_dir = dirs::home_dir()
189    .ok_or_else(|| AuthError::Config("Unable to determine user home directory".to_string()))?;
190
191  // Determine npmrc paths
192  let (repo_npmrc, cred_npmrc, git_status) = if options.local_credential {
193    let cwd = std::env::current_dir()?;
194    let git_status = vcs::check_git_status(&cwd);
195
196    let local_npmrc = cwd.join(".npmrc");
197
198    let repo = if let Some(ref r) = options.repo_config {
199      r.clone()
200    } else if local_npmrc.exists() {
201      local_npmrc.clone()
202    } else {
203      home_dir.join(".npmrc")
204    };
205
206    (repo, local_npmrc, Some(git_status))
207  } else {
208    let repo = options.repo_config.clone().unwrap_or_else(|| {
209      let local = Path::new(".npmrc");
210      if local.exists() {
211        local.to_path_buf()
212      } else {
213        home_dir.join(".npmrc")
214      }
215    });
216
217    let cred = options
218      .credential_config
219      .clone()
220      .unwrap_or_else(|| home_dir.join(".npmrc"));
221
222    (repo, cred, None)
223  };
224
225  // Determine yarnrc paths
226  let repo_yarn = options.repo_config_yarn.clone().unwrap_or_else(|| {
227    let local = Path::new(".yarnrc.yml");
228    if local.exists() {
229      local.to_path_buf()
230    } else {
231      home_dir.join(".yarnrc.yml")
232    }
233  });
234
235  let cred_yarn = options
236    .credential_config_yarn
237    .clone()
238    .unwrap_or_else(|| home_dir.join(".yarnrc.yml"));
239
240  let should_update_yarn = match options.yarn {
241    Some(explicit) => explicit,
242    None => {
243      options.repo_config_yarn.is_some()
244        || options.credential_config_yarn.is_some()
245        || Path::new(".yarnrc.yml").exists()
246    }
247  };
248
249  let repo_bun = options
250    .repo_config_bun
251    .clone()
252    .unwrap_or_else(|| PathBuf::from("bunfig.toml"));
253  let should_update_bun = options.bun_env
254    || match options.bun {
255      Some(explicit) => explicit,
256      None => options.repo_config_bun.is_some() || Path::new("bunfig.toml").exists(),
257    };
258
259  let repo_npmrc = fs::resolve(&repo_npmrc)?;
260  let cred_npmrc = fs::resolve(&cred_npmrc)?;
261  let repo_yarn = if should_update_yarn {
262    Some(fs::resolve(&repo_yarn)?)
263  } else {
264    None
265  };
266  let cred_yarn = if should_update_yarn {
267    Some(fs::resolve(&cred_yarn)?)
268  } else {
269    None
270  };
271  let repo_bun = if should_update_bun {
272    Some(fs::resolve(&repo_bun)?)
273  } else {
274    None
275  };
276  let bun_env_path = if options.bun_env {
277    let parent = repo_bun
278      .as_ref()
279      .and_then(|path| path.parent())
280      .ok_or_else(|| AuthError::Config("bunfig.toml has no parent directory".to_string()))?;
281    Some(fs::resolve(&parent.join(".env.local"))?)
282  } else {
283    None
284  };
285  let bun_env_git_status = bun_env_path
286    .as_ref()
287    .map(|path| vcs::check_path_status(path.parent().unwrap(), Path::new(".env.local")));
288
289  let mut paths = vec![repo_npmrc.clone(), cred_npmrc.clone()];
290  if let Some(path) = &repo_yarn {
291    paths.push(path.clone());
292  }
293  if let Some(path) = &cred_yarn {
294    paths.push(path.clone());
295  }
296  if let Some(path) = &repo_bun {
297    paths.push(path.clone());
298  }
299  if let Some(path) = &bun_env_path {
300    paths.push(path.clone());
301  }
302  let mut transaction = fs::FileTransaction::new(&paths)?;
303
304  let bun_registries = if let Some(path) = &repo_bun {
305    if !transaction.existed(path)? {
306      return Err(AuthError::Config(format!(
307        "Bun configuration does not exist: {}",
308        path.display()
309      )));
310    }
311    bunfig::registry_urls(transaction.contents(path)?, options.allow_all_domains)?
312  } else {
313    Vec::new()
314  };
315
316  let npm_source = transaction.contents(&repo_npmrc)?.to_owned();
317  let npm_target = transaction.contents(&cred_npmrc)?.to_owned();
318  let npm_has_registry = npmrc::has_registry(&npm_source, &npm_target, options.allow_all_domains)?;
319  let bun_npm_registries = if options.local_credential || options.bun_env {
320    &[][..]
321  } else {
322    bun_registries.as_slice()
323  };
324  if npm_has_registry || !bun_npm_registries.is_empty() {
325    let same_file = repo_npmrc == cred_npmrc;
326    let (cleaned, updated) = npmrc::transform_npmrc_contents_with_registries(
327      &npm_source,
328      &npm_target,
329      &token,
330      options.allow_all_domains,
331      same_file,
332      bun_npm_registries,
333    )?;
334    transaction.stage(&cred_npmrc, &updated)?;
335    if !same_file && transaction.existed(&repo_npmrc)? && cleaned != npm_source {
336      transaction.stage(&repo_npmrc, &cleaned)?;
337    }
338  }
339
340  if let (Some(source), Some(target)) = (repo_yarn, cred_yarn) {
341    let source_content = transaction.contents(&source)?.to_owned();
342    let target_content = transaction.contents(&target)?.to_owned();
343    if let Some(updated) = yarnrc::transform_yarnrc_contents_with_policy(
344      &source_content,
345      &target_content,
346      &token,
347      options.allow_all_domains,
348    )? {
349      transaction.stage(&target, &updated)?;
350    }
351  }
352
353  if options.bun_env {
354    let bun_path = repo_bun.as_ref().unwrap();
355    let bun_content = transaction.contents(bun_path)?.to_owned();
356    let updated_bun = bunfig::transform_bunfig_for_env(&bun_content, options.allow_all_domains)?
357      .ok_or_else(|| {
358        AuthError::Config("No eligible registry configuration found in bunfig.toml".to_string())
359      })?;
360    if updated_bun != bun_content {
361      transaction.stage(bun_path, &updated_bun)?;
362    }
363
364    let env_path = bun_env_path.as_ref().unwrap();
365    let env_content = transaction.contents(env_path)?.to_owned();
366    let updated_env = bunfig::transform_env_local(&env_content, &token)?;
367    if updated_env != env_content {
368      transaction.stage(env_path, &updated_env)?;
369    }
370  }
371
372  let paths = transaction.commit()?;
373  if paths.is_empty() {
374    return Err(AuthError::Config(
375      "No eligible Artifact Registry configuration found".to_string(),
376    ));
377  }
378  Ok(RunOutcome::Updated {
379    paths,
380    git_status,
381    bun_env_git_status,
382  })
383}
384
385/// Executes authentication synchronously using a temporary Tokio runtime.
386///
387/// This helper works without the `cli` feature or any runtime setup by the caller.
388/// Each call creates a current-thread runtime with I/O and timers enabled, runs
389/// [`run`], and drops the runtime before returning. It does not initialize logging
390/// or print the outcome.
391///
392/// Call this from synchronous code. Within an async Tokio context, use [`run`]
393/// directly. Threads entered into a Tokio runtime, including `spawn_blocking`
394/// threads, are rejected.
395///
396/// # Errors
397///
398/// Returns [`AuthError::Config`] when called within an active Tokio runtime,
399/// [`AuthError::Io`] if runtime creation fails, or any error returned by [`run`].
400///
401/// # Example
402///
403/// ```no_run
404/// use node_auth::{run_blocking, Options};
405///
406/// fn main() -> Result<(), node_auth::AuthError> {
407///     let outcome = run_blocking(&Options::default())?;
408///     // Handle the returned token or updated configuration paths.
409///     Ok(())
410/// }
411/// ```
412pub fn run_blocking(options: &Options) -> Result<RunOutcome, AuthError> {
413  if tokio::runtime::Handle::try_current().is_ok() {
414    return Err(AuthError::Config(
415      "run_blocking cannot be called within an active Tokio runtime; use run().await".to_string(),
416    ));
417  }
418  let runtime = tokio::runtime::Builder::new_current_thread()
419    .enable_all()
420    .build()?;
421  runtime.block_on(run(options))
422}
423
424#[cfg(test)]
425mod tests {
426  use super::*;
427
428  #[tokio::test]
429  async fn bun_option_conflicts_return_dedicated_errors() {
430    let options = Options {
431      bun_env: true,
432      local_credential: true,
433      ..Options::default()
434    };
435    assert!(matches!(
436      run(&options).await,
437      Err(AuthError::BunEnvLocalCredentialConflict)
438    ));
439    let options = Options {
440      local_credential: false,
441      bun: Some(false),
442      ..options
443    };
444    assert!(matches!(
445      run(&options).await,
446      Err(AuthError::BunEnvDisabledConflict)
447    ));
448  }
449
450  #[test]
451  fn blocking_run_returns_token_and_propagates_errors() {
452    let mut options = Options {
453      token: Some("valid-token".to_string()),
454      print_token: true,
455      ..Default::default()
456    };
457    assert!(
458      matches!(run_blocking(&options).unwrap(), RunOutcome::Token(token) if token == "valid-token")
459    );
460    options.token = Some("invalid\ntoken".to_string());
461    assert!(run_blocking(&options).is_err());
462  }
463
464  #[test]
465  fn blocking_run_updates_configuration_without_cli() {
466    let dir = tempfile::tempdir().unwrap();
467    let source = dir.path().join("project.npmrc");
468    let target = dir.path().join("user.npmrc");
469    std::fs::write(&source, "registry=https://us-npm.pkg.dev/project/repo/\n").unwrap();
470    let options = Options {
471      token: Some("valid-token".to_string()),
472      repo_config: Some(source),
473      credential_config: Some(target.clone()),
474      yarn: Some(false),
475      bun: Some(false),
476      ..Default::default()
477    };
478    assert!(
479      matches!(run_blocking(&options).unwrap(), RunOutcome::Updated { paths, .. } if paths.contains(&fs::resolve(&target).unwrap()))
480    );
481    assert!(
482      std::fs::read_to_string(target)
483        .unwrap()
484        .contains("//us-npm.pkg.dev/project/repo/:_authToken=\"valid-token\"")
485    );
486  }
487
488  #[tokio::test]
489  async fn blocking_run_rejects_nested_runtime_without_panicking() {
490    let options = Options {
491      token: Some("valid-token".to_string()),
492      print_token: true,
493      ..Default::default()
494    };
495    assert!(
496      matches!(run_blocking(&options), Err(AuthError::Config(message)) if message.contains("active Tokio runtime"))
497    );
498    assert!(matches!(run(&options).await.unwrap(), RunOutcome::Token(_)));
499  }
500}