Skip to content

A full-featured download manager.

fix(finalize): harden artifact publication across filesystems (#2192)

Dr_rOot7384bbc84f18
diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.md
index 5b600e7a..c9a362a8 100644
--- a/packages/finalize-fs/README.md
+++ b/packages/finalize-fs/README.md
@@ -4,6 +4,46 @@ The sidecar performs handle-relative, identity-checked file publication and
removal. Renames never replace an existing destination. Reparse points and
unsafe path components remain rejected on Windows.
+## Filename sanitization
+
+Download names are authored by remote servers, torrent metadata and users, so
+the host sanitizes the final path component before it reaches any rename or
+copy. The `sanitize_name` sidecar operation exposes the same pure function the
+host mirrors in TypeScript; it never touches the filesystem and is idempotent.
+
+The rule set follows Chromium's `net/base/filename_util.cc`, tightened to one
+domain shared by every platform instead of per-OS masks, because a file
+published on macOS must also survive being copied to a Windows or exFAT volume:
+
+- Replace `< > : " | ? * / \` and C0 controls plus DEL with `_`. `:` covers
+ both the NTFS alternate-data-stream separator and the macOS Finder `:`→`/`
+ display split; `/` and `\` are replaced rather than rejected so a caller
+ cannot smuggle extra directory levels into a final component.
+- Strip trailing dots and spaces, which Win32 silently drops when it later
+ opens the file.
+- Append `_` to the stem of Windows reserved device names (`CON`, `PRN`,
+ `AUX`, `NUL`, `COM1-9`, `LPT1-9`, `CONIN$`, `CONOUT$`, including the
+ superscript `¹²³` one-digit forms), preserving any extension: `CON.txt`
+ becomes `CON_.txt`.
+- Clamp the component to 254 UTF-8 bytes — under the strictest of Unix
+ `NAME_MAX` and the 255 UTF-16-unit Windows per-component limit — truncating
+ the stem on a character boundary while keeping a short extension. The budget
+ deliberately stops one byte short of the 255-byte hard limit: publication
+ may append a conflict suffix (` (1)` or `.N`) after sanitization, and a
+ name clamped to exactly 255 would break `NAME_MAX` the moment that suffix
+ lands. Firefox makes the same call — `kDefaultMaxFileNameLength` is 254 for
+ the same "clamp now, leave room to grow" reason.
+- Fall back to `download` when nothing survives (for example `.`).
+
+Differences from Chromium, recorded deliberately: we sanitize to a single
+cross-platform domain rather than per-OS masks (Chromium varies the illegal
+character set by platform); we do not perform Unicode normalization (NFC/NFD),
+since APFS preserves both forms and normalizing would change identities that
+the journal compares byte-wise; we do not transliterate or strip characters
+beyond the forbidden set, so non-Latin names survive untouched. Only the final
+component is sanitized: directory components are user-created through native
+dialogs and are validated, not rewritten, by the platform open path.
+
## Linux and NFS
Linux NFS mounts can reject `renameat2(RENAME_NOREPLACE)` with `EINVAL` even
@@ -48,6 +88,15 @@ the application's durable transaction and recovery rules.
## Windows and SMB
+Windows rename retries transient sharing conflicts with exponential backoff,
+following surge's `retryRename` precedent: antivirus scanners, search indexers
+and handles lingering after `Close()` returns can hold the artifact or target
+name for a few milliseconds. Only the `ACCESS_DENIED`, `SHARING_VIOLATION` and
+`LOCK_VIOLATION` family retries — five attempts with a 50 ms doubling base
+(50/100/200/400 ms). Every other error, and exhaustion of the schedule, is
+reported immediately; the journal recovery path is unchanged. Unix needs no
+equivalent because its rename does not consult share modes.
+
Windows volumes are checked when opening the actual roots, before the
application records a new finalize journal. The application flushes file data
before publication. Ordinary file FLUSH failures, access failures, full disks,
diff --git a/packages/finalize-fs/src/main.rs b/packages/finalize-fs/src/main.rs
index c33a2ce7..6356b1de 100644
--- a/packages/finalize-fs/src/main.rs
+++ b/packages/finalize-fs/src/main.rs
@@ -4,6 +4,7 @@ mod error;
mod path;
mod platform;
mod protocol;
+mod sanitize;
mod state;
use protocol::{Request, Response, read_frame, write_frame};
diff --git a/packages/finalize-fs/src/platform/unix/copy.rs b/packages/finalize-fs/src/platform/unix/copy.rs
index 8bfa4f73..cd3808f4 100644
--- a/packages/finalize-fs/src/platform/unix/copy.rs
+++ b/packages/finalize-fs/src/platform/unix/copy.rs
@@ -1,10 +1,31 @@
-use super::metadata::{directory_entries, ensure_same_entry, stat_named};
+use super::metadata::{directory_entries, ensure_same_entry, stat_named, stat_opened};
use super::{ArtifactHandle, RootHandle, open_parent};
+use crate::error::native_error;
use crate::path::validate_relative;
use std::ffi::CString;
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
+/// Copy staging is the cross-device fallback, so the staged file should keep
+/// the source's access and modification times instead of advertising the copy
+/// time as the download's own timestamp.
+fn copy_timestamps(source: RawFd, target: RawFd) -> io::Result<()> {
+ let stat = stat_opened(source)?;
+ let times = rustix::fs::Timestamps {
+ last_access: rustix::fs::Timespec {
+ tv_sec: stat.st_atime,
+ tv_nsec: stat.st_atime_nsec,
+ },
+ last_modification: rustix::fs::Timespec {
+ tv_sec: stat.st_mtime,
+ tv_nsec: stat.st_mtime_nsec,
+ },
+ };
+ let target = unsafe { <std::os::fd::BorrowedFd<'_>>::borrow_raw(target) };
+ rustix::fs::futimens(target, &times)
+ .map_err(|error| native_error(error.into(), "futimens(copy_timestamps)", None))
+}
+
fn copy_file_contents(source: RawFd, target: RawFd) -> io::Result<()> {
if unsafe { libc::lseek(source, 0, libc::SEEK_SET) } < 0 {
return Err(io::Error::last_os_error());
@@ -47,6 +68,7 @@ fn copy_file_contents(source: RawFd, target: RawFd) -> io::Result<()> {
written += count as usize;
}
}
+ copy_timestamps(source, target)?;
if unsafe { libc::fsync(target) } < 0 {
return Err(io::Error::last_os_error());
}
@@ -124,6 +146,9 @@ fn copy_directory_contents(source: RawFd, target: RawFd) -> io::Result<()> {
));
}
}
+ // Directory timestamps change with every child creation, so they are
+ // restored only after the whole subtree has been staged.
+ copy_timestamps(source, target)?;
if unsafe { libc::fsync(target) } < 0 {
return Err(io::Error::last_os_error());
}
diff --git a/packages/finalize-fs/src/platform/unix/rename.rs b/packages/finalize-fs/src/platform/unix/rename.rs
index 28a131da..8a18deed 100644
--- a/packages/finalize-fs/src/platform/unix/rename.rs
+++ b/packages/finalize-fs/src/platform/unix/rename.rs
@@ -84,6 +84,12 @@ pub(crate) fn rename_no_replace(
rustix::fs::RenameFlags::NOREPLACE,
)
.map_err(|error| crate::error::native_error(error.into(), "renameat_with(NOREPLACE)", None))?;
+ // Keep the held-handle variant's durability contract: both mutated
+ // directories are flushed before the operation reports success.
+ rustix::fs::fsync(&target_parent)
+ .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_target_parent)", None))?;
+ rustix::fs::fsync(&source_parent)
+ .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_source_parent)", None))?;
Ok(())
}
diff --git a/packages/finalize-fs/src/platform/unix/tests.rs b/packages/finalize-fs/src/platform/unix/tests.rs
index b6369dba..2c458655 100644
--- a/packages/finalize-fs/src/platform/unix/tests.rs
+++ b/packages/finalize-fs/src/platform/unix/tests.rs
@@ -5,6 +5,55 @@ use super::{rename_no_replace, rename_opened_no_replace};
#[cfg(target_os = "macos")]
use std::io;
+#[test]
+fn copy_staging_preserves_source_timestamps() {
+ let base = std::env::temp_dir().join(format!(
+ "motrix-finalize-fs-copy-times-{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir_all(&base);
+ std::fs::create_dir_all(&base).unwrap();
+ let base = base.canonicalize().unwrap();
+ std::fs::write(base.join("source"), b"payload").unwrap();
+ std::fs::create_dir_all(base.join("tree/nested")).unwrap();
+ std::fs::write(base.join("tree/nested/leaf"), b"leaf").unwrap();
+ let past = std::time::SystemTime::now() - std::time::Duration::from_secs(86_400);
+ for path in [
+ base.join("source"),
+ base.join("tree"),
+ base.join("tree/nested"),
+ ] {
+ let handle = std::fs::File::options()
+ .write(true)
+ .open(&path)
+ .unwrap_or_else(|_| std::fs::OpenOptions::new().read(true).open(&path).unwrap());
+ handle
+ .set_times(std::fs::FileTimes::new().set_modified(past))
+ .unwrap();
+ }
+
+ let root = open_root(base.to_str().unwrap()).unwrap();
+ let file = open_artifact(&root, "source").unwrap();
+ super::copy_opened(&file, &root, "staged-file").unwrap();
+ let tree = open_artifact(&root, "tree").unwrap();
+ super::copy_opened(&tree, &root, "staged-tree").unwrap();
+
+ for path in [
+ base.join("staged-file"),
+ base.join("staged-tree"),
+ base.join("staged-tree/nested"),
+ ] {
+ let modified = std::fs::metadata(&path).unwrap().modified().unwrap();
+ assert_eq!(
+ modified,
+ past,
+ "copy staging must preserve the source mtime for {}",
+ path.display()
+ );
+ }
+ let _ = std::fs::remove_dir_all(&base);
+}
+
#[test]
fn held_file_digest_uses_sha256() {
let mut hash = Sha256State::new();
diff --git a/packages/finalize-fs/src/platform/windows/copy.rs b/packages/finalize-fs/src/platform/windows/copy.rs
index 25474249..30cd1ee2 100644
--- a/packages/finalize-fs/src/platform/windows/copy.rs
+++ b/packages/finalize-fs/src/platform/windows/copy.rs
@@ -47,6 +47,9 @@ fn materialize(
"Windows copied artifact does not match its held source",
));
}
+ // Directory timestamps change with every child creation, so they are
+ // restored only after the whole subtree has been staged.
+ super::nt::copy_basic_times(source, &target)?;
if expected.is_directory() {
super::nt::flush_directory(&target).map(|_| ())
} else {
diff --git a/packages/finalize-fs/src/platform/windows/mod.rs b/packages/finalize-fs/src/platform/windows/mod.rs
index 83358170..b9440202 100644
--- a/packages/finalize-fs/src/platform/windows/mod.rs
+++ b/packages/finalize-fs/src/platform/windows/mod.rs
@@ -112,9 +112,15 @@ pub(crate) fn rename_opened_no_replace(
ensure_named_entry(&artifact.handle, &artifact.parent, &artifact.name)?;
let parts = validate_relative(target_relative)?;
let (target_parent, target_name) = open_parent(&target.handle, &parts)?;
- nt::rename_no_replace(&artifact.handle, &target_parent, &target_name)?;
+ nt::rename_no_replace_with_retry(&artifact.handle, &target_parent, &target_name)?;
ensure_named_entry(&artifact.handle, &target_parent, &target_name)?;
assert_name_absent(&artifact.parent, &artifact.name)?;
+ // Match the Unix durability contract: flush both mutated directories
+ // before reporting success, instead of depending on the host to flush
+ // after the sidecar could have crashed. flush_directory keeps the SMB
+ // remote-acknowledgement policy for directory flushes.
+ nt::flush_directory(&target_parent).map(|_| ())?;
+ nt::flush_directory(&artifact.parent).map(|_| ())?;
Ok(())
}
diff --git a/packages/finalize-fs/src/platform/windows/nt.rs b/packages/finalize-fs/src/platform/windows/nt.rs
index ffe5d22f..c57c83a7 100644
--- a/packages/finalize-fs/src/platform/windows/nt.rs
+++ b/packages/finalize-fs/src/platform/windows/nt.rs
@@ -1,7 +1,8 @@
//! Thin, checked wrappers around the Windows native handle APIs we need.
use super::super::windows_policy::{
- is_online_smb2, remote_directory_acknowledged, unsupported_information,
+ is_online_smb2, is_transient_rename_conflict, remote_directory_acknowledged,
+ rename_retry_delay_ms, unsupported_information,
};
use crate::error::{native_error, os_code};
use std::ffi::{OsStr, c_void};
@@ -10,6 +11,7 @@ use std::mem::size_of;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::Path;
+use std::time::Duration;
use windows_sys::Wdk::Foundation::OBJECT_ATTRIBUTES;
use windows_sys::Wdk::Storage::FileSystem::{
FILE_CREATE, FILE_DIRECTORY_FILE, FILE_DISPOSITION_DELETE,
@@ -26,11 +28,12 @@ use windows_sys::Win32::Foundation::{
};
use windows_sys::Win32::Storage::FileSystem::{
CreateFileW, DELETE, FILE_ACCESS_RIGHTS, FILE_APPEND_DATA, FILE_ATTRIBUTE_NORMAL,
- FILE_CASE_SENSITIVE_INFO, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
- FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_READ_DATA, FILE_REMOTE_PROTOCOL_INFO,
- FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE, FILE_WRITE_ATTRIBUTES,
- FILE_WRITE_DATA, FileCaseSensitiveInfo, FileRemoteProtocolInfo, GetFileInformationByHandleEx,
- OPEN_EXISTING, SYNCHRONIZE,
+ FILE_BASIC_INFO, FILE_CASE_SENSITIVE_INFO, FILE_FLAG_BACKUP_SEMANTICS,
+ FILE_FLAG_OPEN_REPARSE_POINT, FILE_LIST_DIRECTORY, FILE_READ_ATTRIBUTES, FILE_READ_DATA,
+ FILE_REMOTE_PROTOCOL_INFO, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE,
+ FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, FileBasicInfo, FileCaseSensitiveInfo,
+ FileRemoteProtocolInfo, GetFileInformationByHandleEx, OPEN_EXISTING, SYNCHRONIZE,
+ SetFileInformationByHandle,
};
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
@@ -354,6 +357,37 @@ pub(super) fn rename_no_replace(
)
}
+/// Rename with surge-style exponential backoff. Antivirus scanners, search
+/// indexers and handles lingering after `Close()` returns can hold the
+/// artifact or target name with a sharing violation for a few milliseconds;
+/// only that error family (`ACCESS_DENIED`, `SHARING_VIOLATION`,
+/// `LOCK_VIOLATION`) is retried, five attempts with a 50 ms doubling base.
+/// Every other error — and exhaustion of the schedule — is reported
+/// immediately, so the host journal recovery path is unchanged.
+pub(super) fn rename_no_replace_with_retry(
+ artifact: &OwnedHandle,
+ target_parent: &OwnedHandle,
+ target_name: &[u16],
+) -> io::Result<()> {
+ let mut attempt = 0_usize;
+ loop {
+ let error = match rename_no_replace(artifact, target_parent, target_name) {
+ Ok(()) => return Ok(()),
+ Err(error) => error,
+ };
+ let delay = is_transient_rename_conflict(os_code(&error))
+ .then(|| rename_retry_delay_ms(attempt))
+ .flatten();
+ match delay {
+ Some(delay) => {
+ std::thread::sleep(Duration::from_millis(delay));
+ attempt += 1;
+ }
+ None => return Err(error),
+ }
+ }
+}
+
pub(super) fn mark_delete(artifact: &OwnedHandle) -> io::Result<()> {
let disposition = FILE_DISPOSITION_INFORMATION_EX {
Flags: FILE_DISPOSITION_DELETE
@@ -391,6 +425,47 @@ pub(super) fn flush(handle: &OwnedHandle) -> io::Result<()> {
check_status(status, "NtFlushBuffersFile")
}
+/// Copy staging is the cross-device fallback, so the staged file keeps the
+/// source's creation, access and modification times instead of advertising
+/// the copy time as the download's own timestamp.
+pub(super) fn copy_basic_times(source: &OwnedHandle, target: &OwnedHandle) -> io::Result<()> {
+ let mut basic = FILE_BASIC_INFO::default();
+ let result = unsafe {
+ GetFileInformationByHandleEx(
+ source.as_raw_handle(),
+ FileBasicInfo,
+ (&mut basic as *mut FILE_BASIC_INFO).cast(),
+ u32::try_from(size_of::<FILE_BASIC_INFO>()).expect("FILE_BASIC_INFO size"),
+ )
+ };
+ if result == 0 {
+ return Err(native_error(
+ io::Error::last_os_error(),
+ "GetFileInformationByHandleEx(FileBasicInfo)",
+ None,
+ ));
+ }
+ // ChangeTime cannot be set and zero fields are left unchanged.
+ basic.ChangeTime = 0;
+ basic.FileAttributes = 0;
+ let result = unsafe {
+ SetFileInformationByHandle(
+ target.as_raw_handle(),
+ FileBasicInfo,
+ (&basic as *const FILE_BASIC_INFO).cast(),
+ u32::try_from(size_of::<FILE_BASIC_INFO>()).expect("FILE_BASIC_INFO size"),
+ )
+ };
+ if result == 0 {
+ return Err(native_error(
+ io::Error::last_os_error(),
+ "SetFileInformationByHandle(FileBasicInfo)",
+ None,
+ ));
+ }
+ Ok(())
+}
+
/// Some SMB object stores reject directory FLUSH even though namespace changes
/// have been acknowledged. Only that precise capability failure uses the remote
/// acknowledgement contract; file flush, access and transport failures still fail.
diff --git a/packages/finalize-fs/src/platform/windows_policy.rs b/packages/finalize-fs/src/platform/windows_policy.rs
index 826d3ac3..ff7cb9c7 100644
--- a/packages/finalize-fs/src/platform/windows_policy.rs
+++ b/packages/finalize-fs/src/platform/windows_policy.rs
@@ -16,6 +16,29 @@ pub(super) fn is_online_smb2(protocol: u32, major: u16, flags: u32) -> bool {
protocol == 0x0002_0000 && major >= 2 && flags & 0x2 == 0
}
+/// Rename errors that are transient in practice: antivirus scanners, search
+/// indexers and recently closed handles hold the artifact or target name for a
+/// few milliseconds. ACCESS_DENIED (5), SHARING_VIOLATION (32) and
+/// LOCK_VIOLATION (33) only — real permission settings, invalid paths,
+/// missing parents and cross-device moves are reported immediately.
+pub(super) fn is_transient_rename_conflict(code: Option<i32>) -> bool {
+ matches!(code, Some(5 | 32 | 33))
+}
+
+/// Exponential backoff between rename attempts, following surge's
+/// `retryRename` (5 attempts, 50 ms base doubling). `attempt` is the zero-based
+/// index of the attempt that just failed; `None` means the fifth attempt was
+/// the last and the error must be reported to the journal recovery path.
+pub(super) fn rename_retry_delay_ms(attempt: usize) -> Option<u64> {
+ match attempt {
+ 0 => Some(50),
+ 1 => Some(100),
+ 2 => Some(200),
+ 3 => Some(400),
+ _ => None,
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -51,4 +74,41 @@ mod tests {
}
assert!(!unsupported_information(None));
}
+
+ #[test]
+ fn only_the_sharing_conflict_family_retries_windows_rename() {
+ for code in [5, 32, 33] {
+ assert!(is_transient_rename_conflict(Some(code)));
+ }
+ // FILE_NOT_FOUND, PATH_NOT_FOUND, NOT_SAME_DEVICE, INVALID_PARAMETER,
+ // DISK_FULL, ALREADY_EXISTS report immediately.
+ for code in [2, 3, 17, 87, 112, 183] {
+ assert!(!is_transient_rename_conflict(Some(code)));
+ }
+ assert!(!is_transient_rename_conflict(None));
+ }
+
+ #[test]
+ fn rename_backoff_follows_the_surge_retryrename_schedule() {
+ // Five attempts total, so four doubling waits of 50 ms base between
+ // them; the fifth failure is final and returns the error instead of
+ // sleeping again.
+ let schedule: &[(usize, Option<u64>)] = &[
+ (0, Some(50)),
+ (1, Some(100)),
+ (2, Some(200)),
+ (3, Some(400)),
+ (4, None),
+ (usize::MAX, None),
+ ];
+ for (attempt, expected) in schedule {
+ assert_eq!(rename_retry_delay_ms(*attempt), *expected);
+ }
+ // Attempt exhaustion is independent of the error code: even a retryable
+ // code stops after the fifth failure.
+ for attempt in 4..=9 {
+ assert!(is_transient_rename_conflict(Some(32)));
+ assert_eq!(rename_retry_delay_ms(attempt), None);
+ }
+ }
}
diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rs
index b31bd928..705aa93e 100644
--- a/packages/finalize-fs/src/protocol.rs
+++ b/packages/finalize-fs/src/protocol.rs
@@ -9,6 +9,10 @@ const MAX_FRAME_BYTES: usize = 64 * 1024;
#[serde(tag = "op", rename_all = "snake_case")]
pub(crate) enum Request {
Capabilities,
+ SanitizeName {
+ request_id: u64,
+ name: String,
+ },
OpenRoot {
request_id: u64,
path: String,
@@ -81,6 +85,7 @@ impl Request {
pub(crate) fn operation(&self) -> &'static str {
match self {
Self::Capabilities => "capabilities",
+ Self::SanitizeName { .. } => "sanitize_name",
Self::OpenRoot { .. } => "open_root",
Self::OpenArtifact { .. } => "open_artifact",
Self::RenameOpenedNoReplace { .. } => "rename_opened_no_replace",
@@ -109,6 +114,8 @@ pub(crate) struct Response<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) platform: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
+ pub(crate) sanitized_name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
pub(crate) rename_no_replace: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) held_roots: Option<bool>,
@@ -135,6 +142,7 @@ impl<'a> Response<'a> {
code: None,
message: None,
platform: None,
+ sanitized_name: None,
rename_no_replace: None,
held_roots: None,
directory_sync: None,
diff --git a/packages/finalize-fs/src/sanitize.rs b/packages/finalize-fs/src/sanitize.rs
new file mode 100644
index 00000000..138e32f9
--- /dev/null
+++ b/packages/finalize-fs/src/sanitize.rs
@@ -0,0 +1,247 @@
+//! Cross-platform filename sanitization for published artifacts.
+//!
+//! Download names are authored anywhere — HTTP `Content-Disposition`,
+//! BitTorrent metadata, magnet links or user edits — and only have to be
+//! representable on the origin system. The published file, however, must be
+//! usable on every filesystem Motrix supports, including ones the user copies
+//! it to later. This module maps any candidate final path component onto a
+//! name that is simultaneously valid on Windows (reserved device names,
+//! forbidden characters, trailing dots and spaces, per-component limits),
+//! macOS (where `:` is legal but Finder renders it as `/`) and Unix
+//! (`NAME_MAX`).
+//!
+//! The character and reserved-name rules follow Chromium's
+//! `net/base/filename_util.cc`, tightened to one shared domain instead of
+//! per-OS masks. Differences from Chromium are recorded in the package
+//! README. Sanitization is idempotent and never inspects the filesystem.
+
+/// UTF-8 byte budget that stays under Unix `NAME_MAX` (255 bytes) and the
+/// Windows per-component limit (255 UTF-16 code units, which always covers
+/// fewer bytes than the UTF-8 encoding of the same text). The budget is one
+/// byte short of the hard limit so a published name can still grow a conflict
+/// suffix — ` (1)` or `.N` — without breaking `NAME_MAX`; Firefox's
+/// `kDefaultMaxFileNameLength` keeps the same 254-byte margin.
+const MAX_COMPONENT_BYTES: usize = 254;
+/// Extensions longer than this are treated as payload, not worth preserving.
+const MAX_EXTENSION_BYTES: usize = 24;
+/// Result when every character of the input is stripped (for example `.`).
+const FALLBACK_NAME: &str = "download";
+const REPLACEMENT: char = '_';
+
+pub(crate) fn sanitize_filename(component: &str) -> String {
+ // 1. Replace characters that are illegal or ambiguous on any supported
+ // platform. `/` and `\` are replaced rather than rejected so a caller
+ // that passes a slash-bearing name cannot smuggle in directory levels.
+ let replaced: String = component
+ .chars()
+ .map(|character| {
+ if is_forbidden_character(character) {
+ REPLACEMENT
+ } else {
+ character
+ }
+ })
+ .collect();
+ // 2. Strip trailing dots and spaces, which Windows drops silently: a
+ // name published as `file.` would otherwise round-trip as `file`.
+ let trimmed = replaced.trim_end_matches(['.', ' ']);
+ // 3. Windows reserves whole device names including `CON.txt` forms; the
+ // stem keeps its extension but gains an underscore suffix.
+ let dereserved = dereserve_name(trimmed);
+ // 4. Clamp the component length, keeping a short extension when present.
+ let clamped = clamp_component(&dereserved);
+ if clamped.is_empty() {
+ FALLBACK_NAME.to_string()
+ } else {
+ clamped
+ }
+}
+
+fn is_forbidden_character(character: char) -> bool {
+ matches!(
+ character,
+ '\0'..='\u{1f}' | '\u{7f}' | '<' | '>' | '"' | '|' | '?' | '*' | '/' | '\\' | ':'
+ )
+}
+
+fn dereserve_name(name: &str) -> String {
+ let stem_end = name.find('.').unwrap_or(name.len());
+ let (stem, rest) = name.split_at(stem_end);
+ if is_reserved_stem(stem) {
+ format!("{stem}_{rest}")
+ } else {
+ name.to_string()
+ }
+}
+
+fn is_reserved_stem(stem: &str) -> bool {
+ let upper = stem.to_uppercase();
+ if matches!(
+ upper.as_str(),
+ "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
+ ) {
+ return true;
+ }
+ let Some(suffix) = upper
+ .strip_prefix("COM")
+ .or_else(|| upper.strip_prefix("LPT"))
+ else {
+ return false;
+ };
+ matches!(
+ suffix,
+ "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
+ )
+}
+
+fn clamp_component(name: &str) -> String {
+ if name.len() <= MAX_COMPONENT_BYTES {
+ return name.to_string();
+ }
+ if let Some(dot) = name.rfind('.')
+ && dot > 0
+ {
+ let extension_bytes = name.len() - dot - 1;
+ if extension_bytes > 0 && extension_bytes <= MAX_EXTENSION_BYTES {
+ let stem_budget = MAX_COMPONENT_BYTES - extension_bytes - 1;
+ let stem = truncate_utf8(&name[..dot], stem_budget);
+ // Truncation can expose a fresh trailing dot or space.
+ let stem = stem.trim_end_matches(['.', ' ']);
+ let extension = &name[dot + 1..];
+ return format!("{stem}.{extension}");
+ }
+ }
+ truncate_utf8(name, MAX_COMPONENT_BYTES)
+ .trim_end_matches(['.', ' '])
+ .to_string()
+}
+
+fn truncate_utf8(value: &str, max_bytes: usize) -> &str {
+ if value.len() <= max_bytes {
+ return value;
+ }
+ let mut end = max_bytes;
+ while end > 0 && !value.is_char_boundary(end) {
+ end -= 1;
+ }
+ &value[..end]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{MAX_COMPONENT_BYTES, sanitize_filename};
+
+ // The same matrix is mirrored by the host-side
+ // `sanitizeFinalizeFilename` tests; keep both tables in sync.
+ #[test]
+ fn sanitizes_the_cross_platform_filename_matrix() {
+ let cases: &[(&str, &str)] = &[
+ ("normal.zip", "normal.zip"),
+ ("资料.tar.gz", "资料.tar.gz"),
+ ("movie🎬.mp4", "movie🎬.mp4"),
+ ("file<name>.mp4", "file_name_.mp4"),
+ ("a:b.txt", "a_b.txt"),
+ ("say \"hi\"?", "say _hi__"),
+ ("star*|dot>", "star__dot_"),
+ ("path/injection.txt", "path_injection.txt"),
+ ("win\\dows.txt", "win_dows.txt"),
+ ("CON", "CON_"),
+ ("con.txt", "con_.txt"),
+ ("Com5", "Com5_"),
+ ("LPT9.tar.gz", "LPT9_.tar.gz"),
+ ("COM¹.log", "COM¹_.log"),
+ ("lpt².dat", "lpt²_.dat"),
+ ("aux", "aux_"),
+ ("nul.image.iso", "nul_.image.iso"),
+ ("conin$.txt", "conin$_.txt"),
+ ("CONOUT$.log", "CONOUT$_.log"),
+ ("trailing. ", "trailing"),
+ ("trailing... ", "trailing"),
+ ("trailing.", "trailing"),
+ ("spaces .txt", "spaces .txt"),
+ (".hidden", ".hidden"),
+ (".", "download"),
+ ("..", "download"),
+ ("", "download"),
+ (" ", "download"),
+ ("???", "___"),
+ ("control\tchar\n", "control_char_"),
+ ("console\u{7f}.log", "console_.log"),
+ ("CON. ", "CON_"),
+ ("degree°name", "degree°name"),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(sanitize_filename(input), *expected, "input {input:?}");
+ }
+ }
+
+ #[test]
+ fn sanitization_is_idempotent() {
+ for input in ["CON", "file.", "a/b\\c:d", "spaces . ", "name<?>.txt", ""] {
+ let once = sanitize_filename(input);
+ assert_eq!(sanitize_filename(&once), once, "input {input:?}");
+ }
+ }
+
+ #[test]
+ fn long_components_are_clamped_on_character_boundaries() {
+ let long_stem = "a".repeat(300);
+ let clamped = sanitize_filename(&long_stem);
+ assert_eq!(clamped.len(), MAX_COMPONENT_BYTES);
+ assert!(clamped.chars().all(|character| character == 'a'));
+
+ let named = format!("{}.zip", "字".repeat(100));
+ let clamped = sanitize_filename(&named);
+ assert!(clamped.len() <= MAX_COMPONENT_BYTES, "{}", clamped.len());
+ assert!(clamped.ends_with(".zip"), "{clamped}");
+ assert!(clamped.trim_end_matches('字').ends_with(".zip"));
+ // 83 CJK characters (249 bytes) + ".zip" fits in 254 bytes; the
+ // 84th character would exceed the budget.
+ assert_eq!(clamped, format!("{}.zip", "字".repeat(83)));
+
+ // A giant "extension" is payload: clamp the whole name instead.
+ let giant_extension = format!("{}.{}", "d".repeat(300), "x".repeat(200));
+ let clamped = sanitize_filename(&giant_extension);
+ assert_eq!(clamped.len(), MAX_COMPONENT_BYTES);
+
+ // Truncation landing on a trailing dot or space strips it.
+ let dotted = format!("{}.", "b".repeat(300));
+ let clamped = sanitize_filename(&dotted);
+ assert_eq!(clamped.len(), MAX_COMPONENT_BYTES);
+ assert!(!clamped.ends_with('.'));
+ }
+
+ #[test]
+ fn components_at_the_byte_budget_boundary_are_clamped_exactly() {
+ // 253 and 254 bytes are at or under the budget and survive untouched;
+ // 255 bytes is one over and clamps to exactly 254, leaving room for a
+ // conflict suffix (` (1)`, `.N`) that publication may append later.
+ for bytes in [253, 254] {
+ let name = "a".repeat(bytes);
+ assert_eq!(sanitize_filename(&name), name);
+ }
+ assert_eq!(sanitize_filename(&"a".repeat(255)), "a".repeat(254));
+
+ // With a kept extension the stem absorbs the clamp: a 251-byte stem
+ // plus ".zip" totals 255, so the stem drops exactly one byte.
+ let kept = sanitize_filename(&format!("{}.zip", "a".repeat(251)));
+ assert_eq!(kept, format!("{}.zip", "a".repeat(250)));
+ assert_eq!(kept.len(), MAX_COMPONENT_BYTES);
+ }
+
+ #[test]
+ fn sanitized_names_always_pass_the_windows_component_contract() {
+ for input in ["CON", "x".repeat(300).as_str(), "a:b", "tail. "] {
+ let sanitized = sanitize_filename(input);
+ assert!(!sanitized.is_empty());
+ assert!(!sanitized.ends_with([' ', '.']), "{sanitized:?}");
+ assert!(
+ !sanitized.chars().any(super::is_forbidden_character),
+ "{sanitized:?}"
+ );
+ let stem = sanitized.split('.').next().unwrap_or_default();
+ assert!(!super::is_reserved_stem(stem), "{sanitized:?}");
+ assert!(sanitized.len() <= super::MAX_COMPONENT_BYTES);
+ }
+ }
+}
diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rs
index 80e0f7a2..f1ca72ff 100644
--- a/packages/finalize-fs/src/state.rs
+++ b/packages/finalize-fs/src/state.rs
@@ -32,6 +32,11 @@ impl State {
fn dispatch(&mut self, request: Request) -> Response<'static> {
match request {
Request::Capabilities => self.capabilities(),
+ Request::SanitizeName { request_id, name } => {
+ let mut response = Response::ok(Some(request_id));
+ response.sanitized_name = Some(crate::sanitize::sanitize_filename(&name));
+ response
+ }
Request::OpenRoot {
request_id,
path,
@@ -342,4 +347,13 @@ mod tests {
assert_eq!(response.directory_sync, Some(true));
}
}
+
+ #[test]
+ fn sanitize_name_maps_any_candidate_onto_the_shared_domain() {
+ let response = State::new().handle(Request::SanitizeName {
+ request_id: 3,
+ name: "CON.txt ".to_string(),
+ });
+ assert_eq!(response.sanitized_name.as_deref(), Some("CON_.txt"));
+ }
}
diff --git a/src/core/fs/finalize-path.test.ts b/src/core/fs/finalize-path.test.ts
index df8ea9ba..23d166de 100644
--- a/src/core/fs/finalize-path.test.ts
+++ b/src/core/fs/finalize-path.test.ts
@@ -1,6 +1,10 @@
import path from 'node:path'
import { describe, expect, it } from 'vitest'
-import { resolveFinalizeTarget } from './finalize-path'
+import {
+ resolveFinalizeTarget,
+ sanitizeFinalizeFilename,
+ sanitizeFinalizePath,
+} from './finalize-path'
describe('resolveFinalizeTarget', () => {
it.each([
@@ -43,3 +47,104 @@ describe('resolveFinalizeTarget', () => {
)
})
})
+
+describe('sanitizeFinalizeFilename', () => {
+ // Mirrors the sidecar matrix in packages/finalize-fs/src/sanitize.rs;
+ // keep both tables in sync.
+ it.each([
+ ['normal.zip', 'normal.zip'],
+ ['资料.tar.gz', '资料.tar.gz'],
+ ['movie🎬.mp4', 'movie🎬.mp4'],
+ ['file<name>.mp4', 'file_name_.mp4'],
+ ['a:b.txt', 'a_b.txt'],
+ ['say "hi"?', 'say _hi__'],
+ ['star*|dot>', 'star__dot_'],
+ ['path/injection.txt', 'path_injection.txt'],
+ ['win\\dows.txt', 'win_dows.txt'],
+ ['CON', 'CON_'],
+ ['con.txt', 'con_.txt'],
+ ['Com5', 'Com5_'],
+ ['LPT9.tar.gz', 'LPT9_.tar.gz'],
+ ['COM¹.log', 'COM¹_.log'],
+ ['lpt².dat', 'lpt²_.dat'],
+ ['aux', 'aux_'],
+ ['nul.image.iso', 'nul_.image.iso'],
+ ['conin$.txt', 'conin$_.txt'],
+ ['CONOUT$.log', 'CONOUT$_.log'],
+ ['trailing. ', 'trailing'],
+ ['trailing... ', 'trailing'],
+ ['trailing.', 'trailing'],
+ ['spaces .txt', 'spaces .txt'],
+ ['.hidden', '.hidden'],
+ ['.', 'download'],
+ ['..', 'download'],
+ ['', 'download'],
+ [' ', 'download'],
+ ['???', '___'],
+ ['control\tchar\n', 'control_char_'],
+ ['console\u{7f}.log', 'console_.log'],
+ ['CON. ', 'CON_'],
+ ['degree°name', 'degree°name'],
+ ])('sanitizes %j', (input, expected) => {
+ expect(sanitizeFinalizeFilename(input)).toBe(expected)
+ })
+
+ it.each(['CON', 'file.', 'a/b\\c:d', 'spaces . ', 'name<?>.txt', ''])(
+ 'is idempotent for %j',
+ (input) => {
+ const once = sanitizeFinalizeFilename(input)
+ expect(sanitizeFinalizeFilename(once)).toBe(once)
+ }
+ )
+
+ it('clamps long components on character boundaries while keeping extensions', () => {
+ expect(Buffer.byteLength(sanitizeFinalizeFilename('a'.repeat(300)))).toBe(
+ 254
+ )
+ expect(sanitizeFinalizeFilename(`${'字'.repeat(100)}.zip`)).toBe(
+ `${'字'.repeat(83)}.zip`
+ )
+ expect(
+ Buffer.byteLength(
+ sanitizeFinalizeFilename(`${'d'.repeat(300)}.${'x'.repeat(200)}`)
+ )
+ ).toBe(254)
+ expect(sanitizeFinalizeFilename(`${'b'.repeat(300)}.`)).not.toMatch(
+ /[. ]$/u
+ )
+ })
+
+ it('clamps components at the byte budget boundary exactly', () => {
+ // 253 and 254 bytes are at or under the budget and survive untouched;
+ // 255 bytes is one over and clamps to exactly 254, leaving room for a
+ // conflict suffix (` (1)`, `.N`) that publication may append later.
+ for (const bytes of [253, 254]) {
+ expect(sanitizeFinalizeFilename('a'.repeat(bytes))).toBe(
+ 'a'.repeat(bytes)
+ )
+ }
+ expect(sanitizeFinalizeFilename('a'.repeat(255))).toBe('a'.repeat(254))
+
+ // With a kept extension the stem absorbs the clamp: a 251-byte stem plus
+ // ".zip" totals 255, so the stem drops exactly one byte.
+ expect(sanitizeFinalizeFilename(`${'a'.repeat(251)}.zip`)).toBe(
+ `${'a'.repeat(250)}.zip`
+ )
+ })
+})
+
+describe('sanitizeFinalizePath', () => {
+ it.each([
+ ['/downloads/normal.zip', '/downloads/normal.zip'],
+ ['/downloads/CON.txt ', '/downloads/CON_.txt'],
+ ['/downloads/nested/bad:name.bin', '/downloads/nested/bad_name.bin'],
+ ])('sanitizes only the final component of %s', (input, expected) => {
+ expect(sanitizeFinalizePath(input, path.posix)).toBe(expected)
+ })
+
+ it('keeps Windows drive and directory components untouched', () => {
+ expect(sanitizeFinalizePath('C:\\Downloads<Sub>\\CON', path.win32)).toBe(
+ 'C:\\Downloads<Sub>\\CON_'
+ )
+ })
+})
diff --git a/src/core/fs/finalize-path.ts b/src/core/fs/finalize-path.ts
index 9f716029..dc6e3786 100644
--- a/src/core/fs/finalize-path.ts
+++ b/src/core/fs/finalize-path.ts
@@ -1,3 +1,4 @@
+import { Buffer } from 'node:buffer'
import path from 'node:path'
/** Resolve plugin-relative targets and apply the same boundary at commit time. */
@@ -34,3 +35,104 @@ export function resolveFinalizeTarget(
}
return target
}
+
+/**
+ * Byte budget that stays under Unix NAME_MAX (255 bytes) and the Windows
+ * per-component limit (255 UTF-16 units, always fewer than the UTF-8 bytes).
+ * One byte short of the hard limit so the published name can still grow a
+ * conflict suffix (` (1)`, `.N`) without breaking NAME_MAX; Firefox's
+ * kDefaultMaxFileNameLength keeps the same 254-byte margin.
+ */
+const MAX_COMPONENT_BYTES = 254
+/** Extensions longer than this are payload, not worth preserving. */
+const MAX_EXTENSION_BYTES = 24
+/** Result when every character of the input is stripped (for example `.`). */
+const FALLBACK_NAME = 'download'
+const REPLACEMENT = '_'
+
+/**
+ * Map a downloaded final-name candidate onto the one domain that is valid on
+ * every filesystem Motrix publishes to, including Windows volumes the user
+ * later copies the file to. Mirrors the sidecar's `sanitize_name` rule set
+ * (Chromium filename_util tightened to a shared cross-platform domain; see
+ * packages/finalize-fs/README.md). Idempotent, filesystem-free, and only ever
+ * applied to the final path component — directories are validated, not
+ * rewritten.
+ */
+export function sanitizeFinalizeFilename(component: string): string {
+ const replaced = Array.from(component, (character) =>
+ isForbiddenFilenameCharacter(character) ? REPLACEMENT : character
+ ).join('')
+ // Win32 silently drops trailing dots and spaces when reopening the file.
+ const trimmed = replaced.replace(/[. ]+$/u, '')
+ // Windows reserves whole device names including `CON.txt` forms.
+ const dereserved = dereserveFilename(trimmed)
+ const clamped = clampFilenameComponent(dereserved)
+ return clamped === '' ? FALLBACK_NAME : clamped
+}
+
+/** Sanitize only the final component of an absolute target path. */
+export function sanitizeFinalizePath(
+ targetPath: string,
+ paths: typeof path = path
+): string {
+ const name = paths.basename(targetPath)
+ const sanitized = sanitizeFinalizeFilename(name)
+ return sanitized === name
+ ? targetPath
+ : paths.join(paths.dirname(targetPath), sanitized)
+}
+
+function isForbiddenFilenameCharacter(character: string): boolean {
+ const code = character.charCodeAt(0)
+ return (
+ code <= 0x1f ||
+ code === 0x7f ||
+ // `:` covers the NTFS alternate-data-stream separator and the macOS
+ // Finder `:`/`/` display split; `/` and `\` are replaced rather than
+ // rejected so callers cannot smuggle in directory levels.
+ '<>":|?*/\\:'.includes(character)
+ )
+}
+
+function dereserveFilename(name: string): string {
+ const stemEnd = name.indexOf('.')
+ const stem = stemEnd === -1 ? name : name.slice(0, stemEnd)
+ if (!isReservedFilenameStem(stem)) return name
+ const rest = stemEnd === -1 ? '' : name.slice(stemEnd)
+ return `${stem}_${rest}`
+}
+
+function isReservedFilenameStem(stem: string): boolean {
+ const upper = stem.toUpperCase()
+ if (['CON', 'PRN', 'AUX', 'NUL', 'CONIN$', 'CONOUT$'].includes(upper)) {
+ return true
+ }
+ return /^(?:COM|LPT)(?:[1-9]|¹|²|³)$/.test(upper)
+}
+
+function clampFilenameComponent(name: string): string {
+ if (Buffer.byteLength(name) <= MAX_COMPONENT_BYTES) return name
+ const dot = name.lastIndexOf('.')
+ if (dot > 0) {
+ const extension = name.slice(dot + 1)
+ const extensionBytes = Buffer.byteLength(extension)
+ if (extensionBytes > 0 && extensionBytes <= MAX_EXTENSION_BYTES) {
+ const stemBudget = MAX_COMPONENT_BYTES - extensionBytes - 1
+ const stem = truncateUtf8(name.slice(0, dot), stemBudget).replace(
+ /[. ]+$/u,
+ ''
+ )
+ return `${stem}.${extension}`
+ }
+ }
+ return truncateUtf8(name, MAX_COMPONENT_BYTES).replace(/[. ]+$/u, '')
+}
+
+function truncateUtf8(value: string, maxBytes: number): string {
+ let end = value.length
+ while (end > 0 && Buffer.byteLength(value.slice(0, end)) > maxBytes) {
+ end -= 1
+ }
+ return value.slice(0, end)
+}
diff --git a/src/core/plugin/finalize/filesystem-adapter.test.ts b/src/core/plugin/finalize/filesystem-adapter.test.ts
index e844efd5..8b1965dd 100644
--- a/src/core/plugin/finalize/filesystem-adapter.test.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.test.ts
@@ -2,7 +2,39 @@ import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { NativeFinalizeFilesystemAdapter } from './filesystem-adapter'
+import {
+ NativeFinalizeFilesystemAdapter,
+ normalizeSidecarRootPath,
+} from './filesystem-adapter'
+
+describe('normalizeSidecarRootPath', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs()
+ vi.restoreAllMocks()
+ })
+
+ it('strips verbatim namespace prefixes on Windows only', () => {
+ const original = Object.getOwnPropertyDescriptor(process, 'platform')
+ try {
+ Object.defineProperty(process, 'platform', { value: 'win32' })
+ expect(normalizeSidecarRootPath('\\\\?\\C:\\Downloads')).toBe(
+ 'C:\\Downloads'
+ )
+ expect(normalizeSidecarRootPath('\\\\?\\UNC\\server\\share')).toBe(
+ '\\\\server\\share'
+ )
+ expect(normalizeSidecarRootPath('C:\\Downloads')).toBe('C:\\Downloads')
+ expect(normalizeSidecarRootPath('\\\\server\\share')).toBe(
+ '\\\\server\\share'
+ )
+ } finally {
+ if (original) Object.defineProperty(process, 'platform', original)
+ }
+ expect(normalizeSidecarRootPath('\\\\?\\C:\\Downloads')).toBe(
+ process.platform === 'win32' ? 'C:\\Downloads' : '\\\\?\\C:\\Downloads'
+ )
+ })
+})
describe.runIf(process.platform !== 'win32')(
'NativeFinalizeFilesystemAdapter process failures',
diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.ts
index ca6604bf..25e8e14b 100644
--- a/src/core/plugin/finalize/filesystem-adapter.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.ts
@@ -48,6 +48,7 @@ interface WireResponse {
os_error?: number
nt_status?: string
directory_sync_mode?: 'directory_flushed' | 'remote_acknowledged'
+ sanitized_name?: string
platform?: string
rename_no_replace?: boolean
held_roots?: boolean
@@ -75,6 +76,8 @@ export interface FinalizeArtifactHandle {
export interface FinalizeFilesystemAdapter {
capabilities(): Promise<FinalizeFsCapabilities>
+ /** Map a final-name candidate onto the shared cross-platform domain. */
+ sanitizeName?(name: string): Promise<string>
openRoot(
rootPath: string,
expectedIdentity?: string
@@ -277,6 +280,14 @@ export class NativeFinalizeFilesystemAdapter
})
}
+ async sanitizeName(name: string): Promise<string> {
+ const response = await this.request({ op: 'sanitize_name', name })
+ if (response.sanitized_name === undefined) {
+ throw new Error('sidecar omitted sanitized name')
+ }
+ return response.sanitized_name
+ }
+
async openRoot(
rootPath: string,
expectedIdentity?: string
@@ -287,7 +298,7 @@ export class NativeFinalizeFilesystemAdapter
const generation = this.generation
const response = await this.request({
op: 'open_root',
- path: rootPath,
+ path: normalizeSidecarRootPath(rootPath),
expected_identity: expectedIdentity,
})
if (response.handle === undefined)
@@ -497,3 +508,15 @@ export class NativeFinalizeFilesystemAdapter
this.child.kill()
}
}
+
+/**
+ * The sidecar's Windows root walker rejects verbatim `\\?\` namespace paths,
+ * while user-selected and API-derived roots can carry either spelling.
+ * Normalize to the Win32 form before the path crosses the sidecar boundary.
+ */
+export function normalizeSidecarRootPath(rootPath: string): string {
+ if (process.platform !== 'win32') return rootPath
+ return rootPath
+ .replace(/^\\\\\?\\UNC\\/i, '\\\\')
+ .replace(/^\\\\\?\\([a-z]:\\)/i, '$1')
+}
diff --git a/src/core/session/durable-finalize-runtime.test.ts b/src/core/session/durable-finalize-runtime.test.ts
index c1e154d5..e93b8790 100644
--- a/src/core/session/durable-finalize-runtime.test.ts
+++ b/src/core/session/durable-finalize-runtime.test.ts
@@ -138,3 +138,85 @@ it('rejects an invalid target before acquiring leases or reading file identities
db.close()
}
})
+
+it('sanitizes a cross-platform hostile final name before planning', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'motrix-sanitize-'))
+ try {
+ const sourcePath = path.join(root, 'source.part')
+ await writeFile(sourcePath, 'payload')
+ // Windows reserved stem with trailing space: publishable nowhere as-is.
+ const requestedTarget = path.join(root, 'CON.txt ')
+ const sanitizedTarget = path.join(root, 'CON_.txt')
+ const sourceIdentity = await readArtifactIdentity(sourcePath)
+ const moved: string[] = []
+ const db = new Database(':memory:')
+ migrate(db)
+ let rebaseTargetRoot: string | undefined
+ const fs = {
+ identity: async (artifactPath: string) =>
+ artifactPath === sanitizedTarget || artifactPath === sourcePath
+ ? sourceIdentity
+ : null,
+ sameFilesystem: async () => true,
+ materializePrivate: async () => sourceIdentity,
+ moveNoReplace: async (
+ _source: string,
+ _expected: ArtifactIdentity,
+ targetPath: string
+ ) => {
+ moved.push(targetPath)
+ await writeFile(targetPath, 'payload')
+ },
+ makeDurable: async () => undefined,
+ removeKnown: async () => undefined,
+ } satisfies FinalizeArtifactOperations
+ const runtime = new DurableFinalizeRuntime({
+ db,
+ session: {
+ persistFinalizedArtifact: async (_task, _occurrence, input, commit) => {
+ rebaseTargetRoot = input.fileRebase?.targetRoot
+ return commit((mutation) => {
+ db.prepare(
+ `UPDATE plugin_finalize_journals SET phase='db_committed',
+ updated_at=? WHERE plan_id=? AND phase='target_installed'`
+ ).run(mutation.updatedAt, mutation.journalId)
+ })
+ },
+ },
+ fs,
+ })
+
+ const result = await runtime.commit({
+ task: makeDownloadTask({
+ id: 'task-sanitize',
+ name: 'CON.txt ',
+ type: TaskType.Http,
+ kind: TaskKind.Direct,
+ saveDir: root,
+ filename: 'CON.txt ',
+ finalName: 'CON.txt ',
+ diskPath: sourcePath,
+ finalPath: requestedTarget,
+ source: 'user',
+ sourceMeta: null,
+ instances: [],
+ createdAt: 1,
+ updatedAt: 1,
+ }),
+ occurrence: null,
+ sourcePath,
+ targetPath: requestedTarget,
+ metadataOps: [],
+ contributors: [],
+ postDeliveries: [],
+ fileRebase: { sourceRoot: sourcePath, targetRoot: requestedTarget },
+ })
+
+ expect(moved).toEqual([sanitizedTarget])
+ expect(result.targetPath).toBe(sanitizedTarget)
+ expect(rebaseTargetRoot).toBe(sanitizedTarget)
+ db.close()
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+})
diff --git a/src/core/session/durable-finalize-runtime.ts b/src/core/session/durable-finalize-runtime.ts
index 8d63aedf..1616b65c 100644
--- a/src/core/session/durable-finalize-runtime.ts
+++ b/src/core/session/durable-finalize-runtime.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto'
import path from 'node:path'
+import { sanitizeFinalizePath } from '@core/fs/finalize-path'
import { getLogger } from '@core/logger'
import {
ArtifactIdentityError,
@@ -59,13 +60,24 @@ export class DurableFinalizeRuntime {
async commit(
input: DurableFinalizeArtifactInput
): Promise<FinalizeCommitResult> {
+ // The final name can carry characters that Windows or exFAT volumes
+ // cannot reopen. Sanitize the final component once, before validation or
+ // identity capture, so journal, rebase and database all record the name
+ // the filesystem actually received.
+ const targetPath = sanitizeFinalizePath(input.targetPath)
+ if (targetPath !== input.targetPath) {
+ getLogger('finalize').info(
+ {
+ taskId: input.task.id,
+ requested: input.targetPath,
+ sanitized: targetPath,
+ },
+ 'finalize_target_name_sanitized'
+ )
+ }
// Reject invalid output plans before quiescing writers or hashing large files.
try {
- assertFinalizePaths(
- input.task.saveDir,
- input.sourcePath,
- input.targetPath
- )
+ assertFinalizePaths(input.task.saveDir, input.sourcePath, targetPath)
} catch (err) {
getLogger('finalize').warn(
{
@@ -73,7 +85,7 @@ export class DurableFinalizeRuntime {
phase: input.task.transitionPhase,
saveDir: input.task.saveDir,
sourcePath: input.sourcePath,
- targetPath: input.targetPath,
+ targetPath,
err,
},
'finalize_path_validation_failed'
@@ -97,13 +109,20 @@ export class DurableFinalizeRuntime {
taskId: input.task.id,
saveDir: input.task.saveDir,
sourcePath: input.sourcePath,
- targetPath: input.targetPath,
+ targetPath,
sourceIdentity,
replacement,
metadataOps: input.metadataOps,
contributors: input.contributors,
})
+ // Rebase paths must follow the sanitized final component when the
+ // requested target named the same file.
+ const fileRebase =
+ input.fileRebase && input.fileRebase.targetRoot === input.targetPath
+ ? { ...input.fileRebase, targetRoot: targetPath }
+ : input.fileRebase
+
return await this.options.session.persistFinalizedArtifact(
input.task,
input.occurrence,
@@ -111,7 +130,7 @@ export class DurableFinalizeRuntime {
metadataOps: input.metadataOps,
postDeliveries: input.postDeliveries,
beforeCommit: input.beforeCommit,
- fileRebase: input.fileRebase,
+ fileRebase,
},
async (commitDatabase) => {
const repository = new SqliteFinalizeJournalRepository(
diff --git a/src/core/task/actions/finalize-task.test.ts b/src/core/task/actions/finalize-task.test.ts
index 28bd05bb..adf38c6d 100644
--- a/src/core/task/actions/finalize-task.test.ts
+++ b/src/core/task/actions/finalize-task.test.ts
@@ -2030,6 +2030,40 @@ describe('finalizeTask plugin-hook chain (Plan C / T15)', () => {
expect(task.status).toBe(TaskStatus.Completed)
})
+ it('HTTP: a sanitized final name is deduplicated before publication', async () => {
+ // `a:b.txt` sanitizes to `a_b.txt`. That name was never reserved at create
+ // time, so an existing `a_b.txt` must yield `a_b (1).txt` instead of a
+ // no-replace rename failure.
+ const commitFinalizedArtifact = vi.fn(async () => {})
+ const finalNamePicker = { pick: vi.fn(async () => 'a_b (1).txt') }
+ const deps: FinalizeTaskDeps = {
+ ...makeDeps(),
+ orchestrator: makeOrchestrator(makeBeforeFinalizeCommit()),
+ auditLog: makeAuditLog(),
+ commitFinalizedArtifact,
+ finalNamePicker,
+ }
+ const task = makeTask({
+ diskPath: '/d/a:b.txt.motrix',
+ finalPath: '/d/a:b.txt',
+ finalName: 'a:b.txt',
+ })
+ ;(deps.taskManager.getById as ReturnType<typeof vi.fn>).mockReturnValue(
+ task
+ )
+
+ await finalizeTask('t1', deps)
+
+ expect(finalNamePicker.pick).toHaveBeenCalledWith('/d', 'a_b.txt')
+ expect(commitFinalizedArtifact).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sourcePath: '/d/a:b.txt.motrix',
+ targetPath: '/d/a_b (1).txt',
+ task: expect.objectContaining({ finalPath: '/d/a_b (1).txt' }),
+ })
+ )
+ })
+
it('HTTP: durable commit failure preserves the recoverable rename intent', async () => {
const deps: FinalizeTaskDeps = {
...makeDeps(),
diff --git a/src/core/task/actions/finalize-task.ts b/src/core/task/actions/finalize-task.ts
index 5bbf288f..dced1e85 100644
--- a/src/core/task/actions/finalize-task.ts
+++ b/src/core/task/actions/finalize-task.ts
@@ -30,6 +30,8 @@ import {
parseBtFileLayout,
} from '../bt-storage-layout'
import { settleBtUpload } from '../bt-upload-settlement'
+import type { FinalNamePicker } from '../final-name-picker'
+import { resolvePublishedTargetPath } from '../finalize-target-name'
import { fireAfterComplete, fireOnError } from '../hook-dispatch'
import { normalizeTerminalRuntimeMetrics } from '../normalize-terminal-runtime-metrics'
import type { OccurrenceDispatcher } from '../occurrences/occurrence-dispatcher'
@@ -149,6 +151,11 @@ export interface FinalizeTaskDeps {
monotonicNow?: () => number
createEngineTaskId?: () => string
/** Production FS+journal+task transaction. Tests may omit for legacy IO. */
+ /**
+ * Re-deduplicates a final name that sanitization changed. Optional so tests
+ * that never publish an unsafe name can omit it.
+ */
+ finalNamePicker?: Pick<FinalNamePicker, 'pick'>
commitFinalizedArtifact?: (
input: FinalizeArtifactCommitRequest
) => Promise<void>
@@ -272,7 +279,14 @@ async function finalizeHttp(
})
return
}
- const desiredFinalPath = finalizeOutcome.finalFilePath ?? task.finalPath
+ // The final name can arrive from Content-Disposition or plugin hooks with
+ // characters that Windows or exFAT volumes cannot reopen; sanitize only the
+ // final component, and re-deduplicate it, before any rename or durable
+ // commit consumes it.
+ const desiredFinalPath = await resolvePublishedTargetPath(
+ finalizeOutcome.finalFilePath ?? task.finalPath,
+ deps.finalNamePicker
+ )
const renameSource = task.diskPath
if (!deps.commitFinalizedArtifact) {
await persistDesiredFinalPath(task, desiredFinalPath, deps)
@@ -544,8 +558,15 @@ async function finalizeBt(
await finalizeBtInPlace(task, deps, finalizeOutcome, previousStatus)
return
}
+ // Same publication rule as HTTP. DurableFinalizeRuntime would sanitize the
+ // target anyway, but only here does the task row learn the name it lands
+ // under.
+ const publishedFinalPath = await resolvePublishedTargetPath(
+ desiredFinalPath,
+ deps.finalNamePicker
+ )
if (!deps.commitFinalizedArtifact) {
- await persistDesiredFinalPath(task, desiredFinalPath, deps)
+ await persistDesiredFinalPath(task, publishedFinalPath, deps)
}
const storageLayout = getBtStorageLayout(task)
const stagingPayloadPath = getBtPayloadPath(task)
@@ -602,19 +623,19 @@ async function finalizeBt(
if (deps.commitFinalizedArtifact) {
const renamedTask = structuredClone(task)
- applyBtTaskAfterRename(renamedTask, desiredFinalPath)
+ applyBtTaskAfterRename(renamedTask, publishedFinalPath)
try {
await deps.commitFinalizedArtifact({
task: renamedTask,
occurrence: null,
sourcePath: renameSource,
- targetPath: desiredFinalPath,
+ targetPath: publishedFinalPath,
replacement: finalizeOutcome.replacement,
metadataOps: finalizeOutcome.metadataOps,
contributors: finalizeOutcome.contributors,
fileRebase: {
sourceRoot: renameSource,
- targetRoot: desiredFinalPath,
+ targetRoot: publishedFinalPath,
},
})
Object.assign(task, structuredClone(renamedTask))
@@ -633,7 +654,7 @@ async function finalizeBt(
}
} else {
try {
- await deps.fs.renameAtomic(renameSource, desiredFinalPath)
+ await deps.fs.renameAtomic(renameSource, publishedFinalPath)
} catch (e) {
const cause = (e as Error).message
const errorMessage = `Failed to rename directory: ${cause}`
@@ -646,7 +667,7 @@ async function finalizeBt(
throw new AppError(ErrorCode.TaskFinalizeRenameFailed, errorMessage, e)
}
try {
- deps.rebaseTaskFilePaths?.(task.id, renameSource, desiredFinalPath)
+ deps.rebaseTaskFilePaths?.(task.id, renameSource, publishedFinalPath)
} catch (err) {
deps.log.warn(
{ err, taskId: task.id },
@@ -661,13 +682,13 @@ async function finalizeBt(
'finalize_bt_metadata_commit_failed'
)
}
- applyBtTaskAfterRename(task, desiredFinalPath)
+ applyBtTaskAfterRename(task, publishedFinalPath)
await persistTaskState(task, deps)
}
if (
storageLayout &&
- !isSameOrDescendant(desiredFinalPath, storageLayout.workspacePath)
+ !isSameOrDescendant(publishedFinalPath, storageLayout.workspacePath)
) {
try {
await deps.fs.removePathRecursive(storageLayout.workspacePath)
diff --git a/src/core/task/finalize-target-name.test.ts b/src/core/task/finalize-target-name.test.ts
new file mode 100644
index 00000000..69f3f08a
--- /dev/null
+++ b/src/core/task/finalize-target-name.test.ts
@@ -0,0 +1,37 @@
+import path from 'node:path'
+import { describe, expect, it, vi } from 'vitest'
+import { resolvePublishedTargetPath } from './finalize-target-name'
+
+describe('resolvePublishedTargetPath', () => {
+ it('keeps an already-clean target untouched and never re-picks it', async () => {
+ // A clean name was deduplicated when the task was created; picking again
+ // would collide with the task's own `.motrix` reservation.
+ const picker = { pick: vi.fn() }
+ expect(
+ await resolvePublishedTargetPath(path.join('/d', 'foo.mp4'), picker)
+ ).toBe(path.join('/d', 'foo.mp4'))
+ expect(picker.pick).not.toHaveBeenCalled()
+ })
+
+ it('deduplicates a sanitized name against what already exists', async () => {
+ // `a:b.txt` sanitizes to `a_b.txt`, which nobody reserved at create time.
+ const picker = { pick: vi.fn(async () => 'a_b (1).txt') }
+ expect(
+ await resolvePublishedTargetPath(path.join('/d', 'a:b.txt'), picker)
+ ).toBe(path.join('/d', 'a_b (1).txt'))
+ expect(picker.pick).toHaveBeenCalledWith(path.join('/d'), 'a_b.txt')
+ })
+
+ it('returns the sanitized name when the picker finds it free', async () => {
+ const picker = { pick: vi.fn(async (_dir: string, name: string) => name) }
+ expect(
+ await resolvePublishedTargetPath(path.join('/d', 'CON.txt'), picker)
+ ).toBe(path.join('/d', 'CON_.txt'))
+ })
+
+ it('still sanitizes when no picker is wired', async () => {
+ expect(
+ await resolvePublishedTargetPath(path.join('/d', 'a:b.txt'), undefined)
+ ).toBe(path.join('/d', 'a_b.txt'))
+ })
+})
diff --git a/src/core/task/finalize-target-name.ts b/src/core/task/finalize-target-name.ts
new file mode 100644
index 00000000..ccb93f5b
--- /dev/null
+++ b/src/core/task/finalize-target-name.ts
@@ -0,0 +1,26 @@
+import path from 'node:path'
+import { sanitizeFinalizePath } from '@core/fs/finalize-path'
+import type { FinalNamePicker } from './final-name-picker'
+
+/**
+ * Resolve the path a finalized artifact is published under.
+ *
+ * The final component is sanitized for every supported filesystem, and when
+ * sanitization changes it the result is deduplicated again. The name was
+ * reserved at create time in its unsanitized spelling, so the sanitized one
+ * can collide with an existing file; publication renames without replacing,
+ * so an unhandled collision fails the task instead of becoming `name (1)`.
+ *
+ * An already-clean name is returned as-is: it is the reservation made at
+ * create time, and re-picking it would count the task's own temporary file
+ * as a conflict.
+ */
+export async function resolvePublishedTargetPath(
+ requested: string,
+ picker: Pick<FinalNamePicker, 'pick'> | undefined
+): Promise<string> {
+ const sanitized = sanitizeFinalizePath(requested)
+ if (sanitized === requested || !picker) return sanitized
+ const dir = path.dirname(sanitized)
+ return path.join(dir, await picker.pick(dir, path.basename(sanitized)))
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 6fa88e56..a443db44 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1166,6 +1166,7 @@ function buildFinalizeDeps(adapter: Aria2Adapter) {
? taskInspectorActivityRuntime.runTaskMutation(taskIds, operation)
: operation(),
log,
+ finalNamePicker,
commitFinalizedArtifact: async (input: FinalizeArtifactCommitRequest) => {
if (!durableFinalizeRuntime) {
throw new Error('durable finalize runtime is unavailable')
diff --git a/src/server/index.ts b/src/server/index.ts
index fc8a7b83..2427b2f7 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -1490,6 +1490,7 @@ async function main() {
operation: () => Promise<T>
) => taskInspectorActivityRuntime.runTaskMutation(taskIds, operation),
log,
+ finalNamePicker,
commitFinalizedArtifact: async (input: FinalizeArtifactCommitRequest) => {
const post =
input.occurrence?.type === 'terminal'