Skip to main content

node_auth/
lib.rs

1//! # `node-auth`
2//!
3//! A fast, lightweight, standalone Rust CLI and library that authenticates Node package managers
4//! (**npm**, **yarn**, and **pnpm**) 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 Node, npm, or pnpm to be installed or configured 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//!
21//! ### Library Usage Example
22//!
23//! ```no_run
24//! use node_auth::{run, Options};
25//!
26//! #[tokio::main]
27//! async fn main() -> Result<(), node_auth::AuthError> {
28//!     let options = Options {
29//!         token: Some("custom-token".to_string()),
30//!         ..Default::default()
31//!     };
32//!     run(&options).await?;
33//!     Ok(())
34//! }
35//! ```
36
37#![warn(missing_docs)]
38
39pub mod auth;
40pub mod cli;
41pub mod error;
42pub mod fs;
43pub mod logger;
44pub mod npmrc;
45pub mod registry;
46pub mod token;
47pub mod vcs;
48pub mod yarnrc;
49
50pub use error::AuthError;
51use std::path::{Path, PathBuf};
52
53/// Useful result of a library authentication run, with presentation left to callers.
54pub enum RunOutcome {
55    /// The requested token, with no configuration files modified.
56    Token(String),
57    /// Paths replaced, and the Git safety status for local credentials if applicable.
58    Updated {
59        /// Absolute paths successfully replaced.
60        paths: Vec<PathBuf>,
61        /// Git status of the local `.npmrc` when `local_credential` was requested.
62        git_status: Option<vcs::GitStatus>,
63    },
64}
65
66impl std::fmt::Debug for RunOutcome {
67    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        match self {
69            Self::Token(_) => formatter.write_str("Token([redacted])"),
70            Self::Updated { paths, git_status } => formatter
71                .debug_struct("Updated")
72                .field("paths", paths)
73                .field("git_status", git_status)
74                .finish(),
75        }
76    }
77}
78
79/// Configuration options for configuring Node authentication.
80#[derive(Clone, Default)]
81pub struct Options {
82    /// Path to the `.npmrc` file to read registry configs from.
83    /// Defaults to project-level `.npmrc` if present, otherwise user-level `~/.npmrc`.
84    pub repo_config: Option<PathBuf>,
85
86    /// Path to the `.npmrc` file to write credentials to.
87    /// Defaults to user-level `~/.npmrc`.
88    pub credential_config: Option<PathBuf>,
89
90    /// Path to the `.yarnrc.yml` file to read registry configs from.
91    /// Defaults to project-level `.yarnrc.yml` if present, otherwise user-level `~/.yarnrc.yml`.
92    pub repo_config_yarn: Option<PathBuf>,
93
94    /// Path to the `.yarnrc.yml` file to write credentials to.
95    /// Defaults to user-level `~/.yarnrc.yml`.
96    pub credential_config_yarn: Option<PathBuf>,
97
98    /// Forces writing credentials to the current directory's `.npmrc`.
99    pub local_credential: bool,
100
101    /// Explicit OAuth2 access token to use instead of querying ADC or `gcloud`.
102    pub token: Option<String>,
103
104    /// Allow all registry domains to attach the auth token to (not only `*-npm.pkg.dev`).
105    pub allow_all_domains: bool,
106
107    /// Explicitly enable (`Some(true)`) or disable (`Some(false)`) updating `.yarnrc.yml`.
108    /// When `None`, Yarn updating is auto-detected based on `.yarnrc.yml` presence.
109    pub yarn: Option<bool>,
110
111    /// Only retrieve and print the access token to standard output without modifying files.
112    pub print_token: bool,
113}
114
115impl std::fmt::Debug for Options {
116    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        formatter
118            .debug_struct("Options")
119            .field("repo_config", &self.repo_config)
120            .field("credential_config", &self.credential_config)
121            .field("repo_config_yarn", &self.repo_config_yarn)
122            .field("credential_config_yarn", &self.credential_config_yarn)
123            .field("local_credential", &self.local_credential)
124            .field("token", &self.token.as_ref().map(|_| "[redacted]"))
125            .field("allow_all_domains", &self.allow_all_domains)
126            .field("yarn", &self.yarn)
127            .field("print_token", &self.print_token)
128            .finish()
129    }
130}
131
132/// Executes authentication and updates `.npmrc` and `.yarnrc.yml` configuration files.
133///
134/// # Arguments
135///
136/// * `options` - Parameters controlling file paths, tokens, and domain restrictions.
137///
138/// # Errors
139///
140/// Returns [`AuthError`] if authentication fails, files cannot be read/written,
141/// or no Artifact Registry configuration is discovered.
142pub async fn run(options: &Options) -> Result<RunOutcome, AuthError> {
143    let token = auth::get_credentials(options.token.as_deref()).await?;
144    token::validate_token(&token)?;
145    if options.print_token {
146        return Ok(RunOutcome::Token(token));
147    }
148
149    let home_dir = dirs::home_dir()
150        .ok_or_else(|| AuthError::Config("Unable to determine user home directory".to_string()))?;
151
152    // Determine npmrc paths
153    let (repo_npmrc, cred_npmrc, git_status) = if options.local_credential {
154        let cwd = std::env::current_dir()?;
155        let git_status = vcs::check_git_status(&cwd);
156
157        let local_npmrc = cwd.join(".npmrc");
158
159        let repo = if let Some(ref r) = options.repo_config {
160            r.clone()
161        } else if local_npmrc.exists() {
162            local_npmrc.clone()
163        } else {
164            home_dir.join(".npmrc")
165        };
166
167        (repo, local_npmrc, Some(git_status))
168    } else {
169        let repo = options.repo_config.clone().unwrap_or_else(|| {
170            let local = Path::new(".npmrc");
171            if local.exists() {
172                local.to_path_buf()
173            } else {
174                home_dir.join(".npmrc")
175            }
176        });
177
178        let cred = options
179            .credential_config
180            .clone()
181            .unwrap_or_else(|| home_dir.join(".npmrc"));
182
183        (repo, cred, None)
184    };
185
186    // Determine yarnrc paths
187    let repo_yarn = options.repo_config_yarn.clone().unwrap_or_else(|| {
188        let local = Path::new(".yarnrc.yml");
189        if local.exists() {
190            local.to_path_buf()
191        } else {
192            home_dir.join(".yarnrc.yml")
193        }
194    });
195
196    let cred_yarn = options
197        .credential_config_yarn
198        .clone()
199        .unwrap_or_else(|| home_dir.join(".yarnrc.yml"));
200
201    let should_update_yarn = match options.yarn {
202        Some(explicit) => explicit,
203        None => {
204            options.repo_config_yarn.is_some()
205                || options.credential_config_yarn.is_some()
206                || Path::new(".yarnrc.yml").exists()
207        }
208    };
209
210    let repo_npmrc = fs::resolve(&repo_npmrc)?;
211    let cred_npmrc = fs::resolve(&cred_npmrc)?;
212    let repo_yarn = if should_update_yarn {
213        Some(fs::resolve(&repo_yarn)?)
214    } else {
215        None
216    };
217    let cred_yarn = if should_update_yarn {
218        Some(fs::resolve(&cred_yarn)?)
219    } else {
220        None
221    };
222
223    let mut paths = vec![repo_npmrc.clone(), cred_npmrc.clone()];
224    if let Some(path) = &repo_yarn {
225        paths.push(path.clone());
226    }
227    if let Some(path) = &cred_yarn {
228        paths.push(path.clone());
229    }
230    let mut transaction = fs::FileTransaction::new(&paths)?;
231
232    let npm_source = transaction.contents(&repo_npmrc)?.to_owned();
233    let npm_target = transaction.contents(&cred_npmrc)?.to_owned();
234    if npmrc::has_registry(&npm_source, &npm_target, options.allow_all_domains)? {
235        let same_file = repo_npmrc == cred_npmrc;
236        let (cleaned, updated) = npmrc::transform_npmrc_contents(
237            &npm_source,
238            &npm_target,
239            &token,
240            options.allow_all_domains,
241            same_file,
242        )?;
243        transaction.stage(&cred_npmrc, &updated)?;
244        if !same_file && transaction.existed(&repo_npmrc)? && cleaned != npm_source {
245            transaction.stage(&repo_npmrc, &cleaned)?;
246        }
247    } else if !should_update_yarn {
248        return Err(AuthError::Config(
249            "No Artifact Registry configuration found in .npmrc".to_string(),
250        ));
251    }
252
253    if let (Some(source), Some(target)) = (repo_yarn, cred_yarn) {
254        let source_content = transaction.contents(&source)?.to_owned();
255        let target_content = transaction.contents(&target)?.to_owned();
256        if let Some(updated) = yarnrc::transform_yarnrc_contents_with_policy(
257            &source_content,
258            &target_content,
259            &token,
260            options.allow_all_domains,
261        )? {
262            transaction.stage(&target, &updated)?;
263        }
264    }
265
266    let paths = transaction.commit()?;
267    if paths.is_empty() {
268        return Err(AuthError::Config(
269            "No eligible Artifact Registry configuration found".to_string(),
270        ));
271    }
272    Ok(RunOutcome::Updated { paths, git_status })
273}