1use std::io::IsTerminal;
6
7use quicknode_sdk::{
8 AdminConfig, HttpConfig, KvStoreConfig, QuicknodeSdk, SdkFullConfig, StreamsConfig,
9 WebhooksConfig,
10};
11
12use crate::config;
13use crate::errors::CliError;
14use crate::output::{Format, OutputCtx};
15
16#[derive(Debug, Clone, Default)]
18pub struct GlobalArgs {
19 pub api_key: Option<String>,
20 pub config_file: Option<std::path::PathBuf>,
23 pub format: Option<Format>,
27 pub wide: bool,
28 pub no_color: bool,
29 pub quiet: bool,
30 pub verbose: bool,
31 pub no_input: bool,
32 pub yes_count: u8,
33 pub retries: u32,
36 pub base_url: Option<String>,
37}
38
39impl GlobalArgs {
40 pub fn resolve_format(&self, stdout_is_tty: bool) -> Format {
44 self.resolve_output(stdout_is_tty).0
45 }
46
47 pub fn resolve_output(&self, stdout_is_tty: bool) -> (Format, bool) {
55 let (cfg_format, cfg_wide) = self.load_output_config();
56 resolve_output_inner(self.format, self.wide, cfg_format, cfg_wide, stdout_is_tty)
57 }
58
59 pub fn resolve_config_path(&self) -> Option<std::path::PathBuf> {
61 self.config_file.clone().or_else(config::config_path)
62 }
63
64 fn load_output_config(&self) -> (Option<Format>, bool) {
65 let Some(p) = self.resolve_config_path() else {
66 return (None, false);
67 };
68 match config::load_from(&p) {
69 Ok(Some(cfg)) => (cfg.output.format, cfg.output.wide),
70 _ => (None, false),
71 }
72 }
73}
74
75fn resolve_output_inner(
79 flag_format: Option<Format>,
80 flag_wide: bool,
81 cfg_format: Option<Format>,
82 cfg_wide: bool,
83 stdout_is_tty: bool,
84) -> (Format, bool) {
85 let format = flag_format.or(cfg_format).unwrap_or(if stdout_is_tty {
86 Format::Table
87 } else {
88 Format::Json
89 });
90 let wide = flag_wide || cfg_wide;
91 (format, wide)
92}
93
94pub fn user_agent() -> String {
98 format!(
99 "quicknode-cli/{} ({}-{})",
100 env!("CARGO_PKG_VERSION"),
101 std::env::consts::OS,
102 std::env::consts::ARCH,
103 )
104}
105
106pub fn sdk_config(api_key: String) -> SdkFullConfig {
111 let mut full = SdkFullConfig::from_api_key(api_key);
112 let mut headers = std::collections::HashMap::new();
113 headers.insert("User-Agent".to_string(), user_agent());
114 full.http = Some(HttpConfig {
115 headers: Some(headers),
116 ..Default::default()
117 });
118 full
119}
120
121pub struct Ctx {
122 pub sdk: QuicknodeSdk,
123 pub out: OutputCtx,
124 pub global: GlobalArgs,
125}
126
127impl Ctx {
128 pub fn from_global(global: GlobalArgs) -> Result<Self, CliError> {
134 let config_path = global.resolve_config_path();
135 let stdout_is_tty = std::io::stdout().is_terminal();
136 let (format, wide) = global.resolve_output(stdout_is_tty);
137
138 let (api_key, _) = config::resolve_api_key(
139 global.api_key.as_deref(),
140 config_path.as_deref(),
141 false,
142 || unreachable!("prompt disabled for non-auth commands"),
143 )?;
144
145 let mut full = sdk_config(api_key);
146
147 if let Some(base) = &global.base_url {
151 let trimmed = validate_base_url(base)?;
152 let trimmed = trimmed.as_str();
153 full.admin = Some(AdminConfig {
154 base_url: Some(format!("{trimmed}/v0/")),
155 });
156 full.streams = Some(StreamsConfig {
157 base_url: Some(format!("{trimmed}/streams/rest/v1/")),
158 });
159 full.webhooks = Some(WebhooksConfig {
160 base_url: Some(format!("{trimmed}/webhooks/rest/v1/")),
161 });
162 full.kvstore = Some(KvStoreConfig {
163 base_url: Some(format!("{trimmed}/kv/rest/v1/")),
164 });
165 }
166
167 let sdk = QuicknodeSdk::new(&full)?;
168 let out = OutputCtx::detect_with(
169 format,
170 global.no_color,
171 global.quiet,
172 global.verbose,
173 wide,
174 stdout_is_tty,
175 std::env::var_os("NO_COLOR"),
176 std::env::var("TERM").ok(),
177 );
178
179 Ok(Self { sdk, out, global })
180 }
181}
182
183fn validate_base_url(base: &str) -> Result<String, CliError> {
188 let parsed = url::Url::parse(base)
189 .map_err(|_| CliError::Arg(format!("--base-url '{base}' is not a valid URL")))?;
190 match parsed.scheme() {
191 "http" | "https" => {}
192 other => {
193 return Err(CliError::Arg(format!(
194 "--base-url scheme '{other}' is not allowed; use http or https"
195 )))
196 }
197 }
198 if !parsed.username().is_empty() || parsed.password().is_some() {
199 return Err(CliError::Arg(
200 "--base-url must not contain userinfo (username/password)".into(),
201 ));
202 }
203 if parsed.query().is_some() || parsed.fragment().is_some() {
204 return Err(CliError::Arg(
205 "--base-url must not contain a query string or fragment".into(),
206 ));
207 }
208 if !matches!(parsed.path(), "" | "/") {
209 return Err(CliError::Arg("--base-url must not contain a path".into()));
210 }
211 Ok(base.trim_end_matches('/').to_string())
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
219 fn flag_format_wins_over_config_and_tty_default() {
220 let (f, _) =
221 resolve_output_inner(Some(Format::Json), false, Some(Format::Yaml), false, true);
222 assert_eq!(f, Format::Json);
223 let (f, _) =
224 resolve_output_inner(Some(Format::Json), false, Some(Format::Yaml), false, false);
225 assert_eq!(f, Format::Json);
226 }
227
228 #[test]
229 fn config_format_wins_over_tty_default() {
230 let (f, _) = resolve_output_inner(None, false, Some(Format::Yaml), false, true);
231 assert_eq!(f, Format::Yaml);
232 let (f, _) = resolve_output_inner(None, false, Some(Format::Yaml), false, false);
233 assert_eq!(f, Format::Yaml);
234 }
235
236 #[test]
237 fn default_is_table_when_stdout_is_a_tty() {
238 let (f, _) = resolve_output_inner(None, false, None, false, true);
239 assert_eq!(f, Format::Table);
240 }
241
242 #[test]
243 fn default_is_json_when_stdout_is_not_a_tty() {
244 let (f, _) = resolve_output_inner(None, false, None, false, false);
245 assert_eq!(f, Format::Json);
246 }
247
248 #[test]
249 fn config_toon_overrides_non_tty_default() {
250 let (f, _) = resolve_output_inner(None, false, Some(Format::Toon), false, false);
251 assert_eq!(f, Format::Toon);
252 }
253
254 #[test]
255 fn wide_is_additive_between_flag_and_config() {
256 let (_, w) = resolve_output_inner(None, true, None, false, true);
258 assert!(w);
259 let (_, w) = resolve_output_inner(None, false, None, true, true);
261 assert!(w);
262 let (_, w) = resolve_output_inner(None, true, None, true, true);
264 assert!(w);
265 let (_, w) = resolve_output_inner(None, false, None, false, true);
267 assert!(!w);
268 }
269
270 #[test]
271 fn base_url_accepts_plain_http_and_https() {
272 assert_eq!(
273 validate_base_url("https://api.quicknode.com").unwrap(),
274 "https://api.quicknode.com"
275 );
276 assert_eq!(
277 validate_base_url("http://127.0.0.1:8080/").unwrap(),
278 "http://127.0.0.1:8080"
279 );
280 }
281
282 #[test]
283 fn base_url_rejects_non_http_schemes() {
284 for bad in ["file:///etc/passwd", "ftp://x", "javascript:alert(1)"] {
285 assert!(validate_base_url(bad).is_err(), "should reject {bad}");
286 }
287 }
288
289 #[test]
290 fn base_url_rejects_userinfo() {
291 assert!(validate_base_url("https://user:pass@evil/").is_err());
292 assert!(validate_base_url("https://user@evil/").is_err());
293 }
294
295 #[test]
296 fn base_url_rejects_path_query_fragment() {
297 assert!(validate_base_url("https://x/extra/path").is_err());
298 assert!(validate_base_url("https://x/?q=1").is_err());
299 assert!(validate_base_url("https://x/#frag").is_err());
300 }
301
302 #[test]
303 fn base_url_rejects_garbage() {
304 assert!(validate_base_url("not a url").is_err());
305 assert!(validate_base_url("").is_err());
306 }
307
308 #[test]
309 fn user_agent_identifies_the_cli() {
310 let ua = user_agent();
311 assert!(ua.starts_with("quicknode-cli/"), "ua={ua}");
312 assert!(ua.contains(env!("CARGO_PKG_VERSION")), "ua={ua}");
313 }
314
315 #[test]
316 fn sdk_config_sets_the_user_agent_header_and_nothing_else() {
317 let cfg = sdk_config("k".to_string());
318 let http = cfg.http.expect("http config should be set");
319 assert_eq!(
320 http.headers.as_ref().and_then(|h| h.get("User-Agent")),
321 Some(&user_agent())
322 );
323 assert_eq!(http.timeout_secs, None);
325 assert_eq!(http.pool_max_idle_per_host, None);
326 }
327}