Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent-tools,vector-db): refuse ':' NUL and device names in store and collection names

James Dame280d1bc2309
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
index 54c23fcfe..b529f909f 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs
@@ -749,7 +749,9 @@ pub fn thread_segment(thread_id: &str) -> Result<String, String> {
/// Sanitize a caller-supplied entry name into a safe `<stem>.md` filename.
/// Rejects path separators and `..` so the result can never escape the
-/// store directory. `.md` is appended if absent.
+/// store directory, and `:` (on Windows `C:x` is drive-relative and replaces
+/// the base it is joined to), NUL and Windows device names on every OS so a
+/// name means the same file everywhere. `.md` is appended if absent.
pub fn workspace_filename(name: &str) -> Result<String, String> {
let trimmed = name.trim();
let stem = trimmed.strip_suffix(".md").unwrap_or(trimmed);
@@ -759,7 +761,9 @@ pub fn workspace_filename(name: &str) -> Result<String, String> {
|| stem.contains('/')
|| stem.contains('\\')
|| stem.contains("..")
+ || stem.contains([':', '\0'])
|| stem.chars().all(|c| c == '.')
+ || is_windows_device_name(stem)
{
return Err(format!("ERROR: invalid name '{name}'"));
}
@@ -1036,6 +1040,18 @@ mod tests {
}
}
+ #[test]
+ fn filename_rejects_drive_prefixes_nul_and_device_names() {
+ for bad in ["C:x", "c:", "a:b", "C:x.md", "a\0b", "nul", "CON.md", "com1", "aux.txt"] {
+ assert!(
+ workspace_filename(bad).is_err(),
+ "expected {bad:?} to be rejected"
+ );
+ assert!(crate::skills::safe_stem(bad).is_err(), "{bad:?}");
+ }
+ assert_eq!(workspace_filename("console").unwrap(), "console.md");
+ }
+
/// Dot-only and empty-stem names are rejected rather than turned into a
/// hidden file. A bare "." used to yield "..md" -- contained, but a name the
/// guard would reject as input.
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs
index 7f236345e..f11f7a1a2 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/commands.rs
@@ -26,7 +26,7 @@ pub struct FileInput {
#[tauri::command]
pub async fn get_status(state: State<'_, VectorDBState>) -> Result<Status, VectorDBError> {
println!("[VectorDB] Checking ANN availability...");
- let temp = db::collection_path(&state.base_dir, "__status__");
+ let temp = db::collection_path(&state.base_dir, "__status__")?;
let conn = db::open_or_init_conn(&temp)?;
let ann = db::try_load_sqlite_vec_verbose(&conn);
@@ -42,7 +42,7 @@ pub async fn create_collection<R: tauri::Runtime>(
name: String,
dimension: usize,
) -> Result<(), VectorDBError> {
- let path = db::collection_path(&state.base_dir, &name);
+ let path = db::collection_path(&state.base_dir, &name)?;
let conn = db::open_or_init_conn(&path)?;
let has_ann = db::create_schema(&conn, dimension)?;
@@ -61,7 +61,7 @@ pub async fn create_file<R: tauri::Runtime>(
collection: String,
file: FileInput,
) -> Result<AttachmentFileInfo, VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
db::create_file(
&conn,
@@ -80,7 +80,7 @@ pub async fn insert_chunks<R: tauri::Runtime>(
file_id: String,
chunks: Vec<MinimalChunkInput>,
) -> Result<(), VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
let vec_loaded = db::try_load_sqlite_vec(&conn);
db::insert_chunks(&conn, &file_id, chunks, vec_loaded)
@@ -93,7 +93,7 @@ pub async fn delete_file<R: tauri::Runtime>(
collection: String,
file_id: String,
) -> Result<(), VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
db::delete_file(&conn, &file_id)
}
@@ -110,7 +110,7 @@ pub async fn search_collection<R: tauri::Runtime>(
mode: Option<String>,
file_ids: Option<Vec<String>>,
) -> Result<Vec<SearchResult>, VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
let vec_loaded = db::try_load_sqlite_vec(&conn);
db::search_collection(&conn, &query_embedding, limit, threshold, mode, vec_loaded, file_ids)
@@ -123,7 +123,7 @@ pub async fn list_attachments<R: tauri::Runtime>(
collection: String,
limit: Option<usize>,
) -> Result<Vec<AttachmentFileInfo>, VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
db::list_attachments(&conn, limit)
}
@@ -135,7 +135,7 @@ pub async fn delete_chunks<R: tauri::Runtime>(
collection: String,
ids: Vec<String>,
) -> Result<(), VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
db::delete_chunks(&conn, ids)
}
@@ -146,7 +146,7 @@ pub async fn delete_collection<R: tauri::Runtime>(
state: State<'_, VectorDBState>,
collection: String,
) -> Result<(), VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
if path.exists() {
std::fs::remove_file(path).ok();
}
@@ -172,7 +172,7 @@ pub async fn get_chunks<R: tauri::Runtime>(
start_order: i64,
end_order: i64,
) -> Result<Vec<SearchResult>, VectorDBError> {
- let path = db::collection_path(&state.base_dir, &collection);
+ let path = db::collection_path(&state.base_dir, &collection)?;
let conn = db::open_or_init_conn(&path)?;
db::get_chunks(&conn, file_id, start_order, end_order)
}
@@ -182,7 +182,7 @@ pub async fn get_chunks<R: tauri::Runtime>(
// ============================================================================
fn memory_conn(state: &VectorDBState) -> Result<rusqlite::Connection, VectorDBError> {
- let path = db::collection_path(&state.base_dir, db::MEMORY_COLLECTION);
+ let path = db::collection_path(&state.base_dir, db::MEMORY_COLLECTION)?;
db::open_or_init_conn(&path)
}
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs
index c4c1e3a75..7f6c89301 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs
+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/db.rs
@@ -65,12 +65,30 @@ pub fn base_dir_in(data_root: &Path) -> PathBuf {
base
}
-pub fn collection_path(base: &Path, name: &str) -> PathBuf {
- let mut p = base.to_path_buf();
+/// The database file for collection `name`, always a single file directly in
+/// `base`. Separators are folded to `_` as before; a `:` (a drive-relative path
+/// on Windows, which `push` would let replace `base`), a NUL, an empty name and
+/// a Windows device name are refused on every OS so a name means the same file
+/// everywhere.
+pub fn collection_path(base: &Path, name: &str) -> Result<PathBuf, VectorDBError> {
let clean = name.replace(['/', '\\'], "_");
- let filename = format!("{}.db", clean);
- p.push(&filename);
- p
+ if clean.is_empty() || clean.contains([':', '\0']) || is_windows_device_name(&clean) {
+ return Err(VectorDBError::InvalidInput(format!(
+ "invalid collection name '{name}'"
+ )));
+ }
+ Ok(base.join(format!("{}.db", clean)))
+}
+
+/// Names Windows maps to a device in every directory, in any case and also
+/// with an extension (`nul.txt`).
+fn is_windows_device_name(name: &str) -> bool {
+ let stem = name.split('.').next().unwrap_or(name).to_ascii_uppercase();
+ match stem.as_bytes() {
+ [a, b, c] => matches!(&[*a, *b, *c], b"CON" | b"PRN" | b"AUX" | b"NUL"),
+ [a, b, c, d] => matches!(&[*a, *b, *c], b"COM" | b"LPT") && d.is_ascii_digit(),
+ _ => false,
+ }
}
pub fn open_or_init_conn(path: &PathBuf) -> Result<Connection, VectorDBError> {
@@ -769,6 +787,19 @@ pub fn chunk_text(text: String, chunk_size: usize, chunk_overlap: usize) -> Vec<
mod tests {
use super::*;
+ #[test]
+ fn collection_path_stays_a_single_file_in_base() {
+ let base = Path::new("/data/vdb");
+ assert_eq!(
+ collection_path(base, "attachments_01H8X").unwrap(),
+ base.join("attachments_01H8X.db")
+ );
+ assert_eq!(collection_path(base, "a/b\\c").unwrap(), base.join("a_b_c.db"));
+ for bad in ["", "C:x", "c:", "a\0b", "nul", "CON.x", "com1"] {
+ assert!(collection_path(base, bad).is_err(), "{bad:?}");
+ }
+ }
+
#[test]
fn override_takes_priority_over_every_other_candidate() {
let paths = build_sqlite_vec_paths(Some("/custom/vec".to_string()), None);
diff --git a/src-tauri/src/core/agent/memory.rs b/src-tauri/src/core/agent/memory.rs
index 3b9bc8fba..e755e5f2c 100644
--- a/src-tauri/src/core/agent/memory.rs
+++ b/src-tauri/src/core/agent/memory.rs
@@ -44,7 +44,9 @@ pub(crate) fn index_message(project_root: &Path, role: &str, text: &str) {
}
let pid = project_id(project_root);
let id = content_id(&pid, role, text);
- let path = db::collection_path(&paths::vector_db_dir(), db::MEMORY_COLLECTION);
+ let Ok(path) = db::collection_path(&paths::vector_db_dir(), db::MEMORY_COLLECTION) else {
+ return;
+ };
if let Ok(conn) = db::open_or_init_conn(&path) {
let _ = db::memory_index(&conn, &id, &pid, text, role, now_ts());
}
@@ -54,7 +56,7 @@ pub(crate) fn index_message(project_root: &Path, role: &str, text: &str) {
/// for the system prompt. None when nothing is recalled (or the store is empty).
pub(crate) fn retrieve_block(project_root: &Path, query: &str) -> Option<String> {
let pid = project_id(project_root);
- let path = db::collection_path(&paths::vector_db_dir(), db::MEMORY_COLLECTION);
+ let path = db::collection_path(&paths::vector_db_dir(), db::MEMORY_COLLECTION).ok()?;
let conn = db::open_or_init_conn(&path).ok()?;
let hits = db::memory_search(&conn, &pid, query, TOP_K).ok()?;
if hits.is_empty() {