Compare commits

...
Author SHA1 Message Date
Yuri Karamian f39b301efc fix: judge network paths by their text on Windows
On Windows, a network path from note content that lies outside the vault
and outside any folder the user opened is refused before the filesystem is
asked about it, in the backend path checks and in the frontend resolvers.
Other platforms are unchanged.
2026-10-10 17:29:10 +02:00
6 changed files with 285 additions and 2 deletions

No files matched your search

+45
View File
@@ -3157,7 +3157,49 @@ fn active_vault_path<R: Runtime>(app: &AppHandle<R>) -> Result<PathBuf, String>
.ok_or_else(|| "No active vault".to_string())
}
/// Folders the user already works in: every configured vault and every folder granted through a
/// file dialog or by opening a note from outside a vault. Used to judge network paths by their text.
fn known_roots<R: Runtime>(app: &AppHandle<R>) -> Vec<String> {
let mut roots: Vec<String> = app
.try_state::<AppState>()
.and_then(|state| {
state.config.lock().ok().map(|config| {
config
.vaults
.iter()
.map(|vault| vault.path.clone())
.collect()
})
})
.unwrap_or_default();
for pattern in app.fs_scope().allowed_patterns() {
// Scope entries are glob patterns: `folder`, `folder/*` and `folder/**`, with glob
// characters in the folder name written as one-character classes.
let text = pattern
.as_str()
.replace("[[]", "[")
.replace("[]]", "]")
.replace("[*]", "*")
.replace("[?]", "?");
let folder = text.trim_end_matches(['*', '/', '\\']);
if !folder.is_empty() {
roots.push(folder.to_string());
}
}
roots
}
fn refuse_foreign_network_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
if cfg!(windows) && crate::vault::operations::is_network_path(&path.to_string_lossy()) {
return crate::vault::operations::refuse_foreign_network_path(path, &known_roots(app));
}
Ok(())
}
fn path_is_in_active_vault<R: Runtime>(app: &AppHandle<R>, path: &Path) -> bool {
if refuse_foreign_network_path(app, path).is_err() {
return false;
}
let Ok(vault) = active_vault_path(app)
.and_then(|path| std::fs::canonicalize(path).map_err(|error| error.to_string()))
else {
@@ -3173,6 +3215,7 @@ fn path_is_in_active_vault<R: Runtime>(app: &AppHandle<R>, path: &Path) -> bool
}
fn ensure_scoped_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
refuse_foreign_network_path(app, path)?;
if app.fs_scope().is_allowed(path) {
Ok(())
} else {
@@ -3181,6 +3224,7 @@ fn ensure_scoped_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(),
}
fn ensure_readable_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
refuse_foreign_network_path(app, path)?;
if path.is_file() && (path_is_in_active_vault(app, path) || app.fs_scope().is_allowed(path)) {
Ok(())
} else {
@@ -3189,6 +3233,7 @@ fn ensure_readable_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(
}
fn ensure_writable_path<R: Runtime>(app: &AppHandle<R>, path: &Path) -> Result<(), String> {
refuse_foreign_network_path(app, path)?;
if path_is_in_active_vault(app, path) || app.fs_scope().is_allowed(path) {
Ok(())
} else {
+144
View File
@@ -21,11 +21,81 @@ fn canonicalize_path(path: &Path, label: &str) -> Result<PathBuf, String> {
fs::canonicalize(path).map_err(|error| format!("Invalid {label}: {error}"))
}
/// Whether Windows would resolve this path over the network: `\\host\share\..`, `//host/share/..`
/// or the verbatim `\\?\UNC\host\..`. Merely examining such a path (does it exist, what is its
/// real path) makes Windows contact the host and offer it the user's login, so a path taken from
/// note content must be judged by its text before the filesystem is asked anything.
pub(crate) fn is_network_path(path: &str) -> bool {
let normalized = path.replace('\\', "/");
match normalized
.strip_prefix("//?/")
.or_else(|| normalized.strip_prefix("//./"))
{
Some(rest) => rest
.get(..4)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("unc/")),
None => normalized.starts_with("//"),
}
}
/// `//host/share/folder` in one spelling: forward slashes, no verbatim prefix, lower case.
fn network_path_key(path: &str) -> String {
let normalized = path.replace('\\', "/");
let rest = match normalized.get(..8) {
Some(prefix)
if prefix.eq_ignore_ascii_case("//?/unc/")
|| prefix.eq_ignore_ascii_case("//./unc/") =>
{
format!("//{}", &normalized[8..])
}
_ => normalized,
};
rest.trim_end_matches('/').to_lowercase()
}
/// Whether a network path lies, by its text alone, inside one of the folders the user already
/// works in (a vault on a share, or a folder they opened a note from).
pub(crate) fn network_path_within(path: &str, roots: &[String]) -> bool {
let key = network_path_key(path);
if key.split('/').any(|segment| segment == "..") {
return false;
}
roots
.iter()
.filter(|root| is_network_path(root))
.any(|root| {
let root = network_path_key(root);
key == root
|| key
.strip_prefix(&root)
.is_some_and(|rest| rest.starts_with('/'))
})
}
/// Refuses a network path outside the known folders before any filesystem call. Only Windows
/// reads these spellings as network paths; elsewhere `//x/y` is an ordinary local path.
pub(crate) fn refuse_foreign_network_path(path: &Path, roots: &[String]) -> Result<(), String> {
refuse_foreign_network_path_on(cfg!(windows), path, roots)
}
fn refuse_foreign_network_path_on(
windows: bool,
path: &Path,
roots: &[String],
) -> Result<(), String> {
let text = path.to_string_lossy();
if windows && is_network_path(&text) && !network_path_within(&text, roots) {
return Err("Network paths outside the vault are not opened".to_string());
}
Ok(())
}
fn ensure_vault_content_path(
vault_path: &str,
requested_path: &Path,
allow_root: bool,
) -> Result<PathBuf, String> {
refuse_foreign_network_path(requested_path, &[vault_path.to_string()])?;
let vault = canonicalize_path(Path::new(vault_path), "vault path")?;
let requested = canonicalize_path(requested_path, "vault item path")?;
let metadata = vault.join(".helixnotes");
@@ -87,6 +157,7 @@ fn ensure_notebook_path(vault_path: &str, requested_path: &Path) -> Result<PathB
}
fn ensure_trash_entry(vault_path: &str, requested_path: &Path) -> Result<PathBuf, String> {
refuse_foreign_network_path(requested_path, &[vault_path.to_string()])?;
let trash = canonicalize_path(&helixnotes_dir(vault_path).join("trash"), "trash path")?;
let requested = canonicalize_path(requested_path, "trash item path")?;
if requested == trash || !requested.starts_with(&trash) {
@@ -2479,6 +2550,79 @@ pub fn sanitize_filename(name: &str) -> String {
.to_string()
}
#[cfg(test)]
mod network_path_tests {
use super::*;
#[test]
fn network_paths_are_recognized_by_their_text() {
for path in [
r"\\host\share\r.pdf",
"//host/share/r.pdf",
r"\\?\UNC\host\share\r.pdf",
r"\\?\unc\host\share",
"//?/UNC/host/share",
r"\/host\share",
] {
assert!(is_network_path(path), "{path}");
}
for path in [
r"C:\Users\me\note.md",
"C:/Users/me/note.md",
r"\\?\C:\Users\me\note.md",
r"\\.\C:\x",
"/home/me/note.md",
"relative/note.md",
r"folder\note.md",
"",
] {
assert!(!is_network_path(path), "{path}");
}
}
#[test]
fn only_network_paths_inside_known_folders_pass_on_windows() {
let roots = vec![
r"\\nas\notes\Vault".to_string(),
r"\\?\UNC\files\home\me\opened".to_string(),
r"C:\Users\me\Vault".to_string(),
];
let check = |path: &str| refuse_foreign_network_path_on(true, Path::new(path), &roots);
// Inside a vault or an opened folder, in any spelling.
for path in [
r"\\nas\notes\Vault\note.md",
"//NAS/notes/vault/sub/note.md",
r"\\?\UNC\nas\notes\Vault\.helixnotes\attachments\a.png",
r"\\files\home\me\opened\note.md",
r"\\nas\notes\Vault",
] {
assert!(check(path).is_ok(), "{path}");
}
// Another host, another share, a sibling folder, or a way back out.
for path in [
r"\\evil\share\r.pdf",
"//evil/share/r.pdf",
r"\\nas\other\x.md",
r"\\nas\notes\Vault2\x.md",
r"\\nas\notes\Vault\..\..\other\x.md",
r"\\?\UNC\evil\share\x.md",
] {
assert!(check(path).is_err(), "{path}");
}
// Local paths are not this check's business, and a local vault grants no network folder.
assert!(check(r"C:\Windows\system.ini").is_ok());
assert!(check("relative/x.md").is_ok());
assert!(refuse_foreign_network_path_on(
true,
Path::new(r"\\nas\x"),
&[r"C:\nas".to_string()]
)
.is_err());
// Elsewhere `//x/y` is an ordinary local path and nothing is refused.
assert!(refuse_foreign_network_path_on(false, Path::new("//home/me/x.md"), &[]).is_ok());
}
}
#[cfg(test)]
mod tests {
use super::{
+3
View File
@@ -3349,6 +3349,9 @@
return convertFileSrc(src, 'imgproxy');
}
const local = resolveFileReference(src, $activeNotePath, currentNoteAssetRoot());
// A network path outside the vault is never loaded as a file (Windows). Written as
// `//host/image.png` it is a web address without its scheme; anything else shows no image.
if (!local.path) return /^\/\/[^/\\?.]/.test(src) ? convertFileSrc('https:' + src, 'imgproxy') : '';
return convertFileSrc(normalizePath(local.path)) + local.suffix;
}
+48
View File
@@ -0,0 +1,48 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { isNetworkPath, networkPathWithin, resolveFileReference, resolveVaultFilePath } from './paths.ts';
test('network paths are recognized by their text', () => {
for (const path of ['\\\\host\\share\\r.pdf', '//host/share/r.pdf', '\\\\?\\UNC\\host\\share', '//?/unc/host/share']) {
assert.equal(isNetworkPath(path), true, path);
}
for (const path of ['C:\\Users\\me\\note.md', 'C:/Users/me/note.md', '\\\\?\\C:\\Users\\me', '/home/me/note.md', 'relative/note.md', '']) {
assert.equal(isNetworkPath(path), false, path);
}
});
test('a network path counts as inside a folder only by its own text', () => {
const roots = ['\\\\nas\\notes\\Vault', 'C:/Users/me/Vault', null];
assert.equal(networkPathWithin('//NAS/notes/vault/sub/a.png', roots), true);
assert.equal(networkPathWithin('\\\\?\\UNC\\nas\\notes\\Vault\\a.png', roots), true);
assert.equal(networkPathWithin('//nas/notes/Vault2/a.png', roots), false);
assert.equal(networkPathWithin('//nas/notes/Vault/../../other/a.png', roots), false);
assert.equal(networkPathWithin('//evil/share/a.png', roots), false);
});
test('on Windows a reference to a network path outside the vault resolves to no file', () => {
const vault = 'C:/Users/me/Vault';
const note = 'C:/Users/me/Vault/Folder/note.md';
for (const target of ['//evil/share/r.pdf', '\\\\evil\\share\\r.pdf', '//evil/share/image.png', '%2F%2Fevil/share/x.png']) {
assert.equal(resolveFileReference(target, note, vault, true).path, '', target);
}
// Ordinary references are untouched.
assert.equal(resolveVaultFilePath('image.png', note, vault, true), 'C:/Users/me/Vault/Folder/image.png');
assert.equal(resolveVaultFilePath('.helixnotes/attachments/a.png', note, vault, true), 'C:/Users/me/Vault/.helixnotes/attachments/a.png');
assert.equal(resolveVaultFilePath('C:/Users/me/Pictures/a.png', note, vault, true), 'C:/Users/me/Pictures/a.png');
});
test('a vault or an opened note on a network share keeps working on Windows', () => {
const vault = '\\\\nas\\notes\\Vault';
const note = '\\\\nas\\notes\\Vault\\Folder\\note.md';
assert.equal(resolveVaultFilePath('image.png', note, vault, true), '//nas/notes/Vault/Folder/image.png');
assert.equal(resolveVaultFilePath('//nas/notes/Vault/other.png', note, vault, true), '//nas/notes/Vault/other.png');
assert.equal(resolveVaultFilePath('//nas/notes/Elsewhere/x.png', note, vault, true), '');
// A note opened from outside any vault: its own folder is allowed.
assert.equal(resolveVaultFilePath('pic.png', '\\\\files\\home\\me\\note.md', null, true), '//files/home/me/pic.png');
assert.equal(resolveVaultFilePath('//other/share/pic.png', '\\\\files\\home\\me\\note.md', null, true), '');
});
test('elsewhere a path starting with two slashes stays an ordinary local path', () => {
assert.equal(resolveVaultFilePath('//home/me/pic.png', '/home/me/Vault/note.md', '/home/me/Vault', false), '//home/me/pic.png');
});
+39 -2
View File
@@ -52,13 +52,41 @@ export function noteAssetRoot(notePath: string | null, activeVault: string | nul
return [...vaults].filter(root => isPathInDirectory(notePath, root)).sort((a, b) => b.length - a.length)[0] ?? null;
}
/**
* Whether Windows would resolve this path over the network: `\\host\share`, `//host/share` or the
* verbatim `\\?\UNC\host`. Merely loading or examining such a path makes Windows contact the host
* and offer it the user's login, so a path from note content is judged by its text first.
*/
export function isNetworkPath(path: string): boolean {
const normalized = path.replace(/\\/g, '/');
const verbatim = /^\/\/[?.]\/(.*)$/.exec(normalized);
return verbatim ? /^unc\//i.test(verbatim[1]) : normalized.startsWith('//');
}
function networkPathKey(path: string): string {
return path.replace(/\\/g, '/').replace(/^\/\/[?.]\/unc\//i, '//').replace(/\/+$/, '').toLowerCase();
}
/** Whether a network path lies, by its text alone, inside one of the given folders. */
export function networkPathWithin(path: string, roots: readonly (string | null | undefined)[]): boolean {
const key = networkPathKey(path);
if (key.split('/').includes('..')) return false;
return roots.some((root) => {
if (!root || !isNetworkPath(root)) return false;
const rootKey = networkPathKey(root);
return key === rootKey || key.startsWith(rootKey + '/');
});
}
const windowsHost = typeof navigator !== 'undefined' && /windows nt/i.test(navigator.userAgent);
/** Decode only the URI path, keeping query/fragment data out of filesystem paths. */
export function resolveFileReference(source: string, notePath: string | null, vaultRoot: string | null): { path: string; suffix: string } {
export function resolveFileReference(source: string, notePath: string | null, vaultRoot: string | null, windows = windowsHost): { path: string; suffix: string } {
const boundary = source.search(/[?#]/);
const encoded = boundary < 0 ? source : source.slice(0, boundary);
let path: string;
try { path = decodeURIComponent(encoded); } catch { path = encoded; }
return { path: resolveVaultFilePath(path, notePath, vaultRoot), suffix: boundary < 0 ? '' : source.slice(boundary) };
return { path: resolveVaultFilePath(path, notePath, vaultRoot, windows), suffix: boundary < 0 ? '' : source.slice(boundary) };
}
/** Percent-encode each path segment for a Markdown destination; a Windows drive prefix stays literal. */
@@ -69,12 +97,21 @@ export function encodeMarkdownPath(path: string): string {
.replace(/[!'()*]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`)).join('/');
}
/**
* The local file a reference in a note points at. On Windows a network path outside the vault and
* the note's own folder resolves to '' (no file), so nothing downstream touches it.
*/
export function resolveVaultFilePath(
targetPath: string,
notePath: string | null,
vaultRoot: string | null,
windows = windowsHost,
): string {
const target = normalizeLocalAssetPath(targetPath);
if (windows && isNetworkPath(target)) {
const noteFolder = notePath ? notePath.replace(/\\/g, '/').replace(/\/[^/]*$/, '') : null;
if (!networkPathWithin(target, [vaultRoot, noteFolder])) return '';
}
if (target.startsWith('/') || /^[A-Za-z]:\//.test(target)) return target;
const root = vaultRoot?.replace(/\\/g, '/').replace(/\/$/, '') ?? '';
+6
View File
@@ -93,6 +93,12 @@
const note = get(activeNotePath);
const root = noteAssetRoot(note, config?.active_vault ?? null, config?.vaults.map(vault => vault.path) ?? []);
const absPath = resolveFileReference(href, note, root).path;
if (!absPath) {
// A network path outside the vault is not opened as a file (Windows). Written as
// `//host/page` it is a web address without its scheme.
if (/^\/\/[^/\\?.]/.test(href)) openUrl('https:' + href).catch((err) => console.error('Failed to open URL:', err));
return;
}
// Internal .md note link - navigate within the app
if (absPath.endsWith('.md')) {
window.dispatchEvent(new CustomEvent('helixnotes-open-note', { detail: absPath }));