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