1#![warn(missing_docs)]
38
39pub mod auth;
40pub mod cli;
41pub mod error;
42pub mod fs;
43pub mod logger;
44pub mod npmrc;
45pub mod registry;
46pub mod token;
47pub mod vcs;
48pub mod yarnrc;
49
50pub use error::AuthError;
51use std::path::{Path, PathBuf};
52
53pub enum RunOutcome {
55 Token(String),
57 Updated {
59 paths: Vec<PathBuf>,
61 git_status: Option<vcs::GitStatus>,
63 },
64}
65
66impl std::fmt::Debug for RunOutcome {
67 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 match self {
69 Self::Token(_) => formatter.write_str("Token([redacted])"),
70 Self::Updated { paths, git_status } => formatter
71 .debug_struct("Updated")
72 .field("paths", paths)
73 .field("git_status", git_status)
74 .finish(),
75 }
76 }
77}
78
79#[derive(Clone, Default)]
81pub struct Options {
82 pub repo_config: Option<PathBuf>,
85
86 pub credential_config: Option<PathBuf>,
89
90 pub repo_config_yarn: Option<PathBuf>,
93
94 pub credential_config_yarn: Option<PathBuf>,
97
98 pub local_credential: bool,
100
101 pub token: Option<String>,
103
104 pub allow_all_domains: bool,
106
107 pub yarn: Option<bool>,
110
111 pub print_token: bool,
113}
114
115impl std::fmt::Debug for Options {
116 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 formatter
118 .debug_struct("Options")
119 .field("repo_config", &self.repo_config)
120 .field("credential_config", &self.credential_config)
121 .field("repo_config_yarn", &self.repo_config_yarn)
122 .field("credential_config_yarn", &self.credential_config_yarn)
123 .field("local_credential", &self.local_credential)
124 .field("token", &self.token.as_ref().map(|_| "[redacted]"))
125 .field("allow_all_domains", &self.allow_all_domains)
126 .field("yarn", &self.yarn)
127 .field("print_token", &self.print_token)
128 .finish()
129 }
130}
131
132pub async fn run(options: &Options) -> Result<RunOutcome, AuthError> {
143 let token = auth::get_credentials(options.token.as_deref()).await?;
144 token::validate_token(&token)?;
145 if options.print_token {
146 return Ok(RunOutcome::Token(token));
147 }
148
149 let home_dir = dirs::home_dir()
150 .ok_or_else(|| AuthError::Config("Unable to determine user home directory".to_string()))?;
151
152 let (repo_npmrc, cred_npmrc, git_status) = if options.local_credential {
154 let cwd = std::env::current_dir()?;
155 let git_status = vcs::check_git_status(&cwd);
156
157 let local_npmrc = cwd.join(".npmrc");
158
159 let repo = if let Some(ref r) = options.repo_config {
160 r.clone()
161 } else if local_npmrc.exists() {
162 local_npmrc.clone()
163 } else {
164 home_dir.join(".npmrc")
165 };
166
167 (repo, local_npmrc, Some(git_status))
168 } else {
169 let repo = options.repo_config.clone().unwrap_or_else(|| {
170 let local = Path::new(".npmrc");
171 if local.exists() {
172 local.to_path_buf()
173 } else {
174 home_dir.join(".npmrc")
175 }
176 });
177
178 let cred = options
179 .credential_config
180 .clone()
181 .unwrap_or_else(|| home_dir.join(".npmrc"));
182
183 (repo, cred, None)
184 };
185
186 let repo_yarn = options.repo_config_yarn.clone().unwrap_or_else(|| {
188 let local = Path::new(".yarnrc.yml");
189 if local.exists() {
190 local.to_path_buf()
191 } else {
192 home_dir.join(".yarnrc.yml")
193 }
194 });
195
196 let cred_yarn = options
197 .credential_config_yarn
198 .clone()
199 .unwrap_or_else(|| home_dir.join(".yarnrc.yml"));
200
201 let should_update_yarn = match options.yarn {
202 Some(explicit) => explicit,
203 None => {
204 options.repo_config_yarn.is_some()
205 || options.credential_config_yarn.is_some()
206 || Path::new(".yarnrc.yml").exists()
207 }
208 };
209
210 let repo_npmrc = fs::resolve(&repo_npmrc)?;
211 let cred_npmrc = fs::resolve(&cred_npmrc)?;
212 let repo_yarn = if should_update_yarn {
213 Some(fs::resolve(&repo_yarn)?)
214 } else {
215 None
216 };
217 let cred_yarn = if should_update_yarn {
218 Some(fs::resolve(&cred_yarn)?)
219 } else {
220 None
221 };
222
223 let mut paths = vec![repo_npmrc.clone(), cred_npmrc.clone()];
224 if let Some(path) = &repo_yarn {
225 paths.push(path.clone());
226 }
227 if let Some(path) = &cred_yarn {
228 paths.push(path.clone());
229 }
230 let mut transaction = fs::FileTransaction::new(&paths)?;
231
232 let npm_source = transaction.contents(&repo_npmrc)?.to_owned();
233 let npm_target = transaction.contents(&cred_npmrc)?.to_owned();
234 if npmrc::has_registry(&npm_source, &npm_target, options.allow_all_domains)? {
235 let same_file = repo_npmrc == cred_npmrc;
236 let (cleaned, updated) = npmrc::transform_npmrc_contents(
237 &npm_source,
238 &npm_target,
239 &token,
240 options.allow_all_domains,
241 same_file,
242 )?;
243 transaction.stage(&cred_npmrc, &updated)?;
244 if !same_file && transaction.existed(&repo_npmrc)? && cleaned != npm_source {
245 transaction.stage(&repo_npmrc, &cleaned)?;
246 }
247 } else if !should_update_yarn {
248 return Err(AuthError::Config(
249 "No Artifact Registry configuration found in .npmrc".to_string(),
250 ));
251 }
252
253 if let (Some(source), Some(target)) = (repo_yarn, cred_yarn) {
254 let source_content = transaction.contents(&source)?.to_owned();
255 let target_content = transaction.contents(&target)?.to_owned();
256 if let Some(updated) = yarnrc::transform_yarnrc_contents_with_policy(
257 &source_content,
258 &target_content,
259 &token,
260 options.allow_all_domains,
261 )? {
262 transaction.stage(&target, &updated)?;
263 }
264 }
265
266 let paths = transaction.commit()?;
267 if paths.is_empty() {
268 return Err(AuthError::Config(
269 "No eligible Artifact Registry configuration found".to_string(),
270 ));
271 }
272 Ok(RunOutcome::Updated { paths, git_status })
273}