1use crate::AuthError;
4use crate::registry::{RegistryPolicy, RegistryUrl};
5use crate::token::validate_token;
6use std::str::FromStr;
7use toml_edit::{DocumentMut, InlineTable, Item, Value};
8
9const TOKEN_VARIABLE: &str = "NODE_AUTH_TOKEN";
10const TOKEN_REFERENCE: &str = "$NODE_AUTH_TOKEN";
11
12pub fn registry_urls(
14 content: &str,
15 allow_all_domains: bool,
16) -> Result<Vec<RegistryUrl>, AuthError> {
17 let document = parse(content)?;
18 let Some(install) = document.get("install") else {
19 return Ok(Vec::new());
20 };
21 let install = install
22 .as_table_like()
23 .ok_or_else(|| AuthError::Config("Bun `install` configuration must be a table".to_string()))?;
24 let policy = RegistryPolicy { allow_all_domains };
25 let mut registries = Vec::new();
26
27 if let Some(item) = install.get("registry")
28 && let Some(registry) = parse_registry_item(item, "install.registry", &policy)?
29 {
30 registries.push(registry);
31 }
32
33 if let Some(scopes) = install.get("scopes") {
34 let scopes = scopes.as_table_like().ok_or_else(|| {
35 AuthError::Config("Bun `install.scopes` configuration must be a table".to_string())
36 })?;
37 for (scope, item) in scopes.iter() {
38 let location = format!("install.scopes.{scope}");
39 if let Some(registry) = parse_registry_item(item, &location, &policy)? {
40 registries.push(registry);
41 }
42 }
43 }
44
45 registries.sort_by(|left, right| left.npm_key().cmp(right.npm_key()));
46 registries.dedup_by(|left, right| left.npm_key() == right.npm_key());
47 Ok(registries)
48}
49
50pub fn transform_bunfig_for_env(
54 content: &str,
55 allow_all_domains: bool,
56) -> Result<Option<String>, AuthError> {
57 let mut document = parse(content)?;
58 let eligible = registry_urls(content, allow_all_domains)?;
59 if eligible.is_empty() {
60 return Ok(None);
61 }
62 let policy = RegistryPolicy { allow_all_domains };
63 let install = document
64 .get_mut("install")
65 .and_then(Item::as_table_like_mut)
66 .ok_or_else(|| AuthError::Config("Bun `install` configuration must be a table".to_string()))?;
67
68 if let Some(item) = install.get_mut("registry") {
69 update_registry_item(item, "install.registry", &policy)?;
70 }
71 if let Some(scopes) = install.get_mut("scopes") {
72 let scopes = scopes.as_table_like_mut().ok_or_else(|| {
73 AuthError::Config("Bun `install.scopes` configuration must be a table".to_string())
74 })?;
75 for (scope, item) in scopes.iter_mut() {
76 update_registry_item(item, &format!("install.scopes.{scope}"), &policy)?;
77 }
78 }
79 Ok(Some(document.to_string()))
80}
81
82pub fn transform_env_local(content: &str, token: &str) -> Result<String, AuthError> {
84 validate_token(token)?;
85 let newline = if content.contains("\r\n") {
86 "\r\n"
87 } else {
88 "\n"
89 };
90 let mut output = String::with_capacity(content.len() + token.len() + 32);
91 let mut replaced = false;
92
93 for line in content.split_inclusive('\n') {
94 let body = line.strip_suffix('\n').unwrap_or(line);
95 let body = body.strip_suffix('\r').unwrap_or(body);
96 let trimmed = body.trim_start();
97 let is_token =
98 trimmed.starts_with("NODE_AUTH_TOKEN=") || trimmed.starts_with("export NODE_AUTH_TOKEN=");
99 if is_token {
100 if !replaced {
101 output.push_str(TOKEN_VARIABLE);
102 output.push('=');
103 output.push_str(token);
104 if line.ends_with('\n') {
105 output.push_str(newline);
106 }
107 replaced = true;
108 }
109 } else {
110 output.push_str(line);
111 }
112 }
113
114 if !replaced {
115 if !output.is_empty() && !output.ends_with('\n') {
116 output.push_str(newline);
117 }
118 output.push_str(TOKEN_VARIABLE);
119 output.push('=');
120 output.push_str(token);
121 output.push_str(newline);
122 }
123 Ok(output)
124}
125
126fn parse(content: &str) -> Result<DocumentMut, AuthError> {
127 DocumentMut::from_str(content).map_err(AuthError::from)
128}
129
130fn parse_registry_item(
131 item: &Item,
132 location: &str,
133 policy: &RegistryPolicy,
134) -> Result<Option<RegistryUrl>, AuthError> {
135 let raw = registry_url(item, location)?;
136 policy.parse(raw)
137}
138
139fn registry_url<'a>(item: &'a Item, location: &str) -> Result<&'a str, AuthError> {
140 let value = item.as_value().ok_or_else(|| invalid_registry(location))?;
141 if let Some(url) = value.as_str() {
142 return Ok(url);
143 }
144 let table = value
145 .as_inline_table()
146 .ok_or_else(|| invalid_registry(location))?;
147 table
148 .get("url")
149 .and_then(Value::as_str)
150 .ok_or_else(|| invalid_registry(location))
151}
152
153fn update_registry_item(
154 item: &mut Item,
155 location: &str,
156 policy: &RegistryPolicy,
157) -> Result<(), AuthError> {
158 if parse_registry_item(item, location, policy)?.is_none() {
159 return Ok(());
160 }
161 let value = item
162 .as_value_mut()
163 .ok_or_else(|| invalid_registry(location))?;
164 if value.is_str() {
165 let url = value.clone();
166 let mut table = InlineTable::new();
167 table.insert("url", url);
168 table.insert("token", Value::from(TOKEN_REFERENCE));
169 *value = Value::InlineTable(table);
170 return Ok(());
171 }
172 let table = value
173 .as_inline_table_mut()
174 .ok_or_else(|| invalid_registry(location))?;
175 table.remove("username");
176 table.remove("password");
177 table.insert("token", Value::from(TOKEN_REFERENCE));
178 Ok(())
179}
180
181fn invalid_registry(location: &str) -> AuthError {
182 AuthError::Config(format!(
183 "Bun `{location}` must be a registry URL string or an inline table with a string `url`"
184 ))
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190
191 #[test]
192 fn discovers_default_and_scoped_registries() {
193 let input = r#"[install]
194registry = { url = "https://us-npm.pkg.dev/project/default", token = "old" }
195
196[install.scopes]
197myorg = "https://europe-npm.pkg.dev/project/scoped"
198other = { url = "https://registry.example.com/private", token = "leave" }
199"#;
200 let registries = registry_urls(input, false).unwrap();
201 assert_eq!(registries.len(), 2);
202 assert_eq!(
203 registries[0].npm_key(),
204 "//europe-npm.pkg.dev/project/scoped/"
205 );
206 assert_eq!(registries[1].npm_key(), "//us-npm.pkg.dev/project/default/");
207 }
208
209 #[test]
210 fn transforms_only_eligible_entries_and_preserves_comments() {
211 let input = r#"# Bun settings
212[install.scopes]
213myorg = { url = 'https://us-npm.pkg.dev/project/repo', username = "old", password = "$OLD", extra = true } # keep
214other = "https://registry.example.com/private"
215"#;
216 let output = transform_bunfig_for_env(input, false).unwrap().unwrap();
217 assert!(output.starts_with("# Bun settings\n"));
218 assert!(output.contains("url = 'https://us-npm.pkg.dev/project/repo'"));
219 assert!(output.contains("extra = true"));
220 assert!(output.contains("token = \"$NODE_AUTH_TOKEN\""));
221 assert!(output.contains("# keep"));
222 assert!(!output.contains("username"));
223 assert!(!output.contains("password"));
224 assert!(output.contains("other = \"https://registry.example.com/private\""));
225 }
226
227 #[test]
228 fn converts_string_entry_to_inline_table() {
229 let input = "[install.scopes]\nmyorg = 'https://us-npm.pkg.dev/project/repo'\n";
230 let output = transform_bunfig_for_env(input, false).unwrap().unwrap();
231 assert!(output.contains("url = 'https://us-npm.pkg.dev/project/repo'"));
232 assert!(output.contains("token = \"$NODE_AUTH_TOKEN\""));
233 }
234
235 #[test]
236 fn rejects_invalid_registry_shapes() {
237 let error = registry_urls("[install.scopes]\nmyorg = 42\n", false).unwrap_err();
238 assert!(error.to_string().contains("install.scopes.myorg"));
239 assert!(registry_urls("[install\n", false).is_err());
240 }
241
242 #[test]
243 fn domain_override_updates_other_https_registries() {
244 let input = "[install.scopes]\nmyorg = \"https://registry.example.com/private\"\n";
245 assert!(transform_bunfig_for_env(input, false).unwrap().is_none());
246 let output = transform_bunfig_for_env(input, true).unwrap().unwrap();
247 assert!(output.contains("token = \"$NODE_AUTH_TOKEN\""));
248 }
249
250 #[test]
251 fn updates_env_token_once_and_preserves_line_endings() {
252 let input =
253 "# local\r\nNODE_AUTH_TOKEN=old\r\nOTHER=value\r\nexport NODE_AUTH_TOKEN=duplicate\r\n";
254 let output = transform_env_local(input, "fresh-token").unwrap();
255 assert_eq!(output.matches("NODE_AUTH_TOKEN=").count(), 1);
256 assert!(output.contains("NODE_AUTH_TOKEN=fresh-token\r\n"));
257 assert!(output.starts_with("# local\r\n"));
258 assert!(output.contains("OTHER=value\r\n"));
259 assert!(!output.contains("old"));
260 assert!(!output.contains("duplicate"));
261 }
262}