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