strict-path 0.1.0-beta.1

More than path comparisons: full, cross-platform path security with type-level guarantees
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
// Content copied from original src/validator/restriction.rs
use crate::error::StrictPathError;
use crate::path::strict_path::StrictPath;
use crate::validator::path_history::*;
use crate::Result;

#[cfg(windows)]
use std::ffi::OsStr;
use std::io::{Error as IoError, ErrorKind};
use std::marker::PhantomData;
use std::path::Path;
use std::sync::Arc;

#[cfg(feature = "tempfile")]
use tempfile::TempDir;

#[cfg(windows)]
use std::path::Component;

#[cfg(windows)]
fn is_potential_83_short_name(os: &OsStr) -> bool {
    let s = os.to_string_lossy();
    if let Some(pos) = s.find('~') {
        s[pos + 1..]
            .chars()
            .next()
            .is_some_and(|ch| ch.is_ascii_digit())
    } else {
        false
    }
}

/// SUMMARY:
/// Canonicalize a candidate path and enforce the `PathBoundary` boundary, returning a `StrictPath`.
///
/// PARAMETERS:
/// - `path` (`AsRef<Path>`): Candidate path to validate (absolute or relative).
/// - `restriction` (&`PathBoundary<Marker>`): Boundary to enforce during resolution.
///
/// RETURNS:
/// - `Result<StrictPath<Marker>>`: Canonicalized path proven to be within `restriction`.
///
/// ERRORS:
/// - `StrictPathError::WindowsShortName` (windows): Relative input contains a DOS 8.3 short name segment.
/// - `StrictPathError::PathResolutionError`: Canonicalization fails (I/O or resolution error).
/// - `StrictPathError::PathEscapesBoundary`: Resolved path would escape the boundary.
///
/// EXAMPLE:
/// ```rust
/// # use strict_path::{PathBoundary, Result};
/// # fn main() -> Result<()> {
/// let boundary = PathBoundary::<()>::try_new_create("./sandbox")?;
/// // Use the public API that exercises the same validation pipeline
/// // as this internal helper.
/// let file = boundary.strict_join("sub/file.txt")?;
/// assert!(file.interop_path().to_string_lossy().contains("sandbox"));
/// # Ok(())
/// # }
/// ```
pub(crate) fn canonicalize_and_enforce_restriction_boundary<Marker>(
    path: impl AsRef<Path>,
    restriction: &PathBoundary<Marker>,
) -> Result<StrictPath<Marker>> {
    #[cfg(windows)]
    {
        let original_user_path = path.as_ref().to_path_buf();
        if !path.as_ref().is_absolute() {
            let mut probe = restriction.path().to_path_buf();
            for comp in path.as_ref().components() {
                match comp {
                    Component::CurDir | Component::ParentDir => continue,
                    Component::RootDir | Component::Prefix(_) => continue,
                    Component::Normal(name) => {
                        if is_potential_83_short_name(name) {
                            return Err(StrictPathError::windows_short_name(
                                name.to_os_string(),
                                original_user_path,
                                probe.clone(),
                            ));
                        }
                        probe.push(name);
                    }
                }
            }
        }
    }

    let target_path = if path.as_ref().is_absolute() {
        path.as_ref().to_path_buf()
    } else {
        restriction.path().join(path.as_ref())
    };

    let validated_path = PathHistory::<Raw>::new(target_path)
        .canonicalize()?
        .boundary_check(&restriction.path)?;

    Ok(StrictPath::new(
        Arc::new(restriction.clone()),
        validated_path,
    ))
}

/// A path boundary that serves as the secure foundation for validated path operations.
///
/// SUMMARY:
/// Represent the trusted filesystem root for all strict and virtual path operations. All
/// `StrictPath`/`VirtualPath` values derived from a `PathBoundary` are guaranteed to remain
/// within this boundary.
///
/// EXAMPLE:
/// ```rust
/// # use strict_path::PathBoundary;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let boundary = PathBoundary::<()>::try_new_create("./data")?;
/// let file = boundary.strict_join("logs/app.log")?;
/// println!("{}", file.strictpath_display());
/// # Ok(())
/// # }
/// ```
pub struct PathBoundary<Marker = ()> {
    path: Arc<PathHistory<((Raw, Canonicalized), Exists)>>,
    #[cfg(feature = "tempfile")]
    _temp_dir: Option<Arc<TempDir>>,
    _marker: PhantomData<Marker>,
}

impl<Marker> Clone for PathBoundary<Marker> {
    fn clone(&self) -> Self {
        Self {
            path: self.path.clone(),
            #[cfg(feature = "tempfile")]
            _temp_dir: self._temp_dir.clone(),
            _marker: PhantomData,
        }
    }
}

impl<Marker> PartialEq for PathBoundary<Marker> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.path() == other.path()
    }
}

impl<Marker> Eq for PathBoundary<Marker> {}

impl<Marker> std::hash::Hash for PathBoundary<Marker> {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.path().hash(state);
    }
}

impl<Marker> PartialOrd for PathBoundary<Marker> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<Marker> Ord for PathBoundary<Marker> {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.path().cmp(other.path())
    }
}

impl<Marker> PartialEq<crate::validator::virtual_root::VirtualRoot<Marker>>
    for PathBoundary<Marker>
{
    #[inline]
    fn eq(&self, other: &crate::validator::virtual_root::VirtualRoot<Marker>) -> bool {
        self.path() == other.path()
    }
}

impl<Marker> PartialEq<Path> for PathBoundary<Marker> {
    #[inline]
    fn eq(&self, other: &Path) -> bool {
        self.path() == other
    }
}

impl<Marker> PartialEq<std::path::PathBuf> for PathBoundary<Marker> {
    #[inline]
    fn eq(&self, other: &std::path::PathBuf) -> bool {
        self.eq(other.as_path())
    }
}

impl<Marker> PartialEq<&std::path::Path> for PathBoundary<Marker> {
    #[inline]
    fn eq(&self, other: &&std::path::Path) -> bool {
        self.eq(*other)
    }
}

impl<Marker> PathBoundary<Marker> {
    /// Private constructor that allows setting the temp_dir during construction
    #[cfg(feature = "tempfile")]
    fn new_with_temp_dir(
        path: Arc<PathHistory<((Raw, Canonicalized), Exists)>>,
        temp_dir: Option<Arc<TempDir>>,
    ) -> Self {
        Self {
            path,
            _temp_dir: temp_dir,
            _marker: PhantomData,
        }
    }

    /// Creates a new `PathBoundary` rooted at `restriction_path` (which must already exist and be a directory).
    ///
    /// SUMMARY:
    /// Create a boundary anchored at an existing directory (must exist and be a directory).
    ///
    /// PARAMETERS:
    /// - `restriction_path` (`AsRef<Path>`): Existing directory to anchor the boundary.
    ///
    /// RETURNS:
    /// - `Result<PathBoundary<Marker>>`: New boundary whose root is canonicalized and verified to exist.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: Root is missing, not a directory, or cannot be canonicalized.
    ///
    /// EXAMPLE:
    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
    /// ```rust
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use strict_path::PathBoundary;
    /// let tmp_dir = tempfile::tempdir()?;
    /// let tmp_dir = PathBoundary::<()>::try_new(tmp_dir)?; // Clean variable shadowing
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn try_new<P: AsRef<Path>>(restriction_path: P) -> Result<Self> {
        let restriction_path = restriction_path.as_ref();
        let raw = PathHistory::<Raw>::new(restriction_path);

        let canonicalized = raw.canonicalize()?;

        let verified_exists = match canonicalized.verify_exists() {
            Some(path) => path,
            None => {
                let io = IoError::new(
                    ErrorKind::NotFound,
                    "The specified PathBoundary path does not exist.",
                );
                return Err(StrictPathError::invalid_restriction(
                    restriction_path.to_path_buf(),
                    io,
                ));
            }
        };

        if !verified_exists.is_dir() {
            let error = IoError::new(
                ErrorKind::InvalidInput,
                "The specified PathBoundary path exists but is not a directory.",
            );
            return Err(StrictPathError::invalid_restriction(
                restriction_path.to_path_buf(),
                error,
            ));
        }

        #[cfg(feature = "tempfile")]
        {
            Ok(Self::new_with_temp_dir(Arc::new(verified_exists), None))
        }
        #[cfg(not(feature = "tempfile"))]
        {
            Ok(Self {
                path: Arc::new(verified_exists),
                _marker: PhantomData,
            })
        }
    }

    /// Creates the directory if missing, then constructs a new `PathBoundary`.
    ///
    /// SUMMARY:
    /// Ensure the root exists (create if missing) and construct a new boundary.
    ///
    /// PARAMETERS:
    /// - `root` (`AsRef<Path>`): Directory to create if needed and use as boundary root.
    ///
    /// RETURNS:
    /// - `Result<PathBoundary<Marker>>`: New boundary anchored at `root`.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: Directory creation/canonicalization fails.
    ///
    /// EXAMPLE:
    /// Uses `AsRef<Path>` for maximum ergonomics, including direct `TempDir` support for clean shadowing patterns:
    /// ```rust
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use strict_path::PathBoundary;
    /// let tmp_dir = tempfile::tempdir()?;
    /// let tmp_dir = PathBoundary::<()>::try_new_create(tmp_dir)?; // Clean variable shadowing
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_new_create<P: AsRef<Path>>(root: P) -> Result<Self> {
        let root_path = root.as_ref();
        if !root_path.exists() {
            std::fs::create_dir_all(root_path)
                .map_err(|e| StrictPathError::invalid_restriction(root_path.to_path_buf(), e))?;
        }
        Self::try_new(root_path)
    }

    /// SUMMARY:
    /// Join a candidate path to the boundary and return a validated `StrictPath`.
    ///
    /// PARAMETERS:
    /// - `candidate_path` (`AsRef<Path>`): Absolute or relative path to validate within this boundary.
    ///
    /// RETURNS:
    /// - `Result<StrictPath<Marker>>`: Canonicalized, boundary-checked path.
    ///
    /// ERRORS:
    /// - `StrictPathError::WindowsShortName` (windows), `StrictPathError::PathResolutionError`,
    ///   `StrictPathError::PathEscapesBoundary`.
    #[inline]
    pub fn strict_join(&self, candidate_path: impl AsRef<Path>) -> Result<StrictPath<Marker>> {
        canonicalize_and_enforce_restriction_boundary(candidate_path, self)
    }

    /// Returns the canonicalized PathBoundary root path. Kept crate-private to avoid leaking raw path.
    #[inline]
    pub(crate) fn path(&self) -> &Path {
        self.path.as_ref()
    }

    /// Internal: returns the canonicalized PathHistory of the PathBoundary root for boundary checks.
    #[inline]
    pub(crate) fn stated_path(&self) -> &PathHistory<((Raw, Canonicalized), Exists)> {
        &self.path
    }

    /// Returns true if the PathBoundary root exists.
    ///
    /// This is always true for a constructed PathBoundary, but we query the filesystem for robustness.
    #[inline]
    pub fn exists(&self) -> bool {
        self.path.exists()
    }

    /// SUMMARY:
    /// Return the root path as `&OsStr` for `AsRef<Path>` interop (no allocation).
    #[inline]
    pub fn interop_path(&self) -> &std::ffi::OsStr {
        self.path.as_os_str()
    }

    /// Returns a Display wrapper that shows the PathBoundary root system path.
    #[inline]
    pub fn strictpath_display(&self) -> std::path::Display<'_> {
        self.path().display()
    }

    /// Internal helper: exposes the tempfile RAII handle so `VirtualRoot` constructors can mirror cleanup semantics when constructed from temporary directories.
    #[cfg(feature = "tempfile")]
    #[inline]
    pub(crate) fn temp_dir_arc(&self) -> Option<Arc<TempDir>> {
        self._temp_dir.clone()
    }

    /// SUMMARY:
    /// Return filesystem metadata for the boundary root.
    #[inline]
    pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
        std::fs::metadata(self.path())
    }

    /// SUMMARY:
    /// Create a symbolic link at `link_path` pointing to this boundary's root.
    ///
    /// PARAMETERS:
    /// - `link_path` (&`StrictPath<Marker>`): Destination for the symlink, within the same boundary.
    ///
    /// RETURNS:
    /// - `io::Result<()>`: Mirrors std semantics.
    pub fn strict_symlink(
        &self,
        link_path: &crate::path::strict_path::StrictPath<Marker>,
    ) -> std::io::Result<()> {
        let root = self
            .strict_join("")
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.strict_symlink(link_path)
    }

    /// SUMMARY:
    /// Create a hard link at `link_path` pointing to this boundary's root.
    ///
    /// PARAMETERS and RETURNS mirror `strict_symlink`.
    pub fn strict_hard_link(
        &self,
        link_path: &crate::path::strict_path::StrictPath<Marker>,
    ) -> std::io::Result<()> {
        let root = self
            .strict_join("")
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;

        root.strict_hard_link(link_path)
    }

    /// SUMMARY:
    /// Read directory entries under the boundary root (discovery only).
    #[inline]
    pub fn read_dir(&self) -> std::io::Result<std::fs::ReadDir> {
        std::fs::read_dir(self.path())
    }

    /// SUMMARY:
    /// Remove the boundary root directory (non-recursive); fails if not empty.
    #[inline]
    pub fn remove_dir(&self) -> std::io::Result<()> {
        std::fs::remove_dir(self.path())
    }

    /// SUMMARY:
    /// Recursively remove the boundary root directory and contents.
    #[inline]
    pub fn remove_dir_all(&self) -> std::io::Result<()> {
        std::fs::remove_dir_all(self.path())
    }

    /// SUMMARY:
    /// Convert this boundary into a `VirtualRoot` for virtual path operations.
    #[inline]
    pub fn virtualize(self) -> crate::VirtualRoot<Marker> {
        crate::VirtualRoot {
            root: self,
            #[cfg(feature = "tempfile")]
            _temp_dir: None,
            _marker: PhantomData,
        }
    }

    // Note: Do not add new crate-private helpers unless necessary; use existing flows.

    // OS Standard Directory Constructors
    //
    // These constructors provide secure access to operating system standard directories
    // following platform-specific conventions (XDG on Linux, Known Folder API on Windows,
    // Apple Standard Directories on macOS). Each creates an app-specific subdirectory
    // and enforces path boundaries for secure file operations.

    /// Creates a PathBoundary in the OS standard config directory for the given application.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `~/.config/{app_name}` (XDG Base Directory Specification)
    /// - **Windows**: `%APPDATA%\{app_name}` (Known Folder API - Roaming AppData)
    /// - **macOS**: `~/Library/Application Support/{app_name}` (Apple Standard Directories)
    ///
    /// Respects environment variables like `$XDG_CONFIG_HOME` on Linux systems.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_config(app_name: &str) -> Result<Self> {
        let config_dir = dirs::config_dir()
            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-config".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS config directory not available",
                ),
            })?
            .join(app_name);
        Self::try_new_create(config_dir)
    }

    /// Creates a PathBoundary in the OS standard data directory for the given application.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `~/.local/share/{app_name}` (XDG Base Directory Specification)
    /// - **Windows**: `%APPDATA%\{app_name}` (Known Folder API - Roaming AppData)
    /// - **macOS**: `~/Library/Application Support/{app_name}` (Apple Standard Directories)
    ///
    /// Respects environment variables like `$XDG_DATA_HOME` on Linux systems.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_data(app_name: &str) -> Result<Self> {
        let data_dir = dirs::data_dir()
            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-data".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS data directory not available",
                ),
            })?
            .join(app_name);
        Self::try_new_create(data_dir)
    }

    /// Creates a PathBoundary in the OS standard cache directory for the given application.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `~/.cache/{app_name}` (XDG Base Directory Specification)
    /// - **Windows**: `%LOCALAPPDATA%\{app_name}` (Known Folder API - Local AppData)
    /// - **macOS**: `~/Library/Caches/{app_name}` (Apple Standard Directories)
    ///
    /// Respects environment variables like `$XDG_CACHE_HOME` on Linux systems.
    #[cfg(feature = "dirs")]
    pub fn try_new_os_cache(app_name: &str) -> Result<Self> {
        let cache_dir = dirs::cache_dir()
            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-cache".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS cache directory not available",
                ),
            })?
            .join(app_name);
        Self::try_new_create(cache_dir)
    }

    /// Creates a PathBoundary in the OS local config directory (non-roaming on Windows).
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `~/.config/{app_name}` (same as config_dir)
    /// - **Windows**: `%LOCALAPPDATA%\{app_name}` (Known Folder API - Local AppData)
    /// - **macOS**: `~/Library/Application Support/{app_name}` (same as config_dir)
    #[cfg(feature = "dirs")]
    pub fn try_new_os_config_local(app_name: &str) -> Result<Self> {
        let config_dir = dirs::config_local_dir()
            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-config-local".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS local config directory not available",
                ),
            })?
            .join(app_name);
        Self::try_new_create(config_dir)
    }

    /// Creates a PathBoundary in the OS local data directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `~/.local/share/{app_name}` (same as data_dir)
    /// - **Windows**: `%LOCALAPPDATA%\{app_name}` (Known Folder API - Local AppData)
    /// - **macOS**: `~/Library/Application Support/{app_name}` (same as data_dir)
    #[cfg(feature = "dirs")]
    pub fn try_new_os_data_local(app_name: &str) -> Result<Self> {
        let data_dir = dirs::data_local_dir()
            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-data-local".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS local data directory not available",
                ),
            })?
            .join(app_name);
        Self::try_new_create(data_dir)
    }

    /// Creates a PathBoundary in the user's home directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME`
    /// - **Windows**: `%USERPROFILE%` (e.g., `C:\Users\Username`)
    /// - **macOS**: `$HOME`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_home() -> Result<Self> {
        let home_dir =
            dirs::home_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-home".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS home directory not available",
                ),
            })?;
        Self::try_new(home_dir)
    }

    /// Creates a PathBoundary in the user's desktop directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME/Desktop` or XDG_DESKTOP_DIR
    /// - **Windows**: `%USERPROFILE%\Desktop`
    /// - **macOS**: `$HOME/Desktop`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_desktop() -> Result<Self> {
        let desktop_dir =
            dirs::desktop_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-desktop".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS desktop directory not available",
                ),
            })?;
        Self::try_new(desktop_dir)
    }

    /// Creates a PathBoundary in the user's documents directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME/Documents` or XDG_DOCUMENTS_DIR
    /// - **Windows**: `%USERPROFILE%\Documents`
    /// - **macOS**: `$HOME/Documents`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_documents() -> Result<Self> {
        let docs_dir =
            dirs::document_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-documents".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS documents directory not available",
                ),
            })?;
        Self::try_new(docs_dir)
    }

    /// Creates a PathBoundary in the user's downloads directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME/Downloads` or XDG_DOWNLOAD_DIR
    /// - **Windows**: `%USERPROFILE%\Downloads`
    /// - **macOS**: `$HOME/Downloads`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_downloads() -> Result<Self> {
        let downloads_dir =
            dirs::download_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-downloads".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS downloads directory not available",
                ),
            })?;
        Self::try_new(downloads_dir)
    }

    /// Creates a PathBoundary in the user's pictures directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME/Pictures` or XDG_PICTURES_DIR
    /// - **Windows**: `%USERPROFILE%\Pictures`
    /// - **macOS**: `$HOME/Pictures`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_pictures() -> Result<Self> {
        let pictures_dir =
            dirs::picture_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-pictures".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS pictures directory not available",
                ),
            })?;
        Self::try_new(pictures_dir)
    }

    /// Creates a PathBoundary in the user's music/audio directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME/Music` or XDG_MUSIC_DIR
    /// - **Windows**: `%USERPROFILE%\Music`
    /// - **macOS**: `$HOME/Music`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_audio() -> Result<Self> {
        let audio_dir =
            dirs::audio_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-audio".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS audio directory not available",
                ),
            })?;
        Self::try_new(audio_dir)
    }

    /// Creates a PathBoundary in the user's videos directory.
    ///
    /// **Cross-Platform Behavior:**
    /// - **Linux**: `$HOME/Videos` or XDG_VIDEOS_DIR  
    /// - **Windows**: `%USERPROFILE%\Videos`
    /// - **macOS**: `$HOME/Movies`
    #[cfg(feature = "dirs")]
    pub fn try_new_os_videos() -> Result<Self> {
        let videos_dir =
            dirs::video_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-videos".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS videos directory not available",
                ),
            })?;
        Self::try_new(videos_dir)
    }

    /// Creates a PathBoundary in the OS executable directory (Linux only).
    ///
    /// **Platform Availability:**
    /// - **Linux**: `~/.local/bin` or $XDG_BIN_HOME
    /// - **Windows**: Returns error (not available)
    /// - **macOS**: Returns error (not available)
    #[cfg(feature = "dirs")]
    pub fn try_new_os_executables() -> Result<Self> {
        let exec_dir =
            dirs::executable_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-executables".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS executables directory not available on this platform",
                ),
            })?;
        Self::try_new(exec_dir)
    }

    /// Creates a PathBoundary in the OS runtime directory (Linux only).
    ///
    /// **Platform Availability:**
    /// - **Linux**: `$XDG_RUNTIME_DIR` (session-specific, user-only access)
    /// - **Windows**: Returns error (not available)
    /// - **macOS**: Returns error (not available)
    #[cfg(feature = "dirs")]
    pub fn try_new_os_runtime() -> Result<Self> {
        let runtime_dir =
            dirs::runtime_dir().ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-runtime".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS runtime directory not available on this platform",
                ),
            })?;
        Self::try_new(runtime_dir)
    }

    /// Creates a PathBoundary in the OS state directory (Linux only).
    ///
    /// **Platform Availability:**
    /// - **Linux**: `~/.local/state/{app_name}` or $XDG_STATE_HOME/{app_name}
    /// - **Windows**: Returns error (not available)
    /// - **macOS**: Returns error (not available)
    #[cfg(feature = "dirs")]
    pub fn try_new_os_state(app_name: &str) -> Result<Self> {
        let state_dir = dirs::state_dir()
            .ok_or_else(|| crate::StrictPathError::InvalidRestriction {
                restriction: "os-state".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "OS state directory not available on this platform",
                ),
            })?
            .join(app_name);
        Self::try_new_create(state_dir)
    }

    /// Creates a PathBoundary in a unique temporary directory with RAII cleanup.
    ///
    /// Returns a `StrictPath` pointing to the temp directory root. The directory
    /// will be automatically cleaned up when the `StrictPath` is dropped.
    ///
    /// # Example
    /// ```
    /// # #[cfg(feature = "tempfile")] {
    /// use strict_path::PathBoundary;
    ///
    /// // Get a validated temp directory path directly
    /// let temp_root = PathBoundary::<()>::try_new_temp()?;
    /// let user_input = "uploads/document.pdf";
    /// let validated_path = temp_root.strict_join(user_input)?; // Returns StrictPath
    /// // Ensure parent directories exist before writing
    /// validated_path.create_parent_dir_all()?;
    /// std::fs::write(validated_path.interop_path(), b"content")?; // Direct filesystem access
    /// // temp_root is dropped here, directory gets cleaned up automatically
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "tempfile")]
    pub fn try_new_temp() -> Result<Self> {
        let temp_dir =
            tempfile::tempdir().map_err(|e| crate::StrictPathError::InvalidRestriction {
                restriction: "temp".into(),
                source: e,
            })?;

        let temp_path = temp_dir.path();
        let raw = PathHistory::<Raw>::new(temp_path);
        let canonicalized = raw.canonicalize()?;
        let verified_exists = canonicalized.verify_exists().ok_or_else(|| {
            crate::StrictPathError::InvalidRestriction {
                restriction: "temp".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Temp directory verification failed",
                ),
            }
        })?;

        Ok(Self::new_with_temp_dir(
            Arc::new(verified_exists),
            Some(Arc::new(temp_dir)),
        ))
    }

    /// Creates a PathBoundary in a temporary directory with a custom prefix and RAII cleanup.
    ///
    /// Returns a `StrictPath` pointing to the temp directory root. The directory
    /// will be automatically cleaned up when the `StrictPath` is dropped.
    ///
    /// # Example
    /// ```
    /// # #[cfg(feature = "tempfile")] {
    /// use strict_path::PathBoundary;
    ///
    /// // Get a validated temp directory path with session prefix
    /// let upload_root = PathBoundary::<()>::try_new_temp_with_prefix("upload_batch")?;
    /// let user_file = upload_root.strict_join("user_document.pdf")?; // Validate path
    /// // Process validated path with direct filesystem operations
    /// // upload_root is dropped here, directory gets cleaned up automatically
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "tempfile")]
    pub fn try_new_temp_with_prefix(prefix: &str) -> Result<Self> {
        let temp_dir = tempfile::Builder::new()
            .prefix(prefix)
            .tempdir()
            .map_err(|e| crate::StrictPathError::InvalidRestriction {
                restriction: "temp".into(),
                source: e,
            })?;

        let temp_path = temp_dir.path();
        let raw = PathHistory::<Raw>::new(temp_path);
        let canonicalized = raw.canonicalize()?;
        let verified_exists = canonicalized.verify_exists().ok_or_else(|| {
            crate::StrictPathError::InvalidRestriction {
                restriction: "temp".into(),
                source: std::io::Error::new(
                    std::io::ErrorKind::NotFound,
                    "Temp directory verification failed",
                ),
            }
        })?;

        Ok(Self::new_with_temp_dir(
            Arc::new(verified_exists),
            Some(Arc::new(temp_dir)),
        ))
    }

    /// SUMMARY:
    /// Create a boundary using `app-path` semantics (portable app-relative directory) with optional env override.
    ///
    /// PARAMETERS:
    /// - `subdir` (`AsRef<Path>`): Subdirectory path relative to the executable (or override directory).
    /// - `env_override` (Option<&str>): Optional environment variable name; when present and set,
    ///   its value is used as the base directory instead of the executable directory.
    ///
    /// RETURNS:
    /// - `Result<PathBoundary<Marker>>`: Created/validated boundary at the resolved app-path location.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: If resolution fails or directory cannot be created/validated.
    ///
    /// EXAMPLE:
    /// ```
    /// # #[cfg(feature = "app-path")] {
    /// use strict_path::PathBoundary;
    ///
    /// // Creates ./config/ relative to executable
    /// let config_restriction = PathBoundary::<()>::try_new_app_path("config", None)?;
    ///
    /// // With environment override (checks MYAPP_CONFIG_DIR first)
    /// let config_restriction = PathBoundary::<()>::try_new_app_path("config", Some("MYAPP_CONFIG_DIR"))?;
    /// # }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "app-path")]
    pub fn try_new_app_path<P: AsRef<std::path::Path>>(
        subdir: P,
        env_override: Option<&str>,
    ) -> Result<Self> {
        let subdir_path = subdir.as_ref();
        // Resolve the override environment variable name (if provided) to its value.
        // app-path expects the override PATH value, not the variable name.
        let override_value: Option<String> = env_override.and_then(|key| std::env::var(key).ok());
        let app_path = app_path::AppPath::try_with_override(subdir_path, override_value.as_deref())
            .map_err(|e| crate::StrictPathError::InvalidRestriction {
                restriction: format!("app-path: {}", subdir_path.display()).into(),
                source: std::io::Error::new(std::io::ErrorKind::InvalidInput, e),
            })?;

        Self::try_new_create(app_path)
    }

    /// SUMMARY:
    /// Create a boundary using `app-path`, always consulting a specific environment variable first.
    ///
    /// PARAMETERS:
    /// - `subdir` (`AsRef<Path>`): Subdirectory used with `app-path` resolution.
    /// - `env_override` (&str): Environment variable name to check for a base directory.
    ///
    /// RETURNS:
    /// - `Result<PathBoundary<Marker>>`: New boundary anchored using `app-path` semantics.
    ///
    /// ERRORS:
    /// - `StrictPathError::InvalidRestriction`: If resolution fails or the directory can't be created/validated.
    #[cfg(feature = "app-path")]
    pub fn try_new_app_path_with_env<P: AsRef<std::path::Path>>(
        subdir: P,
        env_override: &str,
    ) -> Result<Self> {
        let subdir_path = subdir.as_ref();
        Self::try_new_app_path(subdir_path, Some(env_override))
    }
}

impl<Marker> AsRef<Path> for PathBoundary<Marker> {
    #[inline]
    fn as_ref(&self) -> &Path {
        // PathHistory implements AsRef<Path>, so forward to it
        self.path.as_ref()
    }
}

impl<Marker> std::fmt::Debug for PathBoundary<Marker> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PathBoundary")
            .field("path", &self.path.as_ref())
            .field("marker", &std::any::type_name::<Marker>())
            .finish()
    }
}

impl<Marker: Default> std::str::FromStr for PathBoundary<Marker> {
    type Err = crate::StrictPathError;

    /// Parse a PathBoundary from a string path for universal ergonomics.
    ///
    /// Creates the directory if it doesn't exist, enabling seamless integration
    /// with any string-parsing context (clap, config files, environment variables, etc.):
    /// ```rust
    /// # use strict_path::PathBoundary;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let temp_dir = tempfile::tempdir()?;
    /// let safe_path = temp_dir.path().join("safe_dir");
    /// let boundary: PathBoundary<()> = safe_path.to_string_lossy().parse()?;
    /// assert!(safe_path.exists());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    fn from_str(path: &str) -> std::result::Result<Self, Self::Err> {
        Self::try_new_create(path)
    }
}
//