1#![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
65pub enum RunOutcome {
67 Token(String),
69 Updated {
71 paths: Vec<PathBuf>,
73 git_status: Option<vcs::GitStatus>,
75 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#[derive(Clone, Default)]
100pub struct Options {
101 pub repo_config: Option<PathBuf>,
104
105 pub credential_config: Option<PathBuf>,
108
109 pub repo_config_yarn: Option<PathBuf>,
112
113 pub credential_config_yarn: Option<PathBuf>,
116
117 pub repo_config_bun: Option<PathBuf>,
120
121 pub local_credential: bool,
123
124 pub token: Option<String>,
126
127 pub allow_all_domains: bool,
129
130 pub yarn: Option<bool>,
133
134 pub bun: Option<bool>,
137
138 pub bun_env: bool,
140
141 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
165pub 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 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 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
385pub 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}