1use anyhow::{Context, Result, bail};
11use hashbrown::HashMap;
12use std::fs;
13use std::io::{Read, Write};
14use std::path::{Path, PathBuf};
15use tracing::{debug, info, warn};
16use vtcode_commons::safe_archive_relative_path;
17
18mod recovery;
19use vtcode_commons::{
20 VtCodePaths, canonicalize, fs::rename_synced, fs::sync_dir, validate_no_escaping_symlink_ancestors,
21};
22
23const MAX_BUNDLE_SIZE: usize = 50 * 1024 * 1024;
25const MAX_FILE_SIZE: usize = 25 * 1024 * 1024;
27const MAX_TOTAL_UNCOMPRESSED_SIZE: u64 = 200 * 1024 * 1024;
33const MAX_FILE_COUNT: usize = 500;
35
36fn within_total_budget(total: u64) -> bool {
41 total <= MAX_TOTAL_UNCOMPRESSED_SIZE
42}
43
44#[derive(Debug, Clone)]
46pub struct ImportedSkillInfo {
47 name: String,
48 version: Option<String>,
49 description: String,
50 path: PathBuf,
51 file_count: usize,
52 total_size: u64,
53}
54
55pub fn export_skill_bundle(skill_root: &Path) -> Result<Vec<u8>> {
60 let skill_md = skill_root.join("SKILL.md");
61 if !skill_md.exists() {
62 bail!("No SKILL.md found at {}", skill_root.display());
63 }
64
65 let mut buf = Vec::new();
66 {
67 let cursor = std::io::Cursor::new(&mut buf);
68 let mut zip_writer = zip::ZipWriter::new(cursor);
69 let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
70
71 add_dir_to_zip(&mut zip_writer, skill_root, skill_root, options)?;
72 zip_writer.finish().context("Failed to finalize zip archive")?;
73 }
74
75 info!("Exported skill bundle from {}: {} bytes", skill_root.display(), buf.len());
76 Ok(buf)
77}
78
79fn add_dir_to_zip<W: Write + std::io::Seek>(
80 zip_writer: &mut zip::ZipWriter<W>,
81 root: &Path,
82 dir: &Path,
83 options: zip::write::SimpleFileOptions,
84) -> Result<()> {
85 for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
86 let entry = entry?;
87 let path = entry.path();
88 let rel = path
89 .strip_prefix(root)
90 .with_context(|| format!("stripping prefix from {}", path.display()))?;
91
92 if vtcode_commons::walk::entry_is_dir(&entry) {
94 let dir_name = format!("{}/", rel.to_string_lossy());
95 zip_writer
96 .add_directory(&dir_name, options)
97 .with_context(|| format!("adding directory {dir_name}"))?;
98 add_dir_to_zip(zip_writer, root, &path, options)?;
99 } else {
100 let name = rel.to_string_lossy().to_string();
101 zip_writer
102 .start_file(&name, options)
103 .with_context(|| format!("starting file {name}"))?;
104 let data = fs::read(&path).with_context(|| format!("reading file {}", path.display()))?;
105 zip_writer.write_all(&data)?;
106 }
107 }
108 Ok(())
109}
110
111pub fn import_skill_bundle(zip_bytes: &[u8], dest_store: &Path) -> Result<ImportedSkillInfo> {
116 if zip_bytes.len() > MAX_BUNDLE_SIZE {
117 bail!("Bundle size {} bytes exceeds maximum {} bytes", zip_bytes.len(), MAX_BUNDLE_SIZE);
118 }
119
120 let temp_dir = tempfile::tempdir().context("Failed to create temp directory")?;
121 let temp_path = temp_dir.path();
122
123 extract_zip_safely(zip_bytes, temp_path)?;
124
125 let skill_md_path = find_skill_md(temp_path)?;
126 let skill_root = skill_md_path.parent().unwrap_or(temp_path);
127
128 validate_extracted_bundle(skill_root)?;
129
130 let (manifest, _instructions) = crate::manifest::parse_skill_content(
131 &fs::read_to_string(&skill_md_path).context("Failed to read extracted SKILL.md")?,
132 )?;
133
134 if let Some(value) = manifest.metadata.as_ref().and_then(|metadata| metadata.get("version")) {
135 let _ = value.as_str().context("skill metadata.version must be a string")?;
136 }
137 let version = crate::versioning::effective_version(&manifest).unwrap_or("0.0.0");
138 if !safe_version(version) {
139 bail!("skill metadata.version must be a safe version identifier");
140 }
141
142 let dest_dir = dest_store.join(&manifest.name).join(version);
143 let (file_count, total_size) = VtCodePaths::with_private_file_lock(dest_store.join("index.json"), || {
144 recovery::recover_abandoned_imports(dest_store)?;
145 let index = load_skill_index_unlocked(dest_store)?;
146 validate_no_escaping_symlink_ancestors(&dest_dir, true).context("validate skill destination")?;
147 let staging = tempfile::Builder::new().prefix(".skill-import-").tempdir_in(dest_store)?;
148 let staged = staging.path().join("new");
149 fs::create_dir(&staged).context("create staged skill directory")?;
150 let counts = copy_dir_recursive(skill_root, &staged)?;
151 let parent = dest_dir.parent().context("skill destination has no parent")?;
152 fs::create_dir_all(parent).context("create skill directory")?;
153 let index_json = updated_skill_index(index, &manifest.name, version)?;
154 let had_previous = recovery::directory_exists(&dest_dir)?;
155 recovery::record_transaction(staging.path(), dest_store, &manifest.name, version, had_previous, &index_json)?;
156 publish_staged_skill(staging, &dest_dir, || publish_skill_index(dest_store, &index_json))?;
157 Ok(counts)
158 })?;
159
160 info!(
161 "Imported skill '{}' v{} ({} files, {} bytes) to {}",
162 manifest.name,
163 version,
164 file_count,
165 total_size,
166 dest_dir.display()
167 );
168
169 let version = version.to_owned();
170
171 Ok(ImportedSkillInfo {
172 name: manifest.name,
173 version: Some(version),
174 description: manifest.description,
175 path: dest_dir,
176 file_count,
177 total_size,
178 })
179}
180
181fn safe_version(version: &str) -> bool {
182 !(version.is_empty()
183 || version.len() > 128
184 || version == "."
185 || version == ".."
186 || !version
187 .bytes()
188 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'+')))
189}
190
191fn publish_staged_skill(
192 staging: tempfile::TempDir,
193 dest: &Path,
194 publish_index: impl FnOnce() -> Result<()>,
195) -> Result<()> {
196 let staged = staging.path().join("new");
197 let backup = staging.path().join("previous");
198 let had_previous = match fs::symlink_metadata(dest) {
199 Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {
200 warn!("Overwriting existing skill version at {}", dest.display());
201 rename_synced(dest, &backup).context("back up existing skill version")?;
202 true
203 }
204 Ok(_) => bail!("skill destination is not a regular directory: {}", dest.display()),
205 Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
206 Err(error) => return Err(error).context("inspect existing skill version"),
207 };
208
209 let result = rename_synced(&staged, dest)
210 .context("publish staged skill version")
211 .and_then(|()| publish_index());
212 if let Err(error) = result {
213 let rollback = (|| -> Result<()> {
214 if !staged.exists() {
215 fs::remove_dir_all(dest).context("remove failed skill version")?;
216 }
217 if had_previous {
218 rename_synced(&backup, dest).context("restore previous skill version")?;
219 }
220 Ok(())
221 })();
222 if let Err(rollback_error) = rollback {
223 let retained = staging.keep();
224 return Err(error.context(format!(
225 "rollback failed: {rollback_error:#}; recovery files retained at {}",
226 retained.display()
227 )));
228 }
229 return Err(error);
230 }
231 Ok(())
232}
233
234pub fn import_inline_bundle(base64_data: &str, dest_store: &Path) -> Result<ImportedSkillInfo> {
236 use base64::Engine;
237 let bytes = base64::engine::general_purpose::STANDARD
238 .decode(base64_data)
239 .context("Failed to decode base64 bundle")?;
240 import_skill_bundle(&bytes, dest_store)
241}
242
243fn extract_zip_safely(zip_bytes: &[u8], dest: &Path) -> Result<()> {
245 let cursor = std::io::Cursor::new(zip_bytes);
246 let mut archive = zip::ZipArchive::new(cursor).context("Failed to open zip archive")?;
247
248 if archive.len() > MAX_FILE_COUNT {
249 bail!("Zip contains {} entries, exceeds maximum {}", archive.len(), MAX_FILE_COUNT);
250 }
251
252 let mut total_uncompressed: u64 = 0;
253
254 for i in 0..archive.len() {
255 let mut file = archive.by_index(i).with_context(|| format!("reading zip entry {i}"))?;
256 let raw_name = file
257 .name()
258 .with_context(|| format!("zip entry {i} has a non-UTF-8 name"))?
259 .into_owned();
260
261 let safe_name = safe_archive_relative_path(Path::new(&raw_name))
262 .with_context(|| format!("Path traversal detected in zip entry: {raw_name}"))?;
263 if safe_name.as_os_str().is_empty() {
264 continue;
265 }
266
267 let out_path = dest.join(safe_name);
268
269 if file.is_dir() {
270 fs::create_dir_all(&out_path).with_context(|| format!("creating dir {}", out_path.display()))?;
271 } else {
272 if file.size() > MAX_FILE_SIZE as u64 {
273 bail!("Zip entry '{}' ({} bytes) exceeds maximum {} bytes", raw_name, file.size(), MAX_FILE_SIZE);
274 }
275
276 if let Some(parent) = out_path.parent() {
277 fs::create_dir_all(parent)?;
278 }
279
280 let mut out_file =
281 fs::File::create(&out_path).with_context(|| format!("creating file {}", out_path.display()))?;
282 let written = copy_bounded(&mut file, &mut out_file, MAX_FILE_SIZE as u64)
285 .with_context(|| format!("writing file {}", out_path.display()))?;
286 total_uncompressed += written;
287 if !within_total_budget(total_uncompressed) {
288 bail!(
289 "Zip uncompressed size {total_uncompressed} bytes exceeds maximum {MAX_TOTAL_UNCOMPRESSED_SIZE} bytes"
290 );
291 }
292 }
293 }
294
295 Ok(())
296}
297
298fn copy_bounded<R: Read, W: Write>(reader: &mut R, writer: &mut W, limit: u64) -> Result<u64> {
304 let mut bounded = reader.take(limit.saturating_add(1));
305 let written = std::io::copy(&mut bounded, writer)?;
306 if written > limit {
307 bail!("entry exceeds maximum {limit} bytes");
308 }
309 Ok(written)
310}
311
312fn find_skill_md(dir: &Path) -> Result<PathBuf> {
314 let direct = dir.join("SKILL.md");
315 if direct.exists() {
316 return Ok(direct);
317 }
318 let direct_lower = dir.join("skill.md");
319 if direct_lower.exists() {
320 return Ok(direct_lower);
321 }
322
323 for entry in fs::read_dir(dir).context("Failed to read extracted directory")? {
324 let entry = entry?;
325 if vtcode_commons::walk::entry_is_dir(&entry) {
326 let nested = entry.path().join("SKILL.md");
327 if nested.exists() {
328 return Ok(nested);
329 }
330 let nested_lower = entry.path().join("skill.md");
331 if nested_lower.exists() {
332 return Ok(nested_lower);
333 }
334 }
335 }
336
337 bail!("No SKILL.md found in extracted bundle")
338}
339
340fn validate_extracted_bundle(skill_root: &Path) -> Result<()> {
342 let mut file_count = 0u64;
343 let mut total_size = 0u64;
344
345 validate_dir_recursive(skill_root, skill_root, &mut file_count, &mut total_size)?;
346
347 if file_count > MAX_FILE_COUNT as u64 {
348 bail!("Bundle contains {file_count} files, exceeds maximum {MAX_FILE_COUNT}");
349 }
350
351 if !within_total_budget(total_size) {
352 bail!("Bundle uncompressed size {total_size} bytes exceeds maximum {MAX_TOTAL_UNCOMPRESSED_SIZE} bytes");
353 }
354
355 Ok(())
356}
357
358fn validate_dir_recursive(root: &Path, dir: &Path, file_count: &mut u64, total_size: &mut u64) -> Result<()> {
359 for entry in fs::read_dir(dir)? {
360 let entry = entry?;
361 let path = entry.path();
362
363 if path.is_symlink() {
364 bail!("Symlinks not allowed in skill bundles: {}", path.display());
365 }
366
367 let canonical = canonicalize(&path).unwrap_or_else(|_| path.clone());
368 let root_canonical = canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
369 if !canonical.starts_with(&root_canonical) {
370 bail!("Path traversal detected: {} escapes bundle root", path.display());
371 }
372
373 if path.is_dir() {
374 validate_dir_recursive(root, &path, file_count, total_size)?;
375 } else {
376 *file_count += 1;
377 let size = entry.metadata()?.len();
378 if size > MAX_FILE_SIZE as u64 {
379 bail!("File {} ({size} bytes) exceeds maximum {MAX_FILE_SIZE} bytes", path.display(),);
380 }
381 *total_size += size;
382 }
383 }
384 Ok(())
385}
386
387fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(usize, u64)> {
392 let mut count = 0usize;
393 let mut size = 0u64;
394
395 for entry in fs::read_dir(src)? {
396 let entry = entry?;
397 let src_path = entry.path();
398 let file_name = entry.file_name();
399 let dst_path = dst.join(&file_name);
400
401 if vtcode_commons::walk::entry_is_dir(&entry) {
402 fs::create_dir_all(&dst_path)?;
403 let (c, s) = copy_dir_recursive(&src_path, &dst_path)?;
404 count += c;
405 size += s;
406 } else {
407 fs::copy(&src_path, &dst_path)
408 .with_context(|| format!("failed to copy {} to {}", src_path.display(), dst_path.display()))?;
409 fs::File::open(&dst_path)
410 .with_context(|| format!("failed to open copied file {}", dst_path.display()))?
411 .sync_all()
412 .with_context(|| format!("failed to sync copied file {}", dst_path.display()))?;
413 count += 1;
414 size += entry
415 .metadata()
416 .with_context(|| format!("failed to stat {}", src_path.display()))?
417 .len();
418 }
419 }
420
421 sync_dir(dst).with_context(|| format!("failed to sync copied directory {}", dst.display()))?;
422
423 Ok((count, size))
424}
425
426#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
428pub struct SkillStoreIndex {
429 skills: HashMap<String, SkillVersionIndex>,
430}
431
432#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
433pub struct SkillVersionIndex {
434 latest_version: String,
435 #[serde(skip_serializing_if = "Option::is_none")]
436 default_version: Option<String>,
437 versions: Vec<String>,
438}
439
440fn updated_skill_index(mut index: SkillStoreIndex, skill_name: &str, version: &str) -> Result<Vec<u8>> {
442 let entry = index.skills.entry(skill_name.to_string()).or_insert_with(|| SkillVersionIndex {
443 latest_version: version.to_string(),
444 default_version: None,
445 versions: Vec::new(),
446 });
447
448 if !entry.versions.contains(&version.to_string()) {
449 entry.versions.push(version.to_string());
450 }
451 entry.latest_version = version.to_string();
452
453 serde_json::to_vec_pretty(&index).with_context(|| format!("failed to serialize index for {skill_name}"))
454}
455
456fn publish_skill_index(store_path: &Path, index_json: &[u8]) -> Result<()> {
457 let index_path = store_path.join("index.json");
458 VtCodePaths::write_private_file_atomic(&index_path, index_json)
459 .with_context(|| format!("failed to write index at {}", index_path.display()))?;
460 sync_dir(store_path).with_context(|| format!("failed to sync store at {}", store_path.display()))?;
461
462 debug!("Updated skill index at {}", index_path.display());
463 Ok(())
464}
465
466pub fn load_skill_index(store_path: &Path) -> Result<SkillStoreIndex> {
468 match fs::metadata(store_path) {
469 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(SkillStoreIndex::default()),
470 Err(error) => return Err(error).context("Failed to inspect skill store"),
471 Ok(_) => {}
472 }
473 VtCodePaths::with_private_file_lock(store_path.join("index.json"), || {
474 recovery::recover_abandoned_imports(store_path)?;
475 load_skill_index_unlocked(store_path)
476 })
477}
478
479fn load_skill_index_unlocked(store_path: &Path) -> Result<SkillStoreIndex> {
480 let Some(content) = recovery::read_index(store_path)? else {
481 return Ok(SkillStoreIndex::default());
482 };
483 serde_json::from_slice(&content).context("Failed to parse skill store index")
484}
485
486#[cfg(test)]
487mod tests;