1#![forbid(unsafe_code)]
6#![cfg_attr(
10 test,
11 allow(
12 clippy::expect_used,
13 clippy::unwrap_used,
14 clippy::indexing_slicing,
15 clippy::useless_format,
16 clippy::clone_on_copy,
17 reason = "Tests legitimately need to unwrap fixture data and index into known-shape \
18 collections"
19 )
20)]
21
22use std::path::{Path, PathBuf};
23
24use thiserror::Error;
25
26pub mod auth;
27pub mod auth_checker;
28pub mod cleanup;
29pub mod cli_error;
30pub mod commit;
31pub mod compatibility;
32pub mod decision;
33pub mod doctor;
34pub mod evaluation;
35pub mod git_ops;
36pub mod issue;
37pub mod issue_quality;
38pub mod label;
39pub mod output;
40pub mod paging;
41pub mod pipeline;
42pub mod pipeline_failure;
43pub mod platform;
44pub mod pr;
45pub mod pr_precheck;
46pub mod query_filter;
47pub mod release;
48pub mod review;
49pub mod semantic_regression;
50pub mod session;
51pub mod skill_suggestion;
52pub mod toon;
53pub mod types;
54pub mod workflow_context;
55pub mod workflow_progress;
56pub mod workflow_recommendation;
57pub mod workflow_semantic;
58
59pub use auth_checker::{AuthCheckResult, AuthChecker};
61pub use cli_error::PlatformCliError;
62pub use compatibility::{PlatformCompat, platform_compatibility, platform_requirement};
63pub use doctor::{CheckItem, CheckStatus, DoctorReport, DoctorSummary, HealthCheck};
64pub use output::{CliError, CliOutput, PaginationMeta};
65pub use paging::{DEFAULT_LIST_LIMIT, FetchStrategy, Paged, fetch_capped};
66
67#[allow(
72 clippy::module_name_repetitions,
73 reason = "Avoids collision with std::error::Error and thiserror::Error"
74)]
75#[derive(Debug, Error)]
76#[non_exhaustive]
77pub enum CoreError {
78 #[error("io error: {0}")]
80 Io(#[from] std::io::Error),
81
82 #[error("serialization error: {0}")]
84 Serialization(#[from] serde_json::Error),
85
86 #[error("application error: {0}")]
89 App(String),
90
91 #[error("path error: {0}")]
93 Path(#[from] PathError),
94
95 #[error("platform error: {0}")]
97 Platform(String),
98
99 #[error(transparent)]
103 Cli(#[from] Box<PlatformCliError>),
104}
105
106impl From<PlatformCliError> for CoreError {
111 fn from(err: PlatformCliError) -> Self {
112 Self::Cli(Box::new(err))
113 }
114}
115
116pub type Result<T> = std::result::Result<T, CoreError>;
118
119pub use auth::{AuthStatus, HostAuthStatus};
121pub use commit::{CommitData, CommitDetail, CommitFile};
122pub use label::{CreateLabelArgs, CreateMilestoneArgs, LabelData, MilestoneData};
123pub use release::{CreateReleaseArgs, ReleaseData};
124pub use review::{ReviewCommentData, ReviewData, ReviewState};
125pub use session::Session;
126pub use types::{CommentData, MergeResult, MergeStrategy};
127
128#[derive(Debug, Clone)]
133#[non_exhaustive]
134pub struct Config {
135 name: String,
136 description: Option<String>,
137}
138
139impl Config {
140 #[must_use]
142 pub fn name(&self) -> &str {
143 &self.name
144 }
145
146 #[must_use]
148 pub fn description(&self) -> Option<&str> {
149 self.description.as_deref()
150 }
151
152 pub fn new(name: impl Into<String>) -> Result<Self> {
166 let name = name.into();
167 if name.is_empty() {
168 return Err(CoreError::App("config name must not be empty".into()));
169 }
170 Ok(Self {
171 name,
172 description: None,
173 })
174 }
175
176 #[must_use]
178 pub fn with_description(mut self, description: impl Into<String>) -> Self {
179 self.description = Some(description.into());
180 self
181 }
182}
183
184#[derive(Debug, Clone)]
186pub struct PathError {
187 pub path: PathBuf,
189 pub kind: PathErrorKind,
191}
192
193impl std::error::Error for PathError {}
194
195#[derive(Debug, Clone)]
197#[non_exhaustive]
198pub enum PathErrorKind {
199 Absolute,
201 ParentDirTraversal,
203 NullByte,
205 DeviceName,
207 InvalidChar {
209 ch: char,
211 },
212 DangerousChar {
214 ch: char,
216 },
217 ComponentTooLong {
219 max_bytes: usize,
221 actual_bytes: usize,
223 },
224}
225
226impl std::fmt::Display for PathError {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 match self.kind {
229 PathErrorKind::Absolute => {
230 write!(f, "absolute path not allowed: {}", self.path.display())
231 }
232 PathErrorKind::ParentDirTraversal => {
233 write!(f, "'..' not allowed: {}", self.path.display())
234 }
235 PathErrorKind::NullByte => write!(f, "null byte in path: {}", self.path.display()),
236 PathErrorKind::DeviceName => write!(
237 f,
238 "reserved device name not allowed: {}",
239 self.path.display()
240 ),
241 PathErrorKind::InvalidChar { ch } => write!(
242 f,
243 "invalid character '{ch}' in path: {}",
244 self.path.display()
245 ),
246 PathErrorKind::DangerousChar { ch } => write!(
247 f,
248 "dangerous Unicode character U+{:04X} in path: {}",
249 ch as u32,
250 self.path.display()
251 ),
252 PathErrorKind::ComponentTooLong {
253 max_bytes,
254 actual_bytes,
255 } => {
256 write!(
257 f,
258 "path component too long (max {max_bytes}B, got {actual_bytes}B): {}",
259 self.path.display()
260 )
261 }
262 }
263 }
264}
265
266#[derive(Debug, Clone)]
271pub struct SafePath(PathBuf);
272
273impl SafePath {
274 pub fn new(path: impl AsRef<Path>) -> Result<Self> {
296 Self::validate(path.as_ref(), false)
297 }
298
299 pub fn new_allow_absolute(path: impl AsRef<Path>) -> Result<Self> {
315 Self::validate(path.as_ref(), true)
316 }
317
318 fn validate(path: &Path, allow_absolute: bool) -> Result<Self> {
319 const MAX_COMPONENT_LEN: usize = 255;
320
321 if !allow_absolute && path.is_absolute() {
323 return Err(PathError {
324 path: path.to_path_buf(),
325 kind: PathErrorKind::Absolute,
326 }
327 .into());
328 }
329
330 if path
332 .components()
333 .any(|c| c == std::path::Component::ParentDir)
334 {
335 return Err(PathError {
336 path: path.to_path_buf(),
337 kind: PathErrorKind::ParentDirTraversal,
338 }
339 .into());
340 }
341
342 if path.as_os_str().as_encoded_bytes().contains(&b'\0') {
344 return Err(PathError {
345 path: path.to_path_buf(),
346 kind: PathErrorKind::NullByte,
347 }
348 .into());
349 }
350
351 if path.components().any(|c| {
356 !matches!(c, std::path::Component::Prefix(_))
357 && c.as_os_str().as_encoded_bytes().contains(&b':')
358 }) {
359 return Err(PathError {
360 path: path.to_path_buf(),
361 kind: PathErrorKind::InvalidChar { ch: ':' },
362 }
363 .into());
364 }
365
366 #[cfg(windows)]
368 {
369 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
370 let upper = stem.to_uppercase();
371 if matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
372 || (upper.len() == 4
373 && (upper.starts_with("COM") || upper.starts_with("LPT"))
374 && upper[3..].parse::<u8>().is_ok())
375 {
376 return Err(PathError {
377 path: path.to_path_buf(),
378 kind: PathErrorKind::DeviceName,
379 }
380 .into());
381 }
382 }
383 }
384
385 for component in path.components() {
387 let len = component.as_os_str().len();
388 if len > MAX_COMPONENT_LEN {
389 return Err(PathError {
390 path: path.to_path_buf(),
391 kind: PathErrorKind::ComponentTooLong {
392 max_bytes: MAX_COMPONENT_LEN,
393 actual_bytes: len,
394 },
395 }
396 .into());
397 }
398
399 let s = component.as_os_str().to_string_lossy();
400 for ch in s.chars() {
401 if matches!(ch, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') {
402 return Err(PathError {
403 path: path.to_path_buf(),
404 kind: PathErrorKind::DangerousChar { ch },
405 }
406 .into());
407 }
408 }
409 }
410
411 Ok(Self(path.to_path_buf()))
412 }
413
414 #[must_use]
416 pub fn as_path(&self) -> &Path {
417 &self.0
418 }
419}
420
421impl AsRef<Path> for SafePath {
422 fn as_ref(&self) -> &Path {
423 &self.0
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430
431 #[test]
432 fn test_config_new_with_valid_name() -> Result<()> {
433 let config = Config::new("test")?;
434 assert_eq!(config.name(), "test");
435 assert!(config.description().is_none());
436 Ok(())
437 }
438
439 #[test]
440 fn test_config_new_with_empty_name_errors() {
441 let err = Config::new("");
442 assert!(matches!(err, Err(CoreError::App(_))));
443 }
444
445 #[test]
446 fn test_config_with_description() -> Result<()> {
447 let config = Config::new("test")?.with_description("a test config");
448 assert_eq!(config.description(), Some("a test config"));
449 Ok(())
450 }
451
452 #[test]
453 fn test_io_error_conversion() {
454 let io_err = std::io::Error::other("test");
455 let core_err = CoreError::from(io_err);
456 assert!(matches!(core_err, CoreError::Io(_)));
457 }
458
459 #[test]
460 fn test_serialization_error_conversion() {
461 let io_err = std::io::Error::other("invalid json");
462 let serde_err = serde_json::Error::io(io_err);
463 let core_err = CoreError::from(serde_err);
464 assert!(matches!(core_err, CoreError::Serialization(_)));
465 }
466
467 #[test]
468 fn test_safe_path_accepts_relative() -> Result<()> {
469 let sp = SafePath::new("foo/bar.txt")?;
470 assert_eq!(sp.as_path(), Path::new("foo/bar.txt"));
471 Ok(())
472 }
473
474 #[test]
475 fn test_safe_path_rejects_absolute() {
476 #[cfg(unix)]
477 let absolute_path = "/etc/passwd";
478 #[cfg(windows)]
479 let absolute_path = r"C:\Windows\system32";
480 assert!(matches!(
481 SafePath::new(absolute_path),
482 Err(CoreError::Path(_))
483 ));
484 }
485
486 #[test]
487 fn test_safe_path_rejects_parent_dir() {
488 assert!(matches!(
489 SafePath::new("../secret.txt"),
490 Err(CoreError::Path(_))
491 ));
492 }
493
494 #[test]
495 fn test_safe_path_rejects_null_byte() {
496 assert!(matches!(
497 SafePath::new("foo\0bar.txt"),
498 Err(CoreError::Path(_))
499 ));
500 }
501
502 #[test]
503 fn test_safe_path_rejects_colon() {
504 let err = SafePath::new("foo:bar.txt");
505 assert!(matches!(
506 err,
507 Err(CoreError::Path(PathError {
508 kind: PathErrorKind::InvalidChar { ch: ':' },
509 ..
510 }))
511 ));
512 }
513
514 #[test]
515 #[cfg(windows)]
516 fn test_safe_path_allows_windows_drive_letter_colon() {
517 let sp = SafePath::new_allow_absolute(r"C:\Users\runner\Temp\body.md");
521 assert!(
522 sp.is_ok(),
523 "drive-letter colon must not be rejected: {sp:?}"
524 );
525 }
526
527 #[test]
528 #[cfg(windows)]
529 fn test_safe_path_rejects_ads_colon_in_absolute_windows_path() {
530 let err = SafePath::new_allow_absolute(r"C:\Users\runner\Temp\body.md:evil");
534 assert!(matches!(
535 err,
536 Err(CoreError::Path(PathError {
537 kind: PathErrorKind::InvalidChar { ch: ':' },
538 ..
539 }))
540 ));
541 }
542
543 #[test]
544 fn test_safe_path_rejects_bidi_control_chars() {
545 let path = format!("foo\u{202A}bar.txt");
547 let err = SafePath::new(path);
548 assert!(matches!(
549 err,
550 Err(CoreError::Path(PathError {
551 kind: PathErrorKind::DangerousChar { ch: '\u{202A}' },
552 ..
553 }))
554 ));
555
556 let path = format!("foo\u{2066}bar.txt");
558 let err = SafePath::new(path);
559 assert!(matches!(
560 err,
561 Err(CoreError::Path(PathError {
562 kind: PathErrorKind::DangerousChar { ch: '\u{2066}' },
563 ..
564 }))
565 ));
566 }
567
568 #[test]
569 fn test_safe_path_rejects_component_too_long() {
570 let long_component = "a".repeat(256);
571 let err = SafePath::new(&long_component);
572 assert!(matches!(
573 err,
574 Err(CoreError::Path(PathError {
575 kind: PathErrorKind::ComponentTooLong {
576 max_bytes: 255,
577 actual_bytes: 256
578 },
579 ..
580 }))
581 ));
582 }
583
584 #[test]
585 fn test_safe_path_accepts_max_component() -> Result<()> {
586 let max_component = "a".repeat(255);
587 let sp = SafePath::new(&max_component)?;
588 assert_eq!(sp.as_path().as_os_str().len(), 255);
589 Ok(())
590 }
591
592 #[test]
593 fn test_safe_path_allow_absolute_accepts_absolute() -> Result<()> {
594 #[cfg(unix)]
595 let absolute_path = "/home/user/custom-skills";
596 #[cfg(windows)]
597 let absolute_path = r"C:\Users\user\custom-skills";
598 let sp = SafePath::new_allow_absolute(absolute_path)?;
599 assert_eq!(sp.as_path(), Path::new(absolute_path));
600 Ok(())
601 }
602
603 #[test]
604 fn test_safe_path_allow_absolute_accepts_relative() -> Result<()> {
605 let sp = SafePath::new_allow_absolute("foo/bar.txt")?;
606 assert_eq!(sp.as_path(), Path::new("foo/bar.txt"));
607 Ok(())
608 }
609
610 #[test]
611 fn test_safe_path_allow_absolute_rejects_parent_dir() {
612 assert!(matches!(
613 SafePath::new_allow_absolute("../secret.txt"),
614 Err(CoreError::Path(_))
615 ));
616 assert!(matches!(
617 SafePath::new_allow_absolute("/foo/../bar"),
618 Err(CoreError::Path(_))
619 ));
620 }
621
622 #[test]
623 fn test_safe_path_allow_absolute_rejects_null_byte() {
624 assert!(matches!(
625 SafePath::new_allow_absolute("foo\0bar.txt"),
626 Err(CoreError::Path(_))
627 ));
628 }
629
630 #[test]
631 fn test_platform_error_variant() {
632 let err = CoreError::Platform("gh not found".into());
633 assert!(matches!(err, CoreError::Platform(_)));
634 let msg = format!("{err}");
635 assert!(msg.contains("platform error"));
636 assert!(msg.contains("gh not found"));
637 }
638
639 #[test]
640 fn test_cli_error_from_platform_cli_error() {
641 let platform_err = PlatformCliError {
642 user_message: "认证失败".into(),
643 raw_stderr: "raw".into(),
644 hint: None,
645 doc_link: None,
646 code: None,
647 platform: platform::Platform::GitHub,
648 };
649 let core_err: CoreError = platform_err.into();
651 assert!(matches!(core_err, CoreError::Cli(_)));
652 let msg = format!("{core_err}");
654 assert!(msg.contains("认证失败"));
655 }
656}
657