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