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