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