1use std::path::{Path, PathBuf};
14
15use url::Url;
16
17use crate::error::{CoreError, ErrorCode};
18use crate::model::sources::{SourceScope, key_shape};
19
20pub const AGGREGATOR_HOSTS: [&str; 7] = [
24 "github.com",
25 "gitlab.com",
26 "bitbucket.org",
27 "codeberg.org",
28 "gitee.com",
29 "git.sr.ht",
30 "huggingface.co",
31];
32
33const CASE_INSENSITIVE_HOSTS: [&str; 4] =
35 ["github.com", "gitlab.com", "bitbucket.org", "codeberg.org"];
36
37pub const OFFICIAL_OWNERS: [&str; 2] = ["github.com/anthropics", "github.com/modelcontextprotocol"];
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43enum Transport {
44 Https,
45 Http,
46 Ssh,
47 Git,
48 Scp,
50 Local,
51}
52
53impl Transport {
54 fn of_scheme(scheme: &str) -> Option<Self> {
55 match scheme.to_ascii_lowercase().as_str() {
56 "https" => Some(Transport::Https),
57 "http" => Some(Transport::Http),
58 "ssh" => Some(Transport::Ssh),
59 "git" => Some(Transport::Git),
60 _ => None,
61 }
62 }
63
64 const fn scheme(self) -> &'static str {
65 match self {
66 Transport::Https => "https",
67 Transport::Http => "http",
68 Transport::Ssh | Transport::Scp => "ssh",
69 Transport::Git => "git",
70 Transport::Local => "file",
71 }
72 }
73
74 const fn default_port(self) -> Option<u16> {
77 match self {
78 Transport::Https => Some(443),
79 Transport::Http => Some(80),
80 Transport::Ssh => Some(22),
81 Transport::Git => Some(9418),
82 Transport::Scp | Transport::Local => None,
83 }
84 }
85
86 const fn marker(self) -> &'static str {
88 match self {
89 Transport::Http => "http://",
90 Transport::Git => "git://",
91 _ => "",
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub struct SourceRef {
100 key: String,
103 url: String,
106 address: String,
109 host: Option<String>,
111 owner: Option<String>,
113 transport: Transport,
114 whole_host: bool,
117}
118
119struct Remote {
122 transport: Transport,
123 userinfo: Option<String>,
125 host: String,
127 absolute: bool,
129 segments: Vec<String>,
131}
132
133enum Parsed {
134 Remote(Remote),
135 Local(String),
137}
138
139fn invalid(text: &str, why: &str) -> CoreError {
140 CoreError::new(
141 ErrorCode::InvalidValue,
142 format!(
143 "{:?} is not a source: {why}",
144 SourceRef::redact_userinfo(text)
145 ),
146 )
147}
148
149fn scp_like(text: &str) -> Option<(&str, &str)> {
151 let (user_host, rest) = text.split_once(':')?;
152 if !user_host.contains('@') || user_host.contains(['/', '\\']) || rest.starts_with("//") {
153 return None;
154 }
155 Some((user_host, rest))
156}
157
158fn is_windows_drive(text: &str) -> bool {
159 let bytes = text.as_bytes();
160 bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
161}
162
163fn is_local_path(text: &str) -> bool {
164 Path::new(text).is_absolute() || is_windows_drive(text) || text.starts_with('/')
165}
166
167fn check_text(text: &str) -> Result<(), &'static str> {
169 if text.chars().any(|c| c.is_control() || c.is_whitespace()) {
170 return Err("it contains spaces or control characters");
171 }
172 if text.contains('\\') {
173 return Err("it contains a backslash");
174 }
175 if text.contains(['?', '#']) {
176 return Err("a query or fragment (`?`, `#`) does not name a repository");
177 }
178 let lower = text.to_ascii_lowercase();
179 if ["%2e", "%2f", "%5c"]
180 .iter()
181 .any(|code| lower.contains(code))
182 {
183 return Err("it percent-encodes `.`, `/` or `\\`");
184 }
185 if text.matches('@').count() > 1 {
186 return Err("it has more than one `@`");
187 }
188 Ok(())
189}
190
191fn checked_segments(path: &str) -> Result<Vec<&str>, &'static str> {
194 let path = path.strip_suffix('/').unwrap_or(path);
195 if path.is_empty() {
196 return Ok(Vec::new());
197 }
198 path.split('/')
199 .map(|segment| match segment {
200 "" => Err("it has an empty path segment (`//`)"),
201 "." | ".." => Err("it has a `.` or `..` path segment"),
202 segment => Ok(segment),
203 })
204 .collect()
205}
206
207fn normalize_escapes(segment: &str) -> Result<String, &'static str> {
210 let mut out = String::with_capacity(segment.len());
211 let mut rest = segment;
212 while let Some(at) = rest.find('%') {
213 out.push_str(&rest[..at]);
214 let hex = rest
215 .get(at + 1..at + 3)
216 .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
217 .ok_or("it has a `%` that is not a percent-encoded byte")?;
218 let byte = u8::from_str_radix(hex, 16).map_err(|_| "it has a bad percent escape")?;
219 if byte.is_ascii_alphanumeric() || b"-_~".contains(&byte) {
220 out.push(char::from(byte));
221 } else {
222 out.push('%');
223 out.push_str(&hex.to_ascii_uppercase());
224 }
225 rest = &rest[at + 3..];
226 }
227 out.push_str(rest);
228 Ok(out)
229}
230
231fn canonical_host(host: &str) -> Result<String, &'static str> {
234 let lower = host.to_ascii_lowercase();
235 let host = lower.strip_suffix('.').unwrap_or(&lower);
236 let ok = match host.strip_prefix('[').and_then(|ip| ip.strip_suffix(']')) {
237 Some(ip) => {
238 !ip.is_empty()
239 && ip
240 .bytes()
241 .all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.')
242 }
243 None => {
244 !host.is_empty()
245 && host.split('.').all(|label| {
246 !label.is_empty()
247 && label.bytes().all(|b| {
248 b.is_ascii_lowercase() || b.is_ascii_digit() || b"-_".contains(&b)
249 })
250 })
251 }
252 };
253 if ok {
254 Ok(host.to_owned())
255 } else {
256 Err("its host is not a host name")
257 }
258}
259
260fn url_remote(text: &str, transport: Transport) -> Result<Remote, &'static str> {
262 check_text(text)?;
263 let rest = text.split_once("://").map_or("", |(_, rest)| rest);
264 let (authority, raw_path) = rest.split_once('/').unwrap_or((rest, ""));
265 if authority
266 .rsplit_once('@')
267 .map_or(authority, |(_, host)| host)
268 .is_empty()
269 {
270 return Err("it has no host");
271 }
272 if raw_path.contains('@') {
273 return Err("it has an `@` in the path");
274 }
275 let raw = checked_segments(raw_path)?;
276 let parsed = Url::parse(text).map_err(|_| "it is not a valid URL")?;
277 let host = canonical_host(parsed.host_str().ok_or("it has no host")?)?;
278 let host = match parsed.port() {
279 Some(port) if Some(port) != transport.default_port() => format!("{host}:{port}"),
280 _ => host,
281 };
282 let userinfo = match (parsed.username(), parsed.password()) {
283 ("", None) => None,
284 (user, None) => Some(user.to_owned()),
285 (user, Some(password)) => Some(format!("{user}:{password}")),
286 };
287 let path = parsed.path();
288 let path = path.strip_prefix('/').unwrap_or(path);
289 let segments = checked_segments(path)?
290 .into_iter()
291 .map(normalize_escapes)
292 .collect::<Result<Vec<_>, _>>()?;
293 if segments.len() != raw.len() {
296 return Err("it is not a valid URL");
297 }
298 Ok(Remote {
299 transport,
300 userinfo,
301 host,
302 absolute: true,
303 segments,
304 })
305}
306
307fn scp_remote(text: &str, user_host: &str, path: &str) -> Result<Remote, &'static str> {
309 check_text(text)?;
310 if path.contains(['%', '@']) {
311 return Err("an scp-style path cannot contain `%` or `@`");
312 }
313 let (user, host) = user_host.rsplit_once('@').unwrap_or(("", user_host));
314 let host = canonical_host(host)?;
315 let absolute = path.starts_with('/');
316 let segments = checked_segments(path.strip_prefix('/').unwrap_or(path))?
317 .into_iter()
318 .map(str::to_owned)
319 .collect();
320 Ok(Remote {
321 transport: Transport::Scp,
322 userinfo: (!user.is_empty()).then(|| user.to_owned()),
323 host,
324 absolute,
325 segments,
326 })
327}
328
329impl SourceRef {
330 pub fn from_git_url(url: &str) -> Result<Self, CoreError> {
335 let text = url.trim();
336 Self::parse(text, text).map(|(source, _)| source)
337 }
338
339 pub fn from_key_or_url(text: &str) -> Result<Self, CoreError> {
342 let text = text.trim();
343 Self::parse(&as_url(text), text).map(|(source, _)| source)
344 }
345
346 pub fn canonical_key(text: &str) -> Result<(String, SourceScope), CoreError> {
353 let text = text.trim();
354 let Some(base) = text.strip_suffix("/*") else {
355 return Ok((Self::from_key_or_url(text)?.key, SourceScope::Repo));
356 };
357 let Parsed::Remote(remote) = Self::split(&as_url(&format!("{base}/x")), text)? else {
359 return Err(invalid(text, "a local source has no owner or host key"));
360 };
361 match remote.segments.as_slice() {
362 [_] => Ok((
363 format!("{}{}/*", remote.transport.marker(), remote.host),
364 SourceScope::Host,
365 )),
366 [_, _] => {
367 let (source, _) = Self::from_remote(remote).map_err(|why| invalid(text, why))?;
368 match source.scope_key(SourceScope::Owner) {
369 Some(key) => Ok((key, SourceScope::Owner)),
370 None => Err(invalid(text, "it has no owner")),
371 }
372 }
373 _ => Err(invalid(
374 text,
375 "a key ending in `/*` is host/* (a host) or host/owner/* (an owner)",
376 )),
377 }
378 }
379
380 pub fn redact_userinfo(text: &str) -> String {
383 let mut out = String::with_capacity(text.len());
384 let mut rest = text;
385 while let Some(at) = rest.find("://") {
386 let (head, tail) = rest.split_at(at + 3);
387 out.push_str(head);
388 let end = tail
389 .find(|c: char| c == '/' || c.is_whitespace() || matches!(c, '"' | '\'' | '`'))
390 .unwrap_or(tail.len());
391 match tail[..end].rfind('@') {
392 Some(at) => {
393 out.push_str("***");
394 out.push_str(&tail[at..end]);
395 }
396 None => out.push_str(&tail[..end]),
397 }
398 rest = &tail[end..];
399 }
400 out.push_str(rest);
401 out
402 }
403
404 fn split(text: &str, shown: &str) -> Result<Parsed, CoreError> {
407 if text.to_ascii_lowercase().starts_with("file://") {
408 let path = &text["file://".len()..];
409 return Ok(Parsed::Local(match path.strip_prefix('/') {
412 Some(rest) if is_windows_drive(rest) => rest.to_owned(),
413 Some(_) => path.to_owned(),
414 None => format!("//{path}"),
415 }));
416 }
417 let remote = if let Some((scheme, _)) = text.split_once("://") {
418 let transport = Transport::of_scheme(scheme)
419 .ok_or_else(|| invalid(shown, "unsupported URL scheme"))?;
420 url_remote(text, transport)
421 } else if let Some((user_host, path)) = scp_like(text) {
422 scp_remote(text, user_host, path)
423 } else if is_local_path(text) {
424 return Ok(Parsed::Local(text.to_owned()));
425 } else {
426 return Err(invalid(shown, "not a git URL or an absolute path"));
427 };
428 remote
429 .map(Parsed::Remote)
430 .map_err(|why| invalid(shown, why))
431 }
432
433 fn parse(text: &str, shown: &str) -> Result<(Self, Option<String>), CoreError> {
435 match Self::split(text, shown)? {
436 Parsed::Local(path) => Ok((Self::local(&path, shown)?, None)),
437 Parsed::Remote(remote) => Self::from_remote(remote).map_err(|why| invalid(shown, why)),
438 }
439 }
440
441 pub fn from_local_path(path: &Path) -> Result<Self, CoreError> {
443 let text = path.to_string_lossy();
444 if !is_local_path(&text) {
445 return Err(invalid(&text, "not an absolute path"));
446 }
447 Self::local(&text, &text)
448 }
449
450 pub fn whole_host(url: &str) -> Result<Self, CoreError> {
455 let text = url.trim();
456 let parsed = Url::parse(text).map_err(|_| invalid(text, "it is not a valid URL"))?;
457 let transport = match parsed.scheme() {
458 "https" => Transport::Https,
459 "http" => Transport::Http,
460 _ => return Err(invalid(text, "unsupported URL scheme")),
461 };
462 if !parsed.username().is_empty() || parsed.password().is_some() {
463 return Err(invalid(text, "it carries a user name or password"));
464 }
465 let host = canonical_host(
466 parsed
467 .host_str()
468 .ok_or_else(|| invalid(text, "it has no host"))?,
469 )
470 .map_err(|why| invalid(text, why))?;
471 let host = match parsed.port() {
472 Some(port) if Some(port) != transport.default_port() => format!("{host}:{port}"),
473 _ => host,
474 };
475 let key = format!("{}{host}/*", transport.marker());
476 if key_shape(&key) != Some(SourceScope::Host) {
477 return Err(invalid(text, "its host cannot be a source key"));
478 }
479 Ok(Self {
480 url: format!("{}://{host}", transport.scheme()),
481 address: host.clone(),
482 key,
483 host: Some(host),
484 owner: None,
485 transport,
486 whole_host: true,
487 })
488 }
489
490 fn local(path: &str, original: &str) -> Result<Self, CoreError> {
491 let mut path = path.replace('\\', "/");
492 while path.len() > 1 && path.ends_with('/') {
493 path.pop();
494 }
495 if is_windows_drive(&path) {
496 path[..1].make_ascii_uppercase();
497 }
498 let rest = if path.starts_with("//") {
499 path.as_str()
500 } else {
501 path.trim_start_matches('/')
502 };
503 let key = format!("file:///{rest}");
504 if key_shape(&key) != Some(SourceScope::Repo) {
505 return Err(invalid(original, "not a usable local path"));
506 }
507 Ok(Self {
508 url: key.clone(),
509 key,
510 address: String::new(),
511 host: None,
512 owner: None,
513 transport: Transport::Local,
514 whole_host: false,
515 })
516 }
517
518 fn from_remote(remote: Remote) -> Result<(Self, Option<String>), &'static str> {
522 let Remote {
523 transport,
524 userinfo,
525 host,
526 absolute,
527 mut segments,
528 } = remote;
529 if let Some(cut) = segments.iter().position(|part| part == "-") {
530 segments.truncate(cut);
531 }
532 if host == "github.com" {
533 segments.truncate(2);
534 }
535 if CASE_INSENSITIVE_HOSTS.contains(&host.as_str()) {
536 segments
537 .iter_mut()
538 .for_each(|part| part.make_ascii_lowercase());
539 }
540 let dot_git = match segments.last_mut() {
541 Some(last) if last.ends_with(".git") => {
542 last.truncate(last.len() - ".git".len());
543 if last.is_empty() {
544 return Err("it has no repository name");
545 }
546 true
547 }
548 _ => false,
549 };
550 if segments.is_empty() {
551 return Err("it has no repository path");
552 }
553 let path = segments.join("/");
554 let key = format!("{}{host}/{path}", transport.marker());
555 if key_shape(&key) != Some(SourceScope::Repo) {
556 return Err("it has characters a source key cannot hold");
557 }
558 let fetch_path = if dot_git { format!("{path}.git") } else { path };
559 let address = if transport == Transport::Scp {
560 format!("{host}:{}{fetch_path}", if absolute { "/" } else { "" })
561 } else {
562 format!("{host}/{fetch_path}")
563 };
564 let user = match transport {
566 Transport::Ssh | Transport::Scp => userinfo
567 .as_deref()
568 .map(|info| info.split_once(':').map_or(info, |(user, _)| user)),
569 _ => None,
570 };
571 let url = with_userinfo(transport, user, &address);
572 let source = Self {
573 key,
574 url,
575 address,
576 owner: (segments.len() >= 2).then(|| segments[0].clone()),
577 host: Some(host),
578 transport,
579 whole_host: false,
580 };
581 Ok((source, userinfo))
582 }
583
584 pub fn key(&self) -> &str {
586 &self.key
587 }
588
589 pub fn url(&self) -> &str {
592 &self.url
593 }
594
595 pub fn fetch_url(&self, given: &str) -> String {
601 let given = given.trim();
602 let Ok((other, userinfo)) = Self::parse(given, "") else {
603 return self.url.clone();
604 };
605 let same = other.transport == self.transport
606 && other.key == self.key
607 && other.address == self.address;
608 match (same, self.transport, userinfo) {
609 (true, Transport::Local, _) => given.to_owned(),
610 (true, _, Some(userinfo)) => {
611 with_userinfo(self.transport, Some(&userinfo), &self.address)
612 }
613 _ => self.url.clone(),
614 }
615 }
616
617 pub fn is_insecure(&self) -> bool {
620 !self.transport.marker().is_empty()
621 }
622
623 pub fn is_local(&self) -> bool {
624 self.host.is_none()
625 }
626
627 pub fn local_path(&self) -> Option<PathBuf> {
629 if !self.is_local() {
630 return None;
631 }
632 let rest = self.key.strip_prefix("file:///")?;
633 Some(if is_windows_drive(rest) || rest.starts_with("//") {
634 PathBuf::from(rest)
635 } else {
636 PathBuf::from(format!("/{rest}"))
637 })
638 }
639
640 pub fn host(&self) -> Option<&str> {
641 self.host.as_deref()
642 }
643
644 pub fn owner(&self) -> Option<&str> {
645 self.owner.as_deref()
646 }
647
648 pub fn scope_key(&self, scope: SourceScope) -> Option<String> {
653 let marker = self.transport.marker();
654 match scope {
655 SourceScope::Repo => Some(self.key.clone()),
656 SourceScope::Owner => Some(format!(
657 "{marker}{}/{}/*",
658 self.host.as_ref()?,
659 self.owner.as_ref()?
660 )),
661 SourceScope::Host => Some(format!("{marker}{}/*", self.host.as_ref()?)),
662 }
663 }
664
665 pub fn matching_keys(&self) -> Vec<String> {
667 let mut keys: Vec<String> = [SourceScope::Repo, SourceScope::Owner, SourceScope::Host]
668 .into_iter()
669 .filter_map(|scope| self.scope_key(scope))
670 .collect();
671 keys.dedup();
672 keys
673 }
674
675 pub fn block_keys(&self) -> Vec<String> {
680 let mut keys = self.matching_keys();
681 let marker = self.transport.marker();
682 if !marker.is_empty() {
683 let secure: Vec<String> = keys
684 .iter()
685 .filter_map(|key| key.strip_prefix(marker).map(str::to_owned))
686 .collect();
687 keys.extend(secure);
688 }
689 keys
690 }
691
692 pub fn scopes(&self) -> Vec<SourceScope> {
695 if self.whole_host {
696 return match &self.host {
697 Some(host) if !AGGREGATOR_HOSTS.contains(&host.as_str()) => {
698 vec![SourceScope::Host]
699 }
700 _ => Vec::new(),
701 };
702 }
703 let mut scopes = vec![SourceScope::Repo];
704 if self.owner.is_some() {
705 scopes.push(SourceScope::Owner);
706 }
707 if let Some(host) = &self.host
708 && !AGGREGATOR_HOSTS.contains(&host.as_str())
709 {
710 scopes.push(SourceScope::Host);
711 }
712 scopes
713 }
714
715 pub fn is_official(&self) -> bool {
718 match (&self.host, &self.owner) {
719 (Some(host), Some(owner)) if !self.is_insecure() => {
720 OFFICIAL_OWNERS.contains(&format!("{host}/{owner}").as_str())
721 }
722 _ => false,
723 }
724 }
725}
726
727fn with_userinfo(transport: Transport, userinfo: Option<&str>, address: &str) -> String {
730 let at = userinfo.map(|info| format!("{info}@")).unwrap_or_default();
731 match transport {
732 Transport::Scp => format!("{at}{address}"),
733 _ => format!("{}://{at}{address}", transport.scheme()),
734 }
735}
736
737fn as_url(text: &str) -> String {
740 if text.contains("://") || scp_like(text).is_some() || is_local_path(text) {
741 text.to_owned()
742 } else {
743 format!("https://{text}")
744 }
745}