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;
58mod registry_query;
59pub mod token;
60pub mod vcs;
61pub mod yarnrc;
62
63pub use error::AuthError;
64use std::path::{Path, PathBuf};
65
66pub enum RunOutcome {
68 Token(String),
70 Updated {
72 paths: Vec<PathBuf>,
74 git_status: Option<vcs::GitStatus>,
76 bun_env_git_status: Option<vcs::GitStatus>,
78 },
79}
80
81impl std::fmt::Debug for RunOutcome {
82 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 match self {
84 Self::Token(_) => formatter.write_str("Token([redacted])"),
85 Self::Updated {
86 paths,
87 git_status,
88 bun_env_git_status,
89 } => formatter
90 .debug_struct("Updated")
91 .field("paths", paths)
92 .field("git_status", git_status)
93 .field("bun_env_git_status", bun_env_git_status)
94 .finish(),
95 }
96 }
97}
98
99#[derive(Clone, Default)]
101pub struct Options {
102 pub repo_config: Option<PathBuf>,
105
106 pub credential_config: Option<PathBuf>,
109
110 pub repo_config_yarn: Option<PathBuf>,
113
114 pub credential_config_yarn: Option<PathBuf>,
117
118 pub repo_config_bun: Option<PathBuf>,
121
122 pub local_credential: bool,
124
125 pub token: Option<String>,
127
128 pub allow_all_domains: bool,
130
131 pub yarn: Option<bool>,
134
135 pub bun: Option<bool>,
138
139 pub bun_env: bool,
141
142 pub print_token: bool,
144}
145
146impl std::fmt::Debug for Options {
147 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 formatter
149 .debug_struct("Options")
150 .field("repo_config", &self.repo_config)
151 .field("credential_config", &self.credential_config)
152 .field("repo_config_yarn", &self.repo_config_yarn)
153 .field("credential_config_yarn", &self.credential_config_yarn)
154 .field("repo_config_bun", &self.repo_config_bun)
155 .field("local_credential", &self.local_credential)
156 .field("token", &self.token.as_ref().map(|_| "[redacted]"))
157 .field("allow_all_domains", &self.allow_all_domains)
158 .field("yarn", &self.yarn)
159 .field("bun", &self.bun)
160 .field("bun_env", &self.bun_env)
161 .field("print_token", &self.print_token)
162 .finish()
163 }
164}
165
166pub async fn run(options: &Options) -> Result<RunOutcome, AuthError> {
177 if options.bun_env && options.local_credential {
178 return Err(AuthError::BunEnvLocalCredentialConflict);
179 }
180
181 if options.bun_env && options.bun == Some(false) {
182 return Err(AuthError::BunEnvDisabledConflict);
183 }
184
185 let token = auth::get_credentials(options.token.as_deref()).await?;
186
187 token::validate_token(&token)?;
188
189 if options.print_token {
190 return Ok(RunOutcome::Token(token));
191 }
192
193 let discovery = if options.repo_config.is_none() && options.repo_config_yarn.is_none() {
194 let manager = registry_query::detect(&std::env::current_dir()?)?;
195 if manager == registry_query::Manager::Yarn && options.yarn == Some(false) {
196 None
197 } else {
198 registry_query::query(manager)?
199 }
200 } else {
201 None
202 };
203 let modern_yarn = discovery.as_ref().is_some_and(|d| d.modern_yarn);
204
205 let home_dir = dirs::home_dir()
206 .ok_or_else(|| AuthError::Config("Unable to determine user home directory".to_string()))?;
207
208 let discovered_npmrc = discovery
209 .as_ref()
210 .map(|d| d.project_root.join(".npmrc"))
211 .filter(|p| p.is_file());
212
213 let (repo_npmrc, cred_npmrc, git_status) = if options.local_credential {
215 let cwd = std::env::current_dir()?;
216 let git_status = vcs::check_git_status(&cwd);
217
218 let local_npmrc = cwd.join(".npmrc");
219
220 let repo = if let Some(ref r) = options.repo_config {
221 r.clone()
222 } else if let Some(source) = &discovered_npmrc {
223 source.clone()
224 } else if local_npmrc.exists() {
225 local_npmrc.clone()
226 } else {
227 home_dir.join(".npmrc")
228 };
229
230 (repo, local_npmrc, Some(git_status))
231 } else {
232 let repo = options.repo_config.clone().unwrap_or_else(|| {
233 let local = Path::new(".npmrc");
234 if let Some(source) = &discovered_npmrc {
235 source.clone()
236 } else if local.exists() {
237 local.to_path_buf()
238 } else {
239 home_dir.join(".npmrc")
240 }
241 });
242
243 let cred = options
244 .credential_config
245 .clone()
246 .unwrap_or_else(|| home_dir.join(".npmrc"));
247
248 (repo, cred, None)
249 };
250
251 let repo_yarn = options.repo_config_yarn.clone().unwrap_or_else(|| {
253 let local = Path::new(".yarnrc.yml");
254 if local.exists() {
255 local.to_path_buf()
256 } else {
257 home_dir.join(".yarnrc.yml")
258 }
259 });
260
261 let cred_yarn = options
262 .credential_config_yarn
263 .clone()
264 .unwrap_or_else(|| home_dir.join(".yarnrc.yml"));
265
266 let should_update_yarn = modern_yarn
267 || match options.yarn {
268 Some(explicit) => explicit,
269 None => {
270 options.repo_config_yarn.is_some()
271 || options.credential_config_yarn.is_some()
272 || Path::new(".yarnrc.yml").exists()
273 }
274 };
275
276 let repo_bun = options
277 .repo_config_bun
278 .clone()
279 .unwrap_or_else(|| PathBuf::from("bunfig.toml"));
280 let should_update_bun = options.bun_env
281 || match options.bun {
282 Some(explicit) => explicit,
283 None => options.repo_config_bun.is_some() || Path::new("bunfig.toml").exists(),
284 };
285
286 let repo_npmrc = fs::resolve(&repo_npmrc)?;
287 let cred_npmrc = fs::resolve(&cred_npmrc)?;
288
289 let repo_yarn = if should_update_yarn {
290 Some(fs::resolve(&repo_yarn)?)
291 } else {
292 None
293 };
294 let cred_yarn = if should_update_yarn {
295 Some(fs::resolve(&cred_yarn)?)
296 } else {
297 None
298 };
299
300 let repo_bun = if should_update_bun {
301 Some(fs::resolve(&repo_bun)?)
302 } else {
303 None
304 };
305 let bun_env_path = if options.bun_env {
306 let parent = repo_bun
307 .as_ref()
308 .and_then(|path| path.parent())
309 .ok_or_else(|| AuthError::Config("bunfig.toml has no parent directory".to_string()))?;
310 Some(fs::resolve(&parent.join(".env.local"))?)
311 } else {
312 None
313 };
314 let bun_env_git_status = bun_env_path
315 .as_ref()
316 .map(|path| vcs::check_path_status(path.parent().unwrap(), Path::new(".env.local")));
317
318 let mut paths = vec![repo_npmrc.clone(), cred_npmrc.clone()];
319
320 if let Some(path) = &repo_yarn {
321 paths.push(path.clone());
322 }
323
324 if let Some(path) = &cred_yarn {
325 paths.push(path.clone());
326 }
327
328 if let Some(path) = &repo_bun {
329 paths.push(path.clone());
330 }
331
332 if let Some(path) = &bun_env_path {
333 paths.push(path.clone());
334 }
335
336 let mut transaction = fs::FileTransaction::new(&paths)?;
337
338 let bun_registries = if let Some(path) = &repo_bun {
339 if !transaction.existed(path)? {
340 return Err(AuthError::Config(format!(
341 "Bun configuration does not exist: {}",
342 path.display()
343 )));
344 }
345
346 bunfig::registry_urls(transaction.contents(path)?, options.allow_all_domains)?
347 } else {
348 Vec::new()
349 };
350
351 let npm_source = transaction.contents(&repo_npmrc)?.to_owned();
352 let npm_target = transaction.contents(&cred_npmrc)?.to_owned();
353 let mut npm_registries = if let Some(discovery) = discovery.as_ref().filter(|_| !modern_yarn) {
354 discovery.registries(options.allow_all_domains)?
355 } else {
356 None
357 };
358 if !options.local_credential && !options.bun_env && !bun_registries.is_empty() {
359 if npm_registries.is_none() {
360 let parser = npmrc::NpmrcParser::new(options.allow_all_domains)?;
361 let policy = registry::RegistryPolicy {
362 allow_all_domains: options.allow_all_domains,
363 };
364 let mut registries = Vec::new();
365 for line in npm_source.lines().chain(npm_target.lines()) {
366 if let npmrc::NpmrcConfigType::Registry { registry, .. } = parser.parse_line(line)?
367 && let Some(registry) = policy.parse_npm_key(®istry)?
368 {
369 registries.push(registry);
370 }
371 }
372 npm_registries = Some(registries);
373 }
374 npm_registries.as_mut().unwrap().extend(bun_registries);
375 }
376 let npm_has_registry = match &npm_registries {
377 Some(registries) => !registries.is_empty(),
378 None => npmrc::has_registry(&npm_source, &npm_target, options.allow_all_domains)?,
379 };
380
381 if npm_has_registry {
382 let same_file = repo_npmrc == cred_npmrc;
383 let (cleaned, updated) = npmrc::transform_npmrc_contents_with_registries(
384 &npm_source,
385 &npm_target,
386 &token,
387 options.allow_all_domains,
388 same_file,
389 npm_registries.as_deref(),
390 )?;
391
392 transaction.stage(&cred_npmrc, &updated)?;
393
394 if !same_file && transaction.existed(&repo_npmrc)? && cleaned != npm_source {
395 transaction.stage(&repo_npmrc, &cleaned)?;
396 }
397 }
398
399 if let (Some(source), Some(target)) = (repo_yarn, cred_yarn) {
400 let source_content = transaction.contents(&source)?.to_owned();
401 let target_content = transaction.contents(&target)?.to_owned();
402 let updated = if modern_yarn {
403 yarnrc::transform_resolved_registries(
404 &target_content,
405 &token,
406 &discovery
407 .as_ref()
408 .unwrap()
409 .registries(options.allow_all_domains)?
410 .unwrap_or_default(),
411 &discovery.as_ref().unwrap().yarn_scopes,
412 )?
413 } else {
414 yarnrc::transform_yarnrc_contents_with_policy(
415 &source_content,
416 &target_content,
417 &token,
418 options.allow_all_domains,
419 )?
420 };
421 if let Some(updated) = updated {
422 transaction.stage(&target, &updated)?;
423 }
424 }
425
426 if options.bun_env {
427 let bun_path = repo_bun.as_ref().unwrap();
428 let bun_content = transaction.contents(bun_path)?.to_owned();
429 let updated_bun = bunfig::transform_bunfig_for_env(&bun_content, options.allow_all_domains)?
430 .ok_or_else(|| {
431 AuthError::Config("No eligible registry configuration found in bunfig.toml".to_string())
432 })?;
433
434 if updated_bun != bun_content {
435 transaction.stage(bun_path, &updated_bun)?;
436 }
437
438 let env_path = bun_env_path.as_ref().unwrap();
439 let env_content = transaction.contents(env_path)?.to_owned();
440 let updated_env = bunfig::transform_env_local(&env_content, &token)?;
441 if updated_env != env_content {
442 transaction.stage(env_path, &updated_env)?;
443 }
444 }
445
446 let paths = transaction.commit()?;
447 if paths.is_empty() {
448 return Err(AuthError::Config(
449 "No eligible Artifact Registry configuration found".to_string(),
450 ));
451 }
452
453 if let Some(discovery) = discovery {
454 discovery.save();
455 }
456
457 Ok(RunOutcome::Updated {
458 paths,
459 git_status,
460 bun_env_git_status,
461 })
462}
463
464pub fn run_blocking(options: &Options) -> Result<RunOutcome, AuthError> {
492 if tokio::runtime::Handle::try_current().is_ok() {
493 return Err(AuthError::Config(
494 "run_blocking cannot be called within an active Tokio runtime; use run().await".to_string(),
495 ));
496 }
497
498 let runtime = tokio::runtime::Builder::new_current_thread()
499 .enable_all()
500 .build()?;
501 runtime.block_on(run(options))
502}
503
504#[cfg(test)]
505mod tests {
506 use super::*;
507
508 #[tokio::test]
509 async fn bun_option_conflicts_return_dedicated_errors() {
510 let options = Options {
511 bun_env: true,
512 local_credential: true,
513 ..Options::default()
514 };
515 assert!(matches!(
516 run(&options).await,
517 Err(AuthError::BunEnvLocalCredentialConflict)
518 ));
519
520 let options = Options {
521 local_credential: false,
522 bun: Some(false),
523 ..options
524 };
525 assert!(matches!(
526 run(&options).await,
527 Err(AuthError::BunEnvDisabledConflict)
528 ));
529 }
530
531 #[test]
532 fn blocking_run_returns_token_and_propagates_errors() {
533 let mut options = Options {
534 token: Some("valid-token".to_string()),
535 print_token: true,
536 ..Default::default()
537 };
538 assert!(
539 matches!(run_blocking(&options).unwrap(), RunOutcome::Token(token) if token == "valid-token")
540 );
541
542 options.token = Some("invalid\ntoken".to_string());
543 assert!(run_blocking(&options).is_err());
544 }
545
546 #[test]
547 fn blocking_run_updates_configuration_without_cli() {
548 let dir = tempfile::tempdir().unwrap();
549 let source = dir.path().join("project.npmrc");
550 let target = dir.path().join("user.npmrc");
551
552 std::fs::write(&source, "registry=https://us-npm.pkg.dev/project/repo/\n").unwrap();
553
554 let options = Options {
555 token: Some("valid-token".to_string()),
556 repo_config: Some(source),
557 credential_config: Some(target.clone()),
558 yarn: Some(false),
559 bun: Some(false),
560 ..Default::default()
561 };
562 assert!(
563 matches!(run_blocking(&options).unwrap(), RunOutcome::Updated { paths, .. } if paths.contains(&fs::resolve(&target).unwrap()))
564 );
565 assert!(
566 std::fs::read_to_string(target)
567 .unwrap()
568 .contains("//us-npm.pkg.dev/project/repo/:_authToken=\"valid-token\"")
569 );
570 }
571
572 #[tokio::test]
573 async fn blocking_run_rejects_nested_runtime_without_panicking() {
574 let options = Options {
575 token: Some("valid-token".to_string()),
576 print_token: true,
577 ..Default::default()
578 };
579 assert!(
580 matches!(run_blocking(&options), Err(AuthError::Config(message)) if message.contains("active Tokio runtime"))
581 );
582 assert!(matches!(run(&options).await.unwrap(), RunOutcome::Token(_)));
583 }
584}