返回 CodeWhale
tests.rs
根目录 / crates / plugins / src / install / tests.rs
1 use super::*;
2 // `scan_tarball` lives in the sibling stage-reader module and is not needed
3 // by the verbs, so it is not in `super`'s namespace.
4 use super::tarball::{scan_tarball, stage_tarball};
5 use codewhale_skill_install::bounded_tar::test_archives;
6
7 #[path = "tests/place_recovery.rs"]
8 mod place_recovery;
9
10 fn write_bundle(root: &Path, dir: &str, name: &str) -> PathBuf {
11 let bundle = root.join(dir);
12 fs::create_dir_all(&bundle).unwrap();
13 fs::write(
14 bundle.join("plugin.toml"),
15 format!("schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n"),
16 )
17 .unwrap();
18 bundle
19 }
20
21 fn tarball(entries: &[(&str, &[u8])]) -> Vec<u8> {
22 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
23 let mut builder = tar::Builder::new(encoder);
24 for (path, body) in entries {
25 let mut header = tar::Header::new_gnu();
26 header.set_size(body.len() as u64);
27 header.set_mode(0o644);
28 header.set_cksum();
29 builder.append_data(&mut header, path, *body).unwrap();
30 }
31 let encoder = builder.into_inner().unwrap();
32 encoder.finish().unwrap()
33 }
34
35 #[cfg(unix)]
36 #[test]
37 fn remote_plugin_stage_preserves_only_owner_executable_intent() {
38 use std::os::unix::fs::PermissionsExt as _;
39
40 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
41 let mut builder = tar::Builder::new(encoder);
42 for (path, body, mode) in [
43 (
44 "repo/plugin.toml",
45 &b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n"[..],
46 0o644,
47 ),
48 ("repo/bin/server", &b"#!/bin/sh\nexit 0\n"[..], 0o6755),
49 ("repo/data.txt", &b"data"[..], 0o666),
50 ] {
51 let mut header = tar::Header::new_gnu();
52 header.set_size(body.len() as u64);
53 header.set_mode(mode);
54 header.set_cksum();
55 builder.append_data(&mut header, path, body).unwrap();
56 }
57 let bytes = builder.into_inner().unwrap().finish().unwrap();
58 let tmp = tempfile::tempdir().unwrap();
59 let staged = stage_tarball(&bytes, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None).unwrap();
60 for (path, expected) in [("bin/server", 0o700), ("data.txt", 0o600)] {
61 assert_eq!(
62 fs::metadata(staged.staged_path.join(path))
63 .unwrap()
64 .permissions()
65 .mode()
66 & 0o7777,
67 expected,
68 "{path}"
69 );
70 }
71 }
72
73 fn symlink_tarball(link_path: &str, target: &str, manifest: &str) -> Vec<u8> {
74 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
75 let mut builder = tar::Builder::new(encoder);
76 let body = b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n";
77 let mut header = tar::Header::new_gnu();
78 header.set_size(body.len() as u64);
79 header.set_mode(0o644);
80 header.set_cksum();
81 builder
82 .append_data(&mut header, manifest, &body[..])
83 .unwrap();
84 let mut link_header = tar::Header::new_gnu();
85 link_header.set_entry_type(tar::EntryType::Symlink);
86 link_header.set_size(0);
87 link_header.set_mode(0o777);
88 link_header.set_cksum();
89 builder
90 .append_link(&mut link_header, link_path, target)
91 .unwrap();
92 let encoder = builder.into_inner().unwrap();
93 encoder.finish().unwrap()
94 }
95
96 /// Emit one raw ustar file entry with an arbitrary (possibly hostile) name.
97 /// `tar::Builder` refuses `..` and absolute paths on write, so adversarial
98 /// archives have to be assembled byte-by-byte.
99 fn raw_tar_file_entry(name: &[u8], body: &[u8]) -> Vec<u8> {
100 let mut header = [0_u8; 512];
101 header[..name.len()].copy_from_slice(name);
102 header[100..108].copy_from_slice(b"0000644\0");
103 header[108..116].copy_from_slice(b"0000000\0");
104 header[116..124].copy_from_slice(b"0000000\0");
105 let size = format!("{:011o}\0", body.len());
106 header[124..136].copy_from_slice(size.as_bytes());
107 header[136..148].copy_from_slice(b"00000000000\0");
108 header[148..156].copy_from_slice(b" ");
109 header[156] = b'0';
110 header[257..263].copy_from_slice(b"ustar\0");
111 header[263..265].copy_from_slice(b"00");
112 let checksum: u32 = header.iter().map(|byte| u32::from(*byte)).sum();
113 let checksum = format!("{checksum:06o}\0 ");
114 header[148..156].copy_from_slice(checksum.as_bytes());
115 let mut out = header.to_vec();
116 out.extend_from_slice(body);
117 let padding = (512 - body.len() % 512) % 512;
118 out.extend(std::iter::repeat_n(0, padding));
119 out
120 }
121
122 fn raw_tarball(entries: &[(&[u8], &[u8])]) -> Vec<u8> {
123 use std::io::Write as _;
124
125 let mut tar_bytes = Vec::new();
126 for (name, body) in entries {
127 tar_bytes.extend(raw_tar_file_entry(name, body));
128 }
129 tar_bytes.extend(std::iter::repeat_n(0, 1024));
130 let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
131 encoder.write_all(&tar_bytes).unwrap();
132 encoder.finish().unwrap()
133 }
134
135 fn allow_all() -> NetworkPolicy {
136 NetworkPolicy {
137 default: codewhale_net::network_policy::DecisionToml::Allow,
138 ..Default::default()
139 }
140 }
141
142 fn no_conflict() -> impl Fn(&str) -> Option<String> {
143 |_| None
144 }
145
146 // ── scan/extract rules ────────────────────────────────────────────────
147
148 #[test]
149 fn scan_rejects_path_traversal() {
150 let bytes = raw_tarball(&[(
151 b"repo-main/../evil/plugin.toml",
152 b"schema_version = 1\n[plugin]\nname = \"evil\"\n",
153 )]);
154 let err = scan_tarball(&bytes, DEFAULT_MAX_SIZE_BYTES).unwrap_err();
155 assert!(
156 matches!(
157 err.downcast_ref::<PluginInstallError>(),
158 Some(PluginInstallError::PathTraversal(_))
159 ),
160 "got: {err:#}"
161 );
162 }
163
164 #[test]
165 fn scan_rejects_absolute_paths() {
166 let bytes = raw_tarball(&[(
167 b"/tmp/evil/plugin.toml",
168 b"schema_version = 1\n[plugin]\nname = \"evil\"\n",
169 )]);
170 assert!(scan_tarball(&bytes, DEFAULT_MAX_SIZE_BYTES).is_err());
171 }
172
173 #[test]
174 fn scan_enforces_size_cap() {
175 let body = vec![b'x'; 1024];
176 let bytes = tarball(&[
177 (
178 "repo-main/plugin.toml",
179 b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n",
180 ),
181 ("repo-main/blob.bin", &body),
182 ]);
183 let err = scan_tarball(&bytes, 512).unwrap_err();
184 assert!(
185 matches!(
186 err.downcast_ref::<PluginInstallError>(),
187 Some(PluginInstallError::OversizedBundle { .. })
188 ),
189 "got: {err:#}"
190 );
191 }
192
193 const MANIFEST: &[u8] = b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n";
194 const SMALL_CAP: u64 = 64 * 1024;
195 const HUGE_BODY: u64 = 16 * 1024 * 1024;
196
197 fn assert_oversized(err: &anyhow::Error) {
198 assert!(
199 matches!(
200 err.downcast_ref::<PluginInstallError>(),
201 Some(PluginInstallError::OversizedBundle { .. })
202 ),
203 "got: {err:#}"
204 );
205 }
206
207 #[test]
208 fn scan_counts_the_size_a_pax_record_gives_an_entry() {
209 let bytes = test_archives::pax_size_record_archive(("plugin.toml", MANIFEST), HUGE_BODY);
210 assert_oversized(&scan_tarball(&bytes, SMALL_CAP).unwrap_err());
211 let tmp = tempfile::tempdir().unwrap();
212 assert_oversized(
213 &tarball::stage_tarball(&bytes, tmp.path(), SMALL_CAP, None)
214 .map(|staged| staged.name)
215 .unwrap_err(),
216 );
217 }
218
219 #[test]
220 fn scan_and_extract_bound_the_decoded_stream_for_extension_entries() {
221 for kind in [tar::EntryType::GNULongName, tar::EntryType::XHeader] {
222 let bytes =
223 test_archives::extension_body_archive(("plugin.toml", MANIFEST), kind, HUGE_BODY);
224 assert_oversized(&scan_tarball(&bytes, SMALL_CAP).unwrap_err());
225 let tmp = tempfile::tempdir().unwrap();
226 assert_oversized(
227 &tarball::stage_tarball(&bytes, tmp.path(), SMALL_CAP, None)
228 .map(|staged| staged.name)
229 .unwrap_err(),
230 );
231 }
232 }
233
234 fn assert_name_too_long(err: &anyhow::Error) {
235 assert!(
236 matches!(
237 err.downcast_ref::<PluginInstallError>(),
238 Some(PluginInstallError::EntryNameTooLong { .. })
239 ),
240 "got: {err:#}"
241 );
242 }
243
244 #[test]
245 fn entry_names_longer_than_the_bound_are_rejected_before_any_copy() {
246 use codewhale_skill_install::bounded_tar::MAX_ENTRY_NAME_BYTES;
247 let archives = [
248 test_archives::long_name_archive(("plugin.toml", MANIFEST), MAX_ENTRY_NAME_BYTES + 1),
249 test_archives::long_name_archive(("plugin.toml", MANIFEST), 100 * 1024),
250 test_archives::long_link_target_archive(
251 ("plugin.toml", MANIFEST),
252 MAX_ENTRY_NAME_BYTES + 1,
253 ),
254 ];
255 for bytes in &archives {
256 assert_name_too_long(&scan_tarball(bytes, SMALL_CAP).unwrap_err());
257 let tmp = tempfile::tempdir().unwrap();
258 assert_name_too_long(
259 &tarball::stage_tarball(bytes, tmp.path(), SMALL_CAP, None)
260 .map(|staged| staged.name)
261 .unwrap_err(),
262 );
263 }
264 let at_bound =
265 test_archives::long_name_archive(("plugin.toml", MANIFEST), MAX_ENTRY_NAME_BYTES);
266 assert!(scan_tarball(&at_bound, SMALL_CAP).is_ok());
267 }
268
269 #[test]
270 fn scan_bounds_the_decoded_stream_for_many_empty_entries() {
271 let bytes = test_archives::empty_entries_archive(("plugin.toml", MANIFEST), 600);
272 assert_oversized(&scan_tarball(&bytes, SMALL_CAP).unwrap_err());
273 let few = test_archives::empty_entries_archive(("plugin.toml", MANIFEST), 20);
274 assert!(scan_tarball(&few, SMALL_CAP).is_ok());
275 }
276
277 #[test]
278 fn scan_requires_exactly_one_plugin_manifest_root() {
279 let zero = tarball(&[("repo-main/README.md", b"no manifest here")]);
280 let err = scan_tarball(&zero, DEFAULT_MAX_SIZE_BYTES).unwrap_err();
281 assert!(
282 matches!(
283 err.downcast_ref::<PluginInstallError>(),
284 Some(PluginInstallError::PluginTomlRoots(0))
285 ),
286 "got: {err:#}"
287 );
288
289 let manifest = b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n";
290 let two = tarball(&[
291 ("repo-main/plugin.toml", manifest),
292 ("repo-main/examples/other/plugin.toml", manifest),
293 ]);
294 let err = scan_tarball(&two, DEFAULT_MAX_SIZE_BYTES).unwrap_err();
295 assert!(
296 matches!(
297 err.downcast_ref::<PluginInstallError>(),
298 Some(PluginInstallError::PluginTomlRoots(2))
299 ),
300 "got: {err:#}"
301 );
302 }
303
304 #[test]
305 fn stage_tarball_accepts_a_kimi_manifest_root() {
306 let manifest = br#"{
307 "name": "kimi-archive",
308 "version": "1.0.0",
309 "description": "Kimi archive fixture"
310 }"#;
311 let bytes = tarball(&[("repo-main/kimi.plugin.json", manifest)]);
312 let tmp = tempfile::tempdir().unwrap();
313 let plugins = tmp.path().join("plugins");
314
315 let staged = stage_tarball(&bytes, &plugins, DEFAULT_MAX_SIZE_BYTES, None).unwrap();
316
317 assert_eq!(staged.name, "kimi-archive");
318 assert!(staged.staged_path.join("kimi.plugin.json").is_file());
319 }
320
321 #[test]
322 fn extract_rejects_symlinks_inside_the_bundle_subtree() {
323 let bytes = symlink_tarball(
324 "repo-main/evil-link",
325 "/etc/passwd",
326 "repo-main/plugin.toml",
327 );
328 let tmp = tempfile::tempdir().unwrap();
329 let plugins = tmp.path().join("plugins");
330 let err = stage_tarball(&bytes, &plugins, DEFAULT_MAX_SIZE_BYTES, None).unwrap_err();
331 assert!(
332 matches!(
333 err.downcast_ref::<PluginInstallError>(),
334 Some(PluginInstallError::SymlinkRejected)
335 ),
336 "got: {err:#}"
337 );
338 assert!(fs::read_dir(&plugins).unwrap().next().is_none());
339 }
340
341 #[test]
342 fn extract_ignores_entries_outside_the_bundle_subtree() {
343 let manifest = b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n";
344 let bytes = tarball(&[
345 ("repo-main/bundles/demo/plugin.toml", manifest),
346 (
347 "repo-main/bundles/demo/skills/a/SKILL.md",
348 b"---\nname: a\ndescription: a\n---\n",
349 ),
350 ("repo-main/other/plugin.toml.bak", b"ignored"),
351 ("repo-main/README.md", b"repo docs stay behind"),
352 ]);
353 let tmp = tempfile::tempdir().unwrap();
354 let plugins = tmp.path().join("plugins");
355 let staged = stage_tarball(&bytes, &plugins, DEFAULT_MAX_SIZE_BYTES, None).unwrap();
356 assert_eq!(staged.name, "demo");
357 assert!(staged.staged_path.join("plugin.toml").exists());
358 assert!(staged.staged_path.join("skills/a/SKILL.md").exists());
359 assert!(!staged.staged_path.join("README.md").exists());
360 assert!(!staged.staged_path.join("other").exists());
361 fs::remove_dir_all(&staged.staged_path).unwrap();
362 }
363
364 // ── local copy rules ──────────────────────────────────────────────────
365
366 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
367 async fn install_from_local_path_copies_and_marks_the_bundle() {
368 let tmp = tempfile::tempdir().unwrap();
369 let plugins = tmp.path().join("plugins");
370 let source = write_bundle(tmp.path(), "src/demo", "demo");
371 fs::create_dir_all(source.join("skills/hello")).unwrap();
372 fs::write(
373 source.join("skills/hello/SKILL.md"),
374 "---\nname: hello\ndescription: hi\n---\nbody\n",
375 )
376 .unwrap();
377
378 let outcome = install(
379 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
380 &plugins,
381 DEFAULT_MAX_SIZE_BYTES,
382 &allow_all(),
383 false,
384 &no_conflict(),
385 )
386 .await
387 .unwrap();
388 let PluginInstallOutcome::Installed(installed) = outcome else {
389 panic!("expected install to succeed");
390 };
391 assert_eq!(installed.name, "demo");
392 assert_eq!(installed.path, plugins.join("demo"));
393 assert!(installed.path.join("plugin.toml").exists());
394 assert!(installed.path.join("skills/hello/SKILL.md").exists());
395 let marker: serde_json::Value = serde_json::from_str(
396 &fs::read_to_string(installed.path.join(INSTALLED_FROM_MARKER)).unwrap(),
397 )
398 .unwrap();
399 assert!(marker["spec"].as_str().unwrap().starts_with("path:"));
400 // Local copies must not inherit a stale provenance marker.
401 assert_ne!(marker["spec"].as_str().unwrap(), "path:");
402 }
403
404 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
405 async fn exact_local_install_rejects_changed_bytes_before_placement() {
406 let tmp = tempfile::tempdir().unwrap();
407 let plugins = tmp.path().join("plugins");
408 let source = write_bundle(tmp.path(), "src/exact-demo", "exact-demo");
409 let expected = crate::manifest::PluginManifest::validate_from_path(&source.join("plugin.toml"))
410 .unwrap()
411 .content_hash;
412 fs::write(source.join("README.md"), "changed after review\n").unwrap();
413 let actual = crate::manifest::PluginManifest::validate_from_path(&source.join("plugin.toml"))
414 .unwrap()
415 .content_hash;
416
417 let error = install_with_expected_content_hash(
418 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
419 &plugins,
420 DEFAULT_MAX_SIZE_BYTES,
421 &allow_all(),
422 &no_conflict(),
423 &expected,
424 )
425 .await
426 .unwrap_err();
427
428 let mismatch = error.downcast_ref::<PluginContentMismatch>().unwrap();
429 assert_eq!(mismatch.expected, expected);
430 assert_eq!(mismatch.actual, actual);
431 assert_eq!(
432 error.to_string(),
433 format!(
434 "plugin source changed after review: expected content hash {expected}, copied bytes hash is {actual}; nothing was installed"
435 )
436 );
437 assert!(!plugins.join("exact-demo").exists());
438 assert!(
439 fs::read_dir(&plugins).unwrap().all(|entry| !entry
440 .unwrap()
441 .file_name()
442 .to_string_lossy()
443 .starts_with(".staging-")),
444 "hash mismatch must clean its private staging directory"
445 );
446 }
447
448 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
449 async fn install_imports_official_kimi_datasource_shape() {
450 let tmp = tempfile::tempdir().unwrap();
451 let plugins = tmp.path().join("plugins");
452 let source = tmp.path().join("src/kimi-datasource");
453 fs::create_dir_all(source.join("bin")).unwrap();
454 fs::write(
455 source.join("kimi.plugin.json"),
456 r#"{
457 "name": "kimi-datasource",
458 "version": "3.3.0",
459 "description": "Kimi datasource",
460 "mcpServers": {
461 "data": {
462 "command": "node",
463 "args": ["./bin/kimi-datasource.mjs"],
464 "cwd": "./"
465 }
466 },
467 "interface": {
468 "displayName": "Kimi Datasource",
469 "shortDescription": "Data tools",
470 "developerName": "Moonshot AI"
471 }
472 }"#,
473 )
474 .unwrap();
475 fs::write(
476 source.join("SKILL.md"),
477 "---\nname: kimi-datasource\ndescription: data\n---\n",
478 )
479 .unwrap();
480 fs::write(source.join("bin/kimi-datasource.mjs"), "// fixture\n").unwrap();
481
482 let outcome = install(
483 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
484 &plugins,
485 DEFAULT_MAX_SIZE_BYTES,
486 &allow_all(),
487 false,
488 &no_conflict(),
489 )
490 .await
491 .unwrap();
492 let PluginInstallOutcome::Installed(installed) = outcome else {
493 panic!("expected Kimi plugin install to succeed");
494 };
495 assert_eq!(installed.name, "kimi-datasource");
496 assert!(installed.path.join("kimi.plugin.json").exists());
497 let validated = crate::manifest::PluginManifest::validate_from_path(
498 &installed.path.join("kimi.plugin.json"),
499 )
500 .unwrap();
501 assert_eq!(validated.inventory.skills, 1);
502 assert_eq!(validated.inventory.mcp_servers, 1);
503 assert_eq!(validated.inventory.stdio_mcp_servers, 1);
504 assert_eq!(
505 validated.manifest.plugin.display_name.as_deref(),
506 Some("Kimi Datasource")
507 );
508 }
509
510 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
511 async fn install_imports_managed_kimi_cu_shape_with_platform_and_tool_filters() {
512 let tmp = tempfile::tempdir().unwrap();
513 let plugins = tmp.path().join("plugins");
514 let source = tmp.path().join("src/kimi-cu");
515 fs::create_dir_all(source.join("skills/kimi-cu")).unwrap();
516 fs::create_dir_all(source.join("bin")).unwrap();
517 fs::write(
518 source.join("kimi.plugin.json"),
519 r#"{
520 "name": "kimi-cu",
521 "version": "0.5.4",
522 "description": "Computer-use wiring",
523 "license": "Proprietary",
524 "skills": "./skills/",
525 "mcpServers": {
526 "kimi-cu": {
527 "command": "sh",
528 "args": ["./bin/kimi-cu-mcp"],
529 "cwd": "./",
530 "enabledTools": ["computer_get_state", "computer_click"]
531 }
532 },
533 "interface": {
534 "displayName": "Kimi Computer Use",
535 "shortDescription": "Computer control",
536 "longDescription": "Requires the external Kimi runtime and permissions.",
537 "developerName": "Moonshot AI",
538 "iconUrl": "https://example.invalid/kimi-cu.png",
539 "category": "Developer Tools",
540 "hostKind": "local",
541 "platforms": ["macos"],
542 "mcpOverrides": {
543 "mac": {
544 "displayName": "Kimi Computer Use for macOS",
545 "iconUrl": "https://example.invalid/kimi-cu-mac.png"
546 }
547 }
548 }
549 }"#,
550 )
551 .unwrap();
552 fs::write(
553 source.join("skills/kimi-cu/SKILL.md"),
554 "---\nname: kimi-cu\ndescription: computer use\n---\n",
555 )
556 .unwrap();
557 fs::write(source.join("bin/kimi-cu-mcp"), "#!/bin/sh\n").unwrap();
558
559 let outcome = install(
560 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
561 &plugins,
562 DEFAULT_MAX_SIZE_BYTES,
563 &allow_all(),
564 false,
565 &no_conflict(),
566 )
567 .await
568 .unwrap();
569 let PluginInstallOutcome::Installed(installed) = outcome else {
570 panic!("expected managed Kimi CU plugin install to succeed");
571 };
572 let validated = crate::manifest::PluginManifest::validate_from_path(
573 &installed.path.join("kimi.plugin.json"),
574 )
575 .unwrap();
576 assert_eq!(validated.inventory.skills, 1);
577 assert_eq!(validated.inventory.mcp_servers, 1);
578 assert_eq!(validated.inventory.stdio_mcp_servers, 1);
579 assert_eq!(
580 validated.manifest.plugin.license.as_deref(),
581 Some("Proprietary")
582 );
583 assert_eq!(
584 validated
585 .manifest
586 .when
587 .as_ref()
588 .and_then(|when| when.os.as_ref()),
589 Some(&vec!["macos".to_string()])
590 );
591 assert_eq!(validated.applicable, cfg!(target_os = "macos"));
592 let server = validated
593 .manifest
594 .mcp_servers
595 .as_ref()
596 .and_then(|servers| servers.get("kimi-cu"))
597 .unwrap();
598 assert_eq!(
599 server.enabled_tools,
600 ["computer_get_state", "computer_click"]
601 );
602 }
603
604 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
605 async fn install_imports_official_kimi_webbridge_shape() {
606 let tmp = tempfile::tempdir().unwrap();
607 let plugins = tmp.path().join("plugins");
608 let source = tmp.path().join("src/kimi-webbridge");
609 fs::create_dir_all(source.join("skills/kimi-webbridge")).unwrap();
610 fs::write(
611 source.join("kimi.plugin.json"),
612 r#"{
613 "$schema": "https://kimi.com/schemas/kimi.plugin.schema.json",
614 "name": "kimi-webbridge",
615 "version": "1.11.3",
616 "description": "Control the real browser",
617 "keywords": ["browser", "automation"],
618 "author": "Moonshot AI",
619 "license": "Proprietary",
620 "skills": "./skills/",
621 "interface": {
622 "displayName": "Kimi WebBridge",
623 "shortDescription": "Browser control",
624 "longDescription": "Requires the local daemon and browser extension.",
625 "developerName": "Moonshot AI",
626 "websiteURL": "https://www.kimi.com/features/webbridge"
627 }
628 }"#,
629 )
630 .unwrap();
631 fs::write(
632 source.join("skills/kimi-webbridge/SKILL.md"),
633 "---\nname: kimi-webbridge\ndescription: browser\n---\n",
634 )
635 .unwrap();
636
637 let outcome = install(
638 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
639 &plugins,
640 DEFAULT_MAX_SIZE_BYTES,
641 &allow_all(),
642 false,
643 &no_conflict(),
644 )
645 .await
646 .unwrap();
647 let PluginInstallOutcome::Installed(installed) = outcome else {
648 panic!("expected Kimi plugin install to succeed");
649 };
650 let validated = crate::manifest::PluginManifest::validate_from_path(
651 &installed.path.join("kimi.plugin.json"),
652 )
653 .unwrap();
654 assert_eq!(validated.inventory.skills, 1);
655 assert_eq!(validated.inventory.mcp_servers, 0);
656 assert_eq!(
657 validated.manifest.plugin.author.as_deref(),
658 Some("Moonshot AI")
659 );
660 }
661
662 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
663 async fn kimi_import_rejects_unsupported_runtime_fields() {
664 let tmp = tempfile::tempdir().unwrap();
665 let plugins = tmp.path().join("plugins");
666 let source = tmp.path().join("src/kimi-hooks");
667 fs::create_dir_all(&source).unwrap();
668 fs::write(
669 source.join("kimi.plugin.json"),
670 r#"{
671 "name": "kimi-hooks",
672 "version": "1.0.0",
673 "hooks": [{"event":"PreToolUse","command":"node ./hook.mjs"}]
674 }"#,
675 )
676 .unwrap();
677
678 let error = install(
679 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
680 &plugins,
681 DEFAULT_MAX_SIZE_BYTES,
682 &allow_all(),
683 false,
684 &no_conflict(),
685 )
686 .await
687 .unwrap_err();
688 assert!(
689 format!("{error:#}").contains("unknown field `hooks`"),
690 "unsupported Kimi runtime fields must fail closed: {error:#}"
691 );
692 assert!(!plugins.join("kimi-hooks").exists());
693 }
694
695 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
696 async fn kimi_import_rejects_unknown_mcp_executable_fields() {
697 let tmp = tempfile::tempdir().unwrap();
698 let plugins = tmp.path().join("plugins");
699 let source = tmp.path().join("src/kimi-unknown-exec");
700 fs::create_dir_all(&source).unwrap();
701 fs::write(
702 source.join("kimi.plugin.json"),
703 r#"{
704 "name": "kimi-unknown-exec",
705 "version": "1.0.0",
706 "mcpServers": {
707 "unknown": {
708 "command": "node",
709 "args": ["server.mjs"],
710 "postInstallCommand": "node install.mjs"
711 }
712 }
713 }"#,
714 )
715 .unwrap();
716
717 let error = install(
718 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
719 &plugins,
720 DEFAULT_MAX_SIZE_BYTES,
721 &allow_all(),
722 false,
723 &no_conflict(),
724 )
725 .await
726 .unwrap_err();
727 assert!(
728 format!("{error:#}").contains("unknown field `postInstallCommand`"),
729 "unknown Kimi executable fields must fail closed: {error:#}"
730 );
731 assert!(!plugins.join("kimi-unknown-exec").exists());
732 }
733
734 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
735 async fn install_refuses_to_overwrite_a_hand_placed_bundle() {
736 let tmp = tempfile::tempdir().unwrap();
737 let plugins = tmp.path().join("plugins");
738 write_bundle(&plugins, "demo", "demo");
739 let source = write_bundle(tmp.path(), "src/demo", "demo");
740
741 let err = install(
742 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
743 &plugins,
744 DEFAULT_MAX_SIZE_BYTES,
745 &allow_all(),
746 false,
747 &no_conflict(),
748 )
749 .await
750 .unwrap_err();
751 assert!(
752 matches!(
753 err.downcast_ref::<PluginInstallError>(),
754 Some(PluginInstallError::NotInstalledHere(_))
755 ),
756 "hand-placed bundle must be protected, got: {err:#}"
757 );
758 assert!(
759 !plugins.join("demo/skills").exists(),
760 "no partial overwrite"
761 );
762
763 // A bundle that *was* installed here gets the AlreadyInstalled hint.
764 fs::write(plugins.join("demo").join(INSTALLED_FROM_MARKER), "{}").unwrap();
765 let err = install(
766 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
767 &plugins,
768 DEFAULT_MAX_SIZE_BYTES,
769 &allow_all(),
770 false,
771 &no_conflict(),
772 )
773 .await
774 .unwrap_err();
775 assert!(
776 matches!(
777 err.downcast_ref::<PluginInstallError>(),
778 Some(PluginInstallError::AlreadyInstalled(_))
779 ),
780 "got: {err:#}"
781 );
782 }
783
784 #[cfg(unix)]
785 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
786 async fn local_install_rejects_symlinks_in_the_source() {
787 let tmp = tempfile::tempdir().unwrap();
788 let plugins = tmp.path().join("plugins");
789 let source = write_bundle(tmp.path(), "src/demo", "demo");
790 std::os::unix::fs::symlink("/etc/passwd", source.join("linked")).unwrap();
791
792 let err = install(
793 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
794 &plugins,
795 DEFAULT_MAX_SIZE_BYTES,
796 &allow_all(),
797 false,
798 &no_conflict(),
799 )
800 .await
801 .unwrap_err();
802 // The bundle validator rejects symlinked content before any copy runs.
803 assert!(format!("{err:#}").contains("symbolic link"), "got: {err:#}");
804 assert!(!plugins.join("demo").exists());
805 }
806
807 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
808 async fn install_refuses_sources_inside_the_plugins_root() {
809 let tmp = tempfile::tempdir().unwrap();
810 let plugins = tmp.path().join("plugins");
811 let nested = write_bundle(&plugins, "demo", "demo");
812 let err = install(
813 PluginInstallSource::parse(nested.to_str().unwrap()).unwrap(),
814 &plugins,
815 DEFAULT_MAX_SIZE_BYTES,
816 &allow_all(),
817 false,
818 &no_conflict(),
819 )
820 .await
821 .unwrap_err();
822 assert!(format!("{err:#}").contains("inside the user plugins directory"));
823 }
824
825 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
826 async fn install_enforces_the_name_conflict_hook() {
827 let tmp = tempfile::tempdir().unwrap();
828 let plugins = tmp.path().join("plugins");
829 let source = write_bundle(tmp.path(), "src/demo", "demo");
830 let err = install(
831 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
832 &plugins,
833 DEFAULT_MAX_SIZE_BYTES,
834 &allow_all(),
835 false,
836 &|name| Some(format!("name '{name}' is shadowed by a builtin bundle")),
837 )
838 .await
839 .unwrap_err();
840 assert!(format!("{err:#}").contains("shadowed by a builtin bundle"));
841 assert!(err.downcast_ref::<PluginNameConflict>().is_some());
842 assert!(!plugins.join("demo").exists());
843 // The staging dir must be cleaned up on the conflict path.
844 assert!(
845 !fs::read_dir(&plugins)
846 .map(|mut entries| entries.any(|entry| entry
847 .unwrap()
848 .file_name()
849 .to_string_lossy()
850 .starts_with(".staging-")))
851 .unwrap_or(false)
852 );
853 }
854
855 // ── update / uninstall ────────────────────────────────────────────────
856
857 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
858 async fn update_refuses_missing_markers() {
859 let tmp = tempfile::tempdir().unwrap();
860 let plugins = tmp.path().join("plugins");
861 write_bundle(&plugins, "hand", "hand");
862 let err = update("hand", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
863 .await
864 .unwrap_err();
865 assert!(
866 matches!(
867 err.downcast_ref::<PluginInstallError>(),
868 Some(PluginInstallError::NotInstalledHere(_))
869 ),
870 "got: {err:#}"
871 );
872 }
873
874 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
875 async fn local_update_reuses_staging_and_preserves_the_installed_bundle_on_failure() {
876 let tmp = tempfile::tempdir().unwrap();
877 let plugins = tmp.path().join("plugins");
878 let source = write_bundle(tmp.path(), "src/demo", "demo");
879 fs::write(source.join("data.txt"), b"v1").unwrap();
880 install(
881 PluginInstallSource::LocalPath(source.clone()),
882 &plugins,
883 DEFAULT_MAX_SIZE_BYTES,
884 &allow_all(),
885 false,
886 &no_conflict(),
887 )
888 .await
889 .unwrap();
890 let target = plugins.join("demo");
891 let original_marker = fs::read(target.join(INSTALLED_FROM_MARKER)).unwrap();
892 let original_json: serde_json::Value = serde_json::from_slice(&original_marker).unwrap();
893 let mut prev_nonce = original_json["install_nonce"]
894 .as_str()
895 .filter(|nonce| !nonce.is_empty())
896 .expect("install writes an install_nonce")
897 .to_string();
898 assert!(matches!(
899 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
900 .await
901 .unwrap(),
902 PluginUpdateResult::NoChange
903 ));
904 assert_eq!(
905 fs::read(target.join(INSTALLED_FROM_MARKER)).unwrap(),
906 original_marker
907 );
908
909 for altered in [Some(b"altered".as_slice()), None] {
910 if let Some(bytes) = altered {
911 fs::write(target.join("data.txt"), bytes).unwrap();
912 } else {
913 fs::remove_file(target.join("data.txt")).unwrap();
914 }
915 assert!(matches!(
916 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
917 .await
918 .unwrap(),
919 PluginUpdateResult::Updated(_)
920 ));
921 assert_eq!(fs::read(target.join("data.txt")).unwrap(), b"v1");
922 let mut repaired_json: serde_json::Value =
923 serde_json::from_slice(&fs::read(target.join(INSTALLED_FROM_MARKER)).unwrap()).unwrap();
924 let next_nonce = repaired_json["install_nonce"]
925 .as_str()
926 .filter(|nonce| !nonce.is_empty())
927 .expect("repair writes a fresh install_nonce")
928 .to_string();
929 assert_ne!(next_nonce, prev_nonce);
930 prev_nonce = next_nonce;
931 repaired_json["install_nonce"] = original_json["install_nonce"].clone();
932 assert_eq!(repaired_json, original_json);
933 }
934
935 fs::write(source.join("data.txt"), b"v2").unwrap();
936 let PluginUpdateResult::Updated(updated) =
937 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
938 .await
939 .unwrap()
940 else {
941 panic!("changed local source must update through the existing installer");
942 };
943 assert_eq!(fs::read(updated.path.join("data.txt")).unwrap(), b"v2");
944 let updated_marker = fs::read(target.join(INSTALLED_FROM_MARKER)).unwrap();
945 assert_ne!(updated_marker, original_marker);
946 assert!(matches!(
947 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
948 .await
949 .unwrap(),
950 PluginUpdateResult::NoChange
951 ));
952
953 let manifest = fs::read(source.join("plugin.toml")).unwrap();
954 fs::write(
955 source.join("plugin.toml"),
956 b"schema_version = 1\n[plugin]\nname = \"other\"\nversion = \"2.0.0\"\n",
957 )
958 .unwrap();
959 let error = update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
960 .await
961 .unwrap_err();
962 assert!(error.downcast_ref::<PluginNameConflict>().is_some());
963 assert!(!plugins.join("other").exists());
964 fs::write(source.join("plugin.toml"), b"malformed = [").unwrap();
965 assert!(
966 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
967 .await
968 .is_err()
969 );
970 fs::write(source.join("plugin.toml"), manifest).unwrap();
971 fs::remove_dir_all(&source).unwrap();
972 assert!(
973 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
974 .await
975 .is_err()
976 );
977 assert_eq!(fs::read(target.join("data.txt")).unwrap(), b"v2");
978 assert_eq!(
979 fs::read(target.join(INSTALLED_FROM_MARKER)).unwrap(),
980 updated_marker
981 );
982 assert_eq!(
983 fs::read_dir(&plugins).unwrap().count(),
984 1,
985 "no staging or backup residue"
986 );
987 }
988
989 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
990 async fn uninstall_requires_the_marker_and_removes_the_bundle() {
991 let tmp = tempfile::tempdir().unwrap();
992 let plugins = tmp.path().join("plugins");
993 let source = write_bundle(tmp.path(), "src/demo", "demo");
994 install(
995 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
996 &plugins,
997 DEFAULT_MAX_SIZE_BYTES,
998 &allow_all(),
999 false,
1000 &no_conflict(),
1001 )
1002 .await
1003 .unwrap();
1004
1005 uninstall("demo", &plugins).unwrap();
1006 assert!(!plugins.join("demo").exists());
1007
1008 write_bundle(&plugins, "hand", "hand");
1009 let err = uninstall("hand", &plugins).unwrap_err();
1010 assert!(
1011 matches!(
1012 err.downcast_ref::<PluginInstallError>(),
1013 Some(PluginInstallError::NotInstalledHere(_))
1014 ),
1015 "got: {err:#}"
1016 );
1017 assert!(plugins.join("hand").exists(), "hand-placed bundle survives");
1018 assert!(uninstall("missing", &plugins).is_err());
1019 }
1020
1021 #[cfg(unix)]
1022 #[test]
1023 fn uninstall_rejects_symlink_targets_escaping_the_plugins_root() {
1024 let tmp = tempfile::tempdir().unwrap();
1025 let plugins = tmp.path().join("plugins");
1026 let outside = tmp.path().join("outside");
1027 fs::create_dir_all(&plugins).unwrap();
1028 fs::create_dir_all(&outside).unwrap();
1029 fs::write(outside.join(INSTALLED_FROM_MARKER), "{}").unwrap();
1030 std::os::unix::fs::symlink(&outside, plugins.join("linked")).unwrap();
1031
1032 let err = uninstall("linked", &plugins).unwrap_err();
1033 assert!(format!("{err:#}").contains("escapes plugins directory"));
1034 assert!(outside.exists());
1035 }
1036
1037 // ── source parsing ────────────────────────────────────────────────────
1038
1039 #[test]
1040 fn parse_routes_remote_and_local_specs() {
1041 assert_eq!(
1042 PluginInstallSource::parse("github:owner/repo").unwrap(),
1043 PluginInstallSource::Remote(InstallSource::GitHubRepo("owner/repo".into()))
1044 );
1045 assert_eq!(
1046 PluginInstallSource::parse("https://example.com/p.tar.gz").unwrap(),
1047 PluginInstallSource::Remote(InstallSource::DirectUrl(
1048 "https://example.com/p.tar.gz".into()
1049 ))
1050 );
1051 assert_eq!(
1052 PluginInstallSource::parse("./bundles/demo").unwrap(),
1053 PluginInstallSource::LocalPath(PathBuf::from("./bundles/demo"))
1054 );
1055 assert_eq!(
1056 PluginInstallSource::parse("path:/opt/demo").unwrap(),
1057 PluginInstallSource::LocalPath(PathBuf::from("/opt/demo"))
1058 );
1059 assert!(PluginInstallSource::parse("").is_err());
1060 assert!(PluginInstallSource::parse(" ").is_err());
1061 assert!(PluginInstallSource::parse("path:").is_err());
1062 assert_eq!(
1063 PluginInstallSource::parse("git:github.com/owner/repo").unwrap(),
1064 PluginInstallSource::Remote(InstallSource::GitHubRepo("owner/repo".into()))
1065 );
1066 for (spec, url) in [
1067 (
1068 "git:github.com/owner/repo@v1.2.3",
1069 "https://github.com/owner/repo/archive/v1.2.3.tar.gz",
1070 ),
1071 (
1072 "npm:@owner/plugin@1.2.3",
1073 "https://registry.npmjs.org/@owner/plugin/-/plugin-1.2.3.tgz",
1074 ),
1075 (
1076 "npm:plugin@1.2.3-alpha.1",
1077 "https://registry.npmjs.org/plugin/-/plugin-1.2.3-alpha.1.tgz",
1078 ),
1079 ] {
1080 let source = PluginInstallSource::parse(spec).unwrap();
1081 assert_eq!(
1082 source,
1083 PluginInstallSource::Remote(InstallSource::DirectUrl(url.into()))
1084 );
1085 assert_eq!(
1086 PluginInstallSource::parse(&plugin_spec_string(&source, None)).unwrap(),
1087 source
1088 );
1089 }
1090 for spec in [
1091 "git:gitlab.com/owner/repo",
1092 "git:github.com/owner/repo@../x",
1093 "git:github.com/owner/repo@",
1094 "npm:plugin",
1095 "npm:plugin@latest",
1096 "npm:plugin@^1.2.3",
1097 "npm:@owner/../plugin@1.2.3",
1098 "npm:../plugin@1.2.3",
1099 ] {
1100 assert!(PluginInstallSource::parse(spec).is_err(), "{spec}");
1101 }
1102 }
1103
1104 // ── remote fetch against a loopback server ────────────────────────────
1105
1106 /// Serve each body once, in order, over plain loopback HTTP.
1107 fn serve_bodies(bodies: Vec<Vec<u8>>) -> String {
1108 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1109 let port = listener.local_addr().unwrap().port();
1110 std::thread::spawn(move || {
1111 for body in bodies {
1112 let Ok((mut stream, _)) = listener.accept() else {
1113 return;
1114 };
1115 // Consume the request headers before responding.
1116 let mut request = Vec::new();
1117 let mut buf = [0_u8; 1024];
1118 loop {
1119 use std::io::Read as _;
1120 let read = stream.read(&mut buf).unwrap_or(0);
1121 if read == 0 {
1122 break;
1123 }
1124 request.extend_from_slice(&buf[..read]);
1125 if request.windows(4).any(|window| window == b"\r\n\r\n") {
1126 break;
1127 }
1128 }
1129 use std::io::Write as _;
1130 let head = format!(
1131 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
1132 body.len()
1133 );
1134 let _ = stream.write_all(head.as_bytes());
1135 let _ = stream.write_all(&body);
1136 let _ = stream.flush();
1137 }
1138 });
1139 format!("http://127.0.0.1:{port}/plugin.tar.gz")
1140 }
1141
1142 fn loopback_policy() -> NetworkPolicy {
1143 NetworkPolicy {
1144 allow: vec!["127.0.0.1".to_string()],
1145 ..Default::default()
1146 }
1147 }
1148
1149 fn remote_bundle_bytes(name: &str, extra: &[u8]) -> Vec<u8> {
1150 let manifest = format!("schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n");
1151 tarball(&[
1152 ("repo-main/plugin.toml", manifest.as_bytes()),
1153 ("repo-main/data.txt", extra),
1154 ])
1155 }
1156
1157 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1158 async fn remote_update_with_unchanged_archive_repairs_altered_install() {
1159 let tmp = tempfile::tempdir().unwrap();
1160 let plugins = tmp.path().join("plugins");
1161 let archive = tarball(&[
1162 (
1163 "repo-main/plugin.toml",
1164 b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n",
1165 ),
1166 ("repo-main/data.txt", b"v1"),
1167 ]);
1168 let url = serve_bodies(vec![archive.clone(), archive.clone(), archive]);
1169 let outcome = install(
1170 PluginInstallSource::parse(&url).unwrap(),
1171 &plugins,
1172 DEFAULT_MAX_SIZE_BYTES,
1173 &loopback_policy(),
1174 false,
1175 &no_conflict(),
1176 )
1177 .await
1178 .unwrap();
1179 assert!(matches!(outcome, PluginInstallOutcome::Installed(_)));
1180 fs::write(plugins.join("demo/data.txt"), b"tampered").unwrap();
1181 assert!(matches!(
1182 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1183 .await
1184 .unwrap(),
1185 PluginUpdateResult::Updated(_)
1186 ));
1187 assert_eq!(fs::read(plugins.join("demo/data.txt")).unwrap(), b"v1");
1188 assert!(matches!(
1189 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1190 .await
1191 .unwrap(),
1192 PluginUpdateResult::NoChange
1193 ));
1194 }
1195
1196 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1197 async fn dsh_update_with_unchanged_package_repairs_altered_install() {
1198 let tmp = tempfile::tempdir().unwrap();
1199 let plugins = tmp.path().join("plugins");
1200 let pkg = write_dsh_base_package(
1201 &tmp.path().join("dsh-repair"),
1202 serde_json::json!({
1203 "name": "dsh-repair",
1204 "version": "1.0.0",
1205 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
1206 }),
1207 "[]\n",
1208 );
1209 fs::create_dir_all(pkg.join("commands")).unwrap();
1210 fs::write(pkg.join("commands/hello.md"), "hello v1\n").unwrap();
1211 fs::write(
1212 pkg.join("plugin.json"),
1213 serde_json::json!({
1214 "$schema": "https://agent-plugins.org/schemas/plugin.json",
1215 "name": "dsh-repair",
1216 "version": "1.0.0",
1217 "extensions": {
1218 "net.codewhale": {
1219 "commands": {"path": "commands"}
1220 }
1221 }
1222 })
1223 .to_string(),
1224 )
1225 .unwrap();
1226
1227 let outcome = install(
1228 PluginInstallSource::parse(pkg.to_str().unwrap()).unwrap(),
1229 &plugins,
1230 DEFAULT_MAX_SIZE_BYTES,
1231 &allow_all(),
1232 false,
1233 &no_conflict(),
1234 )
1235 .await
1236 .unwrap();
1237 assert!(matches!(outcome, PluginInstallOutcome::Installed(_)));
1238
1239 let installed_cmd = plugins.join("dsh-repair/commands/hello.md");
1240 fs::write(&installed_cmd, "tampered\n").unwrap();
1241 assert!(matches!(
1242 update("dsh-repair", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
1243 .await
1244 .unwrap(),
1245 PluginUpdateResult::Updated(_)
1246 ));
1247 assert_eq!(fs::read_to_string(&installed_cmd).unwrap(), "hello v1\n");
1248 assert!(matches!(
1249 update("dsh-repair", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
1250 .await
1251 .unwrap(),
1252 PluginUpdateResult::NoChange
1253 ));
1254 }
1255
1256 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1257 async fn marketplace_archive_selects_only_requested_bundle_and_updates_same_source() {
1258 let tmp = tempfile::tempdir().unwrap();
1259 let plugins = tmp.path().join("plugins");
1260 let make_archive = |content: &[u8], name: &str| {
1261 tarball(&[
1262 (
1263 "repo-main/plugins/demo/plugin.toml",
1264 format!("schema_version = 1\n[plugin]\nname = {name:?}\nversion = \"1.0.0\"\n")
1265 .as_bytes(),
1266 ),
1267 ("repo-main/plugins/demo/data.txt", content),
1268 (
1269 "repo-main/plugins/other/plugin.toml",
1270 b"schema_version = 1\n[plugin]\nname = \"other\"\nversion = \"1.0.0\"\n",
1271 ),
1272 ])
1273 };
1274 let v1 = make_archive(b"v1", "demo");
1275 let v2 = make_archive(b"v2", "demo");
1276 let url = format!(
1277 "{}#path=plugins/demo",
1278 serve_bodies(vec![v1.clone(), v1, v2, make_archive(b"renamed", "other")])
1279 );
1280 let outcome = install(
1281 PluginInstallSource::parse(&url).unwrap(),
1282 &plugins,
1283 DEFAULT_MAX_SIZE_BYTES,
1284 &loopback_policy(),
1285 false,
1286 &no_conflict(),
1287 )
1288 .await
1289 .unwrap();
1290 assert!(matches!(outcome, PluginInstallOutcome::Installed(_)));
1291 assert!(!plugins.join("other").exists());
1292 assert_eq!(fs::read(plugins.join("demo/data.txt")).unwrap(), b"v1");
1293 assert!(matches!(
1294 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1295 .await
1296 .unwrap(),
1297 PluginUpdateResult::NoChange
1298 ));
1299 assert!(matches!(
1300 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1301 .await
1302 .unwrap(),
1303 PluginUpdateResult::Updated(_)
1304 ));
1305 assert_eq!(fs::read(plugins.join("demo/data.txt")).unwrap(), b"v2");
1306 let marker: InstalledFromMarker =
1307 serde_json::from_str(&fs::read_to_string(plugins.join("demo/.installed-from")).unwrap())
1308 .unwrap();
1309 assert_eq!(marker.spec, url);
1310 assert!(
1311 update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1312 .await
1313 .is_err()
1314 );
1315 assert_eq!(fs::read(plugins.join("demo/data.txt")).unwrap(), b"v2");
1316 assert!(!plugins.join("other").exists());
1317 }
1318
1319 #[test]
1320 fn archive_bundle_selector_rejects_traversal_missing_and_ambiguous_roots() {
1321 for selector in [
1322 "",
1323 "/plugins/demo",
1324 "../demo",
1325 "plugins/../demo",
1326 "plugins//demo",
1327 "plugins/%2e%2e",
1328 "plugins\\demo",
1329 ] {
1330 assert!(
1331 PluginInstallSource::parse(&format!(
1332 "https://example.test/repo.tar.gz#path={selector}"
1333 ))
1334 .is_err()
1335 );
1336 }
1337 let tmp = tempfile::tempdir().unwrap();
1338 let manifest = b"schema_version = 1\n[plugin]\nname = \"demo\"\nversion = \"1.0.0\"\n";
1339 let bytes = tarball(&[
1340 ("a/plugins/demo/plugin.toml", manifest),
1341 ("b/plugins/demo/plugin.toml", manifest),
1342 ]);
1343 for path in ["plugins/demo", "plugins/missing"] {
1344 assert!(stage_tarball(&bytes, tmp.path(), DEFAULT_MAX_SIZE_BYTES, Some(path)).is_err());
1345 }
1346 let linked = symlink_tarball(
1347 "repo/plugins/demo/link",
1348 "/tmp",
1349 "repo/plugins/demo/plugin.toml",
1350 );
1351 assert!(
1352 stage_tarball(
1353 &linked,
1354 tmp.path(),
1355 DEFAULT_MAX_SIZE_BYTES,
1356 Some("plugins/demo")
1357 )
1358 .is_err()
1359 );
1360 assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 0);
1361 }
1362
1363 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1364 async fn update_is_a_digest_noop_until_the_upstream_changes() {
1365 let tmp = tempfile::tempdir().unwrap();
1366 let plugins = tmp.path().join("plugins");
1367 let v1 = remote_bundle_bytes("demo", b"v1");
1368 let v2 = remote_bundle_bytes("demo", b"v2-changed");
1369 // install, update (same bytes → no-op), update (new bytes → swap).
1370 let url = serve_bodies(vec![v1.clone(), v1.clone(), v2.clone()]);
1371
1372 let outcome = install(
1373 PluginInstallSource::parse(&url).unwrap(),
1374 &plugins,
1375 DEFAULT_MAX_SIZE_BYTES,
1376 &loopback_policy(),
1377 false,
1378 &no_conflict(),
1379 )
1380 .await
1381 .unwrap();
1382 let PluginInstallOutcome::Installed(installed) = outcome else {
1383 panic!("expected install to succeed");
1384 };
1385 assert_eq!(installed.name, "demo");
1386 assert_eq!(
1387 fs::read(plugins.join("demo/data.txt")).unwrap(),
1388 b"v1".to_vec()
1389 );
1390
1391 let no_change = update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1392 .await
1393 .unwrap();
1394 assert!(
1395 matches!(no_change, PluginUpdateResult::NoChange),
1396 "identical upstream bytes must be a digest no-op"
1397 );
1398 assert_eq!(
1399 fs::read(plugins.join("demo/data.txt")).unwrap(),
1400 b"v1".to_vec()
1401 );
1402
1403 let changed = update("demo", &plugins, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
1404 .await
1405 .unwrap();
1406 let PluginUpdateResult::Updated(updated) = changed else {
1407 panic!("changed upstream bytes must swap the bundle");
1408 };
1409 assert_eq!(
1410 fs::read(updated.path.join("data.txt")).unwrap(),
1411 b"v2-changed".to_vec()
1412 );
1413 // The marker records the new checksum, so a following update against
1414 // the same bytes would be a no-op again.
1415 let marker: serde_json::Value = serde_json::from_str(
1416 &fs::read_to_string(updated.path.join(INSTALLED_FROM_MARKER)).unwrap(),
1417 )
1418 .unwrap();
1419 assert_eq!(marker["source_checksum"].as_str().unwrap(), sha256_hex(&v2));
1420 }
1421
1422 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1423 async fn remote_install_surfaces_policy_gates_without_touching_disk() {
1424 let tmp = tempfile::tempdir().unwrap();
1425 let plugins = tmp.path().join("plugins");
1426
1427 // Default policy prompts for unknown hosts.
1428 let outcome = install(
1429 PluginInstallSource::parse("https://plugin.example.invalid/x.tar.gz").unwrap(),
1430 &plugins,
1431 DEFAULT_MAX_SIZE_BYTES,
1432 &NetworkPolicy::default(),
1433 false,
1434 &no_conflict(),
1435 )
1436 .await
1437 .unwrap();
1438 assert!(
1439 matches!(
1440 outcome,
1441 PluginInstallOutcome::NeedsApproval(ref host) if host == "plugin.example.invalid"
1442 ),
1443 "got: {outcome:?}"
1444 );
1445
1446 let denied = NetworkPolicy {
1447 deny: vec!["plugin.example.invalid".to_string()],
1448 ..Default::default()
1449 };
1450 let outcome = install(
1451 PluginInstallSource::parse("https://plugin.example.invalid/x.tar.gz").unwrap(),
1452 &plugins,
1453 DEFAULT_MAX_SIZE_BYTES,
1454 &denied,
1455 false,
1456 &no_conflict(),
1457 )
1458 .await
1459 .unwrap();
1460 assert!(
1461 matches!(outcome, PluginInstallOutcome::NetworkDenied(_)),
1462 "got: {outcome:?}"
1463 );
1464 assert!(!plugins.join("demo").exists());
1465 }
1466
1467 /// Same manifest/MCP shape as the official Linear and GitHub marketplace
1468 /// bundles: metadata is nested, components and the flat MCP map are at root.
1469 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1470 async fn install_claude_bundle_keeps_root_components_and_review_hash() {
1471 let tmp = tempfile::tempdir().unwrap();
1472 let source = tmp.path().join("source");
1473 fs::create_dir_all(source.join(".claude-plugin")).unwrap();
1474 fs::create_dir_all(source.join("skills/triage")).unwrap();
1475 fs::write(
1476 source.join(".claude-plugin/plugin.json"),
1477 r#"{"name":"linear","description":"Issue tracking","author":{"name":"Linear"},"skills":"./skills/"}"#,
1478 )
1479 .unwrap();
1480 fs::write(
1481 source.join(".mcp.json"),
1482 r#"{"linear":{"type":"http","url":"https://mcp.linear.app/mcp"}}"#,
1483 )
1484 .unwrap();
1485 fs::write(
1486 source.join("skills/triage/SKILL.md"),
1487 "---\nname: triage\ndescription: Issue triage\n---\nRead issues.\n",
1488 )
1489 .unwrap();
1490 let plugins = tmp.path().join("plugins");
1491 let outcome = install(
1492 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
1493 &plugins,
1494 DEFAULT_MAX_SIZE_BYTES,
1495 &allow_all(),
1496 false,
1497 &no_conflict(),
1498 )
1499 .await
1500 .unwrap();
1501 let PluginInstallOutcome::Installed(installed) = outcome else {
1502 panic!("expected install")
1503 };
1504 let path = installed.path.join(".claude-plugin/plugin.json");
1505 let validated = crate::manifest::PluginManifest::validate_from_path(&path).unwrap();
1506 assert_eq!(
1507 validated.canonical_root,
1508 installed.path.canonicalize().unwrap()
1509 );
1510 assert_eq!(validated.inventory.skills, 1);
1511 assert_eq!(validated.inventory.mcp_servers, 1);
1512 let server = &validated.manifest.mcp_servers.as_ref().unwrap()["linear"];
1513 assert_eq!(server.url.as_deref(), Some("https://mcp.linear.app/mcp"));
1514 assert!(server.command.is_none());
1515 assert!(
1516 server.transport.is_none(),
1517 "Streamable HTTP is the existing default HTTP transport"
1518 );
1519 fs::write(
1520 installed.path.join(".mcp.json"),
1521 r#"{"linear":{"type":"http","url":"https://changed.invalid/mcp"}}"#,
1522 )
1523 .unwrap();
1524 let changed = crate::manifest::PluginManifest::validate_from_path(&path).unwrap();
1525 assert_ne!(validated.content_hash, changed.content_hash);
1526 assert_ne!(validated.capability_hash, changed.capability_hash);
1527 }
1528
1529 #[test]
1530 fn claude_archive_stages_the_bundle_outside_metadata_directory() {
1531 let bytes = tarball(&[
1532 ("repo-main/.claude-plugin/plugin.json", br#"{"name":"github"}"#),
1533 ("repo-main/.mcp.json", br#"{"mcpServers":{"github":{"type":"http","url":"https://api.githubcopilot.com/mcp/","headers":{"Authorization":"Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}","X-Workspace":"${GITHUB_WORKSPACE}"}}}}"#),
1534 ("repo-main/skills/review/SKILL.md", b"---\nname: review\ndescription: Review\n---\nReview code.\n"),
1535 ]);
1536 let tmp = tempfile::tempdir().unwrap();
1537 let staged = stage_tarball(
1538 &bytes,
1539 &tmp.path().join("plugins"),
1540 DEFAULT_MAX_SIZE_BYTES,
1541 None,
1542 )
1543 .unwrap();
1544 assert_eq!(staged.name, "github");
1545 assert!(
1546 staged
1547 .staged_path
1548 .join(".claude-plugin/plugin.json")
1549 .is_file()
1550 );
1551 assert!(staged.staged_path.join(".mcp.json").is_file());
1552 assert!(staged.staged_path.join("skills/review/SKILL.md").is_file());
1553 let validated = crate::manifest::PluginManifest::validate_from_path(
1554 &staged.staged_path.join(".claude-plugin/plugin.json"),
1555 )
1556 .unwrap();
1557 let server = &validated.manifest.mcp_servers.as_ref().unwrap()["github"];
1558 assert!(server.headers.is_empty());
1559 assert_eq!(
1560 server.bearer_token_env_var.as_deref(),
1561 Some("GITHUB_PERSONAL_ACCESS_TOKEN")
1562 );
1563 assert_eq!(server.env_headers["X-Workspace"], "GITHUB_WORKSPACE");
1564 }
1565
1566 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1567 async fn claude_import_rejects_unsupported_components_without_partial_install() {
1568 for (file, body) in [
1569 ("hooks/hooks.json", "{}"),
1570 (".lsp.json", "{}"),
1571 (
1572 ".mcp.json",
1573 r#"{"demo":{"command":"node","unknownExecutableField":"run"}}"#,
1574 ),
1575 (
1576 ".mcp.json",
1577 r#"{"demo":{"type":"http","url":"https://example.com/mcp","headers":{"Authorization":"Bearer literal-secret"}}}"#,
1578 ),
1579 (
1580 ".mcp.json",
1581 r#"{"demo":{"type":"http","url":"https://example.com/mcp","headers":{"Authorization":"Bearer ${TOKEN}-suffix"}}}"#,
1582 ),
1583 (
1584 ".mcp.json",
1585 r#"{"demo":{"type":"http","url":"https://example.com/mcp","headers":{"Authorization":"${TOKEN} ${OTHER}"}}}"#,
1586 ),
1587 ] {
1588 let tmp = tempfile::tempdir().unwrap();
1589 let source = tmp.path().join("source");
1590 fs::create_dir_all(source.join(".claude-plugin")).unwrap();
1591 fs::write(
1592 source.join(".claude-plugin/plugin.json"),
1593 r#"{"name":"demo"}"#,
1594 )
1595 .unwrap();
1596 fs::create_dir_all(source.join(file).parent().unwrap()).unwrap();
1597 fs::write(source.join(file), body).unwrap();
1598 let plugins = tmp.path().join("plugins");
1599 assert!(
1600 install(
1601 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
1602 &plugins,
1603 DEFAULT_MAX_SIZE_BYTES,
1604 &allow_all(),
1605 false,
1606 &no_conflict()
1607 )
1608 .await
1609 .is_err(),
1610 "{file}"
1611 );
1612 assert!(!plugins.join("demo").exists());
1613 }
1614 }
1615
1616 #[cfg(unix)]
1617 #[test]
1618 fn claude_metadata_and_mcp_links_cannot_escape_bundle_validation() {
1619 use std::os::unix::fs::symlink;
1620 let tmp = tempfile::tempdir().unwrap();
1621 let root = tmp.path().join("bundle");
1622 let outside = tmp.path().join("outside");
1623 fs::create_dir_all(&root).unwrap();
1624 fs::create_dir_all(&outside).unwrap();
1625 fs::write(outside.join("plugin.json"), r#"{"name":"demo"}"#).unwrap();
1626 symlink(&outside, root.join(".claude-plugin")).unwrap();
1627 assert!(
1628 crate::manifest::PluginManifest::validate_from_path(
1629 &root.join(".claude-plugin/plugin.json")
1630 )
1631 .is_err()
1632 );
1633 fs::remove_file(root.join(".claude-plugin")).unwrap();
1634 fs::create_dir_all(root.join(".claude-plugin")).unwrap();
1635 fs::copy(
1636 outside.join("plugin.json"),
1637 root.join(".claude-plugin/plugin.json"),
1638 )
1639 .unwrap();
1640 fs::write(outside.join("mcp.json"), "{}").unwrap();
1641 symlink(outside.join("mcp.json"), root.join(".mcp.json")).unwrap();
1642 assert!(
1643 crate::manifest::PluginManifest::validate_from_path(
1644 &root.join(".claude-plugin/plugin.json")
1645 )
1646 .is_err()
1647 );
1648 }
1649
1650 #[test]
1651 fn dsh_admission_validates_engines_peer_ranges_and_platforms_and_admits_cjs_and_node_modules() {
1652 let tmp = tempfile::tempdir().unwrap();
1653 let patch_body = "- insert:\n - id: entry\n name: ./lib/index.cjs\n";
1654
1655 let make_bundle = |dir_name: &str, manifest: serde_json::Value| -> PathBuf {
1656 let dir = tmp.path().join(dir_name);
1657 fs::create_dir_all(dir.join("lib")).unwrap();
1658 fs::write(dir.join("package.json"), manifest.to_string()).unwrap();
1659 fs::write(dir.join("cordis.patch.yml"), patch_body).unwrap();
1660 fs::write(
1661 dir.join("lib/index.cjs"),
1662 "module.exports = { apply() {} };\n",
1663 )
1664 .unwrap();
1665 dir
1666 };
1667
1668 let bad_engines = make_bundle(
1669 "bad-engines",
1670 serde_json::json!({
1671 "name": "@demo/bad-engines",
1672 "version": "1.0.0",
1673 "engines": { "dsh": ">=0.3.0" },
1674 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
1675 }),
1676 );
1677 let err = dsh::convert_package(&bad_engines, &tmp.path().join("out-bad-engines"))
1678 .unwrap_err()
1679 .to_string();
1680 assert!(err.contains("incompatible-version"), "{err}");
1681 assert!(err.contains(">=0.3.0"), "{err}");
1682 assert!(err.contains("0.2.1-rc.5"), "{err}");
1683
1684 let bad_peer = make_bundle(
1685 "bad-peer",
1686 serde_json::json!({
1687 "name": "@demo/bad-peer",
1688 "version": "1.0.0",
1689 "peerDependencies": { "@deepseek-ai/dsh-tools": "^1.0.0" },
1690 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
1691 }),
1692 );
1693 let err = dsh::convert_package(&bad_peer, &tmp.path().join("out-bad-peer"))
1694 .unwrap_err()
1695 .to_string();
1696 assert!(err.contains("incompatible-version"), "{err}");
1697 assert!(err.contains("@deepseek-ai/dsh-tools"), "{err}");
1698 assert!(err.contains("^1.0.0"), "{err}");
1699
1700 let other_platform = if cfg!(target_os = "windows") {
1701 "darwin"
1702 } else {
1703 "win32"
1704 };
1705 let bad_platform = make_bundle(
1706 "bad-platform",
1707 serde_json::json!({
1708 "name": "@demo/bad-platform",
1709 "version": "1.0.0",
1710 "engines": { "dsh": "^0.2.1-rc.5" },
1711 "dsh": {
1712 "bundle": {
1713 "patch": "./cordis.patch.yml",
1714 "platforms": [other_platform]
1715 }
1716 }
1717 }),
1718 );
1719 let err = dsh::convert_package(&bad_platform, &tmp.path().join("out-bad-platform"))
1720 .unwrap_err()
1721 .to_string();
1722 assert!(err.contains("unsupported-platform"), "{err}");
1723 assert!(err.contains(other_platform), "{err}");
1724
1725 let host_platform = if cfg!(target_os = "macos") {
1726 "darwin"
1727 } else if cfg!(target_os = "windows") {
1728 "win32"
1729 } else {
1730 "linux"
1731 };
1732 for (idx, range) in ["^0.2.1-rc.5", "^0.2.2-rc.1", ">=0.2.0-rc.1 <0.3.0-0"]
1733 .iter()
1734 .enumerate()
1735 {
1736 let bundle = make_bundle(
1737 &format!("valid-{idx}"),
1738 serde_json::json!({
1739 "name": format!("@demo/valid-{idx}"),
1740 "version": "1.0.0",
1741 "main": "lib/index.cjs",
1742 "engines": { "dsh": range },
1743 "dsh": {
1744 "bundle": {
1745 "patch": "./cordis.patch.yml",
1746 "platforms": [host_platform]
1747 }
1748 }
1749 }),
1750 );
1751 let dep_dir = bundle.join("node_modules/fflate");
1752 fs::create_dir_all(&dep_dir).unwrap();
1753 fs::write(
1754 dep_dir.join("package.json"),
1755 r#"{"name":"fflate","version":"0.8.2","main":"lib/index.cjs"}"#,
1756 )
1757 .unwrap();
1758 fs::create_dir_all(dep_dir.join("lib")).unwrap();
1759 fs::write(dep_dir.join("lib/index.cjs"), "module.exports = {};\n").unwrap();
1760 let pkg = dsh::Package::open(&bundle).unwrap();
1761 assert_eq!(
1762 dsh::presets::contained_module(&pkg, "fflate").unwrap(),
1763 dep_dir.join("lib/index.cjs").canonicalize().unwrap()
1764 );
1765 let out = tmp.path().join(format!("out-valid-{idx}"));
1766 let converted = dsh::convert_package(&bundle, &out).unwrap();
1767 assert!(converted.requires_native);
1768 assert!(
1769 out.join("source/node_modules/fflate/lib/index.cjs")
1770 .is_file()
1771 );
1772 let validated =
1773 crate::manifest::PluginManifest::validate_from_path(&out.join("plugin.json")).unwrap();
1774 assert!(validated.applicable);
1775 }
1776
1777 let addon_bundle = make_bundle(
1778 "addon-bundle",
1779 serde_json::json!({
1780 "name": "@demo/addon-bundle",
1781 "version": "1.0.0",
1782 "engines": { "dsh": "^0.2.1-rc.5" },
1783 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
1784 }),
1785 );
1786 fs::create_dir_all(addon_bundle.join("node_modules/native-dep")).unwrap();
1787 fs::write(
1788 addon_bundle.join("node_modules/native-dep/binding.node"),
1789 b"ELF",
1790 )
1791 .unwrap();
1792 let err = dsh::convert_package(&addon_bundle, &tmp.path().join("out-addon"))
1793 .unwrap_err()
1794 .to_string();
1795 assert!(err.contains(".node"), "{err}");
1796 }
1797
1798 #[test]
1799 fn dsh_native_source_admits_a_top_level_gitignore_and_still_refuses_other_hidden_files() {
1800 let tmp = tempfile::tempdir().unwrap();
1801 let make = |name: &str| -> PathBuf {
1802 let dir = tmp.path().join(name);
1803 fs::create_dir_all(dir.join("lib")).unwrap();
1804 fs::write(
1805 dir.join("package.json"),
1806 serde_json::json!({
1807 "name": format!("@demo/{name}"),
1808 "version": "1.0.0",
1809 "main": "lib/index.cjs",
1810 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
1811 })
1812 .to_string(),
1813 )
1814 .unwrap();
1815 fs::write(
1816 dir.join("cordis.patch.yml"),
1817 "- insert:\n - id: entry\n name: ./lib/index.cjs\n",
1818 )
1819 .unwrap();
1820 fs::write(
1821 dir.join("lib/index.cjs"),
1822 "module.exports = { apply() {} };\n",
1823 )
1824 .unwrap();
1825 dir
1826 };
1827
1828 let with_gitignore = make("with-gitignore");
1829 fs::write(with_gitignore.join(".gitignore"), "node_modules/\n").unwrap();
1830 fs::create_dir_all(with_gitignore.join("presets/liangshen")).unwrap();
1831 fs::write(
1832 with_gitignore.join("presets/liangshen/.dsh-tui-managed.json"),
1833 "{\"owner\":\"@deepseek-harness-tui/dsh-tui\",\"preset\":\"liangshen\"}\n",
1834 )
1835 .unwrap();
1836 let out = tmp.path().join("out-with-gitignore");
1837 let converted = dsh::convert_package(&with_gitignore, &out).unwrap();
1838 assert!(converted.requires_native);
1839 assert!(out.join("source/.gitignore").is_file());
1840 assert!(
1841 out.join("source/presets/liangshen/.dsh-tui-managed.json")
1842 .is_file()
1843 );
1844
1845 for (name, relative) in [
1846 ("nested-gitignore", "lib/.gitignore"),
1847 ("other-hidden", ".prettierrc"),
1848 ("root-dsh-tui-managed", ".dsh-tui-managed.json"),
1849 ("env-file", ".env"),
1850 (
1851 "node-modules-env-variant",
1852 "node_modules/pkg/.env.production",
1853 ),
1854 ("npmrc", ".npmrc"),
1855 ("git-dir", ".git/config"),
1856 ] {
1857 let bundle = make(name);
1858 let path = bundle.join(relative);
1859 fs::create_dir_all(path.parent().unwrap()).unwrap();
1860 fs::write(&path, "x\n").unwrap();
1861 let err = dsh::convert_package(&bundle, &tmp.path().join(format!("out-{name}")))
1862 .unwrap_err()
1863 .to_string();
1864 assert!(
1865 err.contains("credential files or repository metadata"),
1866 "{name}: {err}"
1867 );
1868 }
1869
1870 #[cfg(unix)]
1871 {
1872 let linked = make("linked-gitignore");
1873 fs::write(tmp.path().join("outside-ignore"), "secret\n").unwrap();
1874 std::os::unix::fs::symlink(tmp.path().join("outside-ignore"), linked.join(".gitignore"))
1875 .unwrap();
1876 let err = dsh::convert_package(&linked, &tmp.path().join("out-linked"))
1877 .unwrap_err()
1878 .to_string();
1879 assert!(err.contains("links or reparse points"), "{err}");
1880 }
1881 }
1882
1883 #[test]
1884 fn dsh_client_closure_is_retained_hashed_and_refuses_ambient_dependencies() {
1885 let tmp = tempfile::tempdir().unwrap();
1886 let make = |name: &str, client: &str| -> PathBuf {
1887 let dir = tmp.path().join(name);
1888 fs::create_dir_all(dir.join("lib")).unwrap();
1889 fs::write(
1890 dir.join("package.json"),
1891 serde_json::json!({
1892 "name": format!("@demo/{name}"),
1893 "version": "1.0.0",
1894 "main": "lib/index.cjs",
1895 "exports": { "./client": { "default": "./lib/client.js" } },
1896 "dsh": {
1897 "bundle": { "patch": "./cordis.patch.yml" },
1898 "client": { "inject": ["@deepseek-ai/dsh-client-ui-primitives"], "platform": "web" }
1899 }
1900 })
1901 .to_string(),
1902 )
1903 .unwrap();
1904 fs::write(
1905 dir.join("cordis.patch.yml"),
1906 "- insert:\n - id: entry\n name: ./lib/index.cjs\n",
1907 )
1908 .unwrap();
1909 fs::write(
1910 dir.join("lib/index.cjs"),
1911 "module.exports = { apply() {} };\n",
1912 )
1913 .unwrap();
1914 fs::write(dir.join("lib/client.js"), client).unwrap();
1915 fs::write(dir.join("lib/util.js"), "exports.v = 1;\n").unwrap();
1916 dir
1917 };
1918
1919 let good = make(
1920 "good",
1921 "const r = require(\"react\");\nconst p = require('@deepseek-ai/dsh-client-ui-primitives');\nconst u = require(\"./util\");\n",
1922 );
1923 fs::write(
1924 good.join("lib/util.js"),
1925 "exports.v = 1; require('./client'); require('./data.json'); require('mapped'); require('react-dom/client'); require('react/jsx-runtime');\n",
1926 )
1927 .unwrap();
1928 fs::write(good.join("lib/data.json"), r#"{"value":2}"#).unwrap();
1929 fs::create_dir_all(good.join("node_modules/mapped")).unwrap();
1930 fs::write(
1931 good.join("node_modules/mapped/package.json"),
1932 r#"{"exports":{".":{"import":"./selected.cjs","default":"./missing.js"}}}"#,
1933 )
1934 .unwrap();
1935 fs::write(
1936 good.join("node_modules/mapped/selected.cjs"),
1937 "exports.value = 3;",
1938 )
1939 .unwrap();
1940 let converted = dsh::convert_package(&good, &tmp.path().join("out-good")).unwrap();
1941 assert_eq!(converted.client_closures.len(), 1);
1942 let closure = &converted.client_closures[0];
1943 assert_eq!(closure.entry, "source/lib/client.js");
1944 assert!(closure.files.contains_key("source/lib/util.js"));
1945 assert_eq!(closure.host_provided.len(), 4);
1946 assert!(
1947 closure
1948 .host_provided
1949 .iter()
1950 .any(|id| id == "react-dom/client")
1951 );
1952 assert!(
1953 closure
1954 .host_provided
1955 .iter()
1956 .any(|id| id == "react/jsx-runtime")
1957 );
1958 assert_eq!(
1959 closure.imports["source/lib/client.js"]["./util"].as_deref(),
1960 Some("source/lib/util.js")
1961 );
1962 assert_eq!(closure.imports["source/lib/client.js"]["react"], None);
1963 assert_eq!(
1964 closure.imports["source/lib/util.js"]["./client"].as_deref(),
1965 Some("source/lib/client.js")
1966 );
1967 assert_eq!(
1968 closure.imports["source/lib/util.js"]["./data.json"].as_deref(),
1969 Some("source/lib/data.json")
1970 );
1971 assert_eq!(
1972 closure.imports["source/lib/util.js"]["mapped"].as_deref(),
1973 Some("source/node_modules/mapped/selected.cjs")
1974 );
1975
1976 let installed = fs::read(tmp.path().join("out-good/source/lib/util.js")).unwrap();
1977 assert_eq!(
1978 closure.files["source/lib/util.js"],
1979 codewhale_skill_install::install::sha256_hex(&installed)
1980 );
1981 assert!(
1982 converted
1983 .outcomes
1984 .iter()
1985 .any(|o| o.kind == "client" && o.outcome == "retained")
1986 );
1987 assert!(!converted.outcomes.iter().any(|o| o.needs_manual_port()));
1988
1989 for (label, source) in [
1990 ("dynamic-import", "import(\"./util\");\n"),
1991 ("ambient", "require(\"left-pad\");\n"),
1992 ("builtin", "require(\"node:fs\");\n"),
1993 ("computed", "const n = \"x\"; require(n);\n"),
1994 ("concat", "const l = \"en\"; require(\"./locale/\" + l);\n"),
1995 ("concat-import", "const l = \"en\"; import(\"./a\" + l);\n"),
1996 ("escape", "require(\"../../outside.js\");\n"),
1997 ] {
1998 let bad = make(label, source);
1999 let converted =
2000 dsh::convert_package(&bad, &tmp.path().join(format!("out-{label}"))).unwrap();
2001 assert!(converted.client_closures.is_empty(), "{label}");
2002 assert!(
2003 converted
2004 .outcomes
2005 .iter()
2006 .any(|o| o.kind == "client" && o.outcome == "skipped"),
2007 "{label}"
2008 );
2009 assert!(
2010 converted.requires_native,
2011 "{label}: server half still imports"
2012 );
2013 }
2014 }
2015
2016 #[test]
2017 fn parse_package_json_admits_duplicate_keys_last_wins_while_parse_json_refuses() {
2018 assert!(dsh::parse_json(r#"{"a":1,"a":2}"#).is_err());
2019 assert_eq!(
2020 dsh::parse_package_json(r#"{"a":1,"a":2}"#).unwrap(),
2021 dsh::parse_json(r#"{"a":2}"#).unwrap()
2022 );
2023 }
2024
2025 #[test]
2026 fn convert_package_sanitizes_and_truncates_oversized_description() {
2027 let tmp = tempfile::tempdir().unwrap();
2028 let dir = tmp.path().join("long-desc");
2029 fs::create_dir_all(dir.join("lib")).unwrap();
2030 let raw_desc = format!("a\x07\u{202E}b{}", "x".repeat(1200));
2031 fs::write(
2032 dir.join("package.json"),
2033 serde_json::json!({
2034 "name": "@demo/long-desc",
2035 "version": "1.0.0",
2036 "description": raw_desc,
2037 "main": "lib/index.cjs",
2038 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
2039 })
2040 .to_string(),
2041 )
2042 .unwrap();
2043 fs::write(
2044 dir.join("cordis.patch.yml"),
2045 "- insert:\n - id: entry\n name: ./lib/index.cjs\n",
2046 )
2047 .unwrap();
2048 fs::write(
2049 dir.join("lib/index.cjs"),
2050 "module.exports = { apply() {} };\n",
2051 )
2052 .unwrap();
2053
2054 let out = tmp.path().join("out");
2055 dsh::convert_package(&dir, &out).unwrap();
2056 let manifest_value: serde_json::Value =
2057 serde_json::from_str(&fs::read_to_string(out.join("plugin.json")).unwrap()).unwrap();
2058 let desc = manifest_value["description"].as_str().unwrap();
2059 assert!(
2060 desc.chars().count() <= 1024,
2061 "desc chars={}",
2062 desc.chars().count()
2063 );
2064 assert!(desc.ends_with('…'), "desc={desc:?}");
2065 assert!(!desc.contains('\x07') && !desc.contains('\u{202E}'));
2066 crate::manifest::PluginManifest::validate_from_path(&out.join("plugin.json")).unwrap();
2067 }
2068
2069 #[test]
2070 fn mixed_composition_with_agent_presets_and_code_row_writes_composition_not_roster() {
2071 let tmp = tempfile::tempdir().unwrap();
2072 let dir = tmp.path().join("mixed-comp");
2073 fs::create_dir_all(dir.join("lib")).unwrap();
2074 fs::write(
2075 dir.join("package.json"),
2076 serde_json::json!({
2077 "name": "@demo/mixed-comp",
2078 "version": "1.0.0",
2079 "main": "lib/index.cjs",
2080 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
2081 })
2082 .to_string(),
2083 )
2084 .unwrap();
2085 fs::write(
2086 dir.join("cordis.patch.yml"),
2087 "- insert:\n - id: presets\n name: \"@deepseek-ai/dsh-agent-presets\"\n config: {}\n - id: entry\n name: ./lib/index.cjs\n",
2088 )
2089 .unwrap();
2090 fs::write(
2091 dir.join("lib/index.cjs"),
2092 "module.exports = { apply() {} };\n",
2093 )
2094 .unwrap();
2095
2096 let out = tmp.path().join("out");
2097 let converted = dsh::convert_package(&dir, &out).unwrap();
2098 assert!(converted.requires_native);
2099 assert!(out.join("native/composition.json").is_file());
2100 assert!(out.join("native/index.mjs").is_file());
2101 assert!(!out.join("native/presets.json").exists());
2102 }
2103
2104 fn write_dsh_base_package(root: &Path, package_json: serde_json::Value, patch: &str) -> PathBuf {
2105 fs::create_dir_all(root).unwrap();
2106 fs::write(
2107 root.join("package.json"),
2108 serde_json::to_string_pretty(&package_json).unwrap(),
2109 )
2110 .unwrap();
2111 fs::write(root.join("cordis.patch.yml"), patch).unwrap();
2112 root.to_path_buf()
2113 }
2114
2115 fn minimal_dsh_patch_with_skill() -> &'static str {
2116 "- insert:\n - id: guide-skills\n name: '@deepseek-ai/dsh-skill-filesystem'\n config:\n customSkillDirs:\n - custom-skills\n"
2117 }
2118
2119 fn write_minimal_skill(dir: &Path, name: &str) {
2120 fs::create_dir_all(dir.join(name)).unwrap();
2121 fs::write(
2122 dir.join(name).join("SKILL.md"),
2123 format!("---\nname: {name}\ndescription: demo skill\n---\nbody\n"),
2124 )
2125 .unwrap();
2126 }
2127
2128 #[tokio::test]
2129 async fn local_install_of_folder_with_both_files_takes_dsh_and_merges_commands_agents_hooks() {
2130 let tmp = tempfile::tempdir().unwrap();
2131 let plugins = tmp.path().join("plugins");
2132 let pkg = write_dsh_base_package(
2133 &tmp.path().join("combo-pkg"),
2134 serde_json::json!({
2135 "name": "@acme/combo-widget",
2136 "version": "1.2.0",
2137 "description": "DSH description wins",
2138 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2139 }),
2140 minimal_dsh_patch_with_skill(),
2141 );
2142 write_minimal_skill(&pkg.join("custom-skills"), "guide");
2143 fs::create_dir_all(pkg.join("commands")).unwrap();
2144 fs::write(pkg.join("commands/hello.md"), "# Hello\nRun hello.\n").unwrap();
2145 fs::create_dir_all(pkg.join("agents")).unwrap();
2146 fs::write(
2147 pkg.join("agents/reviewer.toml"),
2148 "id = \"reviewer\"\n[role]\nname = \"reviewer\"\ndescription = \"Reviews\"\nprompt = \"Review.\"\n",
2149 )
2150 .unwrap();
2151 fs::create_dir_all(pkg.join("hooks")).unwrap();
2152 fs::write(
2153 pkg.join("hooks/hooks.toml"),
2154 "enabled = true\n[[hooks]]\nname = \"check\"\nevent = \"turn_end\"\ncommand = \"true\"\n",
2155 )
2156 .unwrap();
2157 fs::write(
2158 pkg.join("plugin.json"),
2159 serde_json::json!({
2160 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2161 "name": "combo-widget",
2162 "version": "1.2.0",
2163 "extensions": {
2164 "net.codewhale": {
2165 "commands": {"path": "commands"},
2166 "agents": {"path": "agents"},
2167 "hooks": {"path": "hooks"}
2168 }
2169 }
2170 })
2171 .to_string(),
2172 )
2173 .unwrap();
2174
2175 let bare_source = PluginInstallSource::parse(pkg.to_str().unwrap()).unwrap();
2176 assert_eq!(bare_source, PluginInstallSource::Dsh(pkg.clone()));
2177 let path_prefixed =
2178 PluginInstallSource::parse(&format!("path:{}", pkg.to_str().unwrap())).unwrap();
2179 assert_eq!(path_prefixed, PluginInstallSource::Dsh(pkg.clone()));
2180
2181 let outcome = install(
2182 bare_source,
2183 &plugins,
2184 DEFAULT_MAX_SIZE_BYTES,
2185 &allow_all(),
2186 false,
2187 &no_conflict(),
2188 )
2189 .await
2190 .unwrap();
2191 let PluginInstallOutcome::Installed(installed) = outcome else {
2192 panic!("expected merged install");
2193 };
2194 assert_eq!(installed.name, "combo-widget");
2195 assert!(installed.path.join("commands/hello.md").is_file());
2196 assert!(installed.path.join("agents/reviewer.toml").is_file());
2197 assert!(installed.path.join("hooks/hooks.toml").is_file());
2198 assert!(installed.path.join("skills/guide/SKILL.md").is_file());
2199 assert!(installed.path.join("CONVERSION.md").is_file());
2200 assert!(installed.path.join("CONVERSION.json").is_file());
2201
2202 let validated =
2203 crate::manifest::PluginManifest::validate_from_path(&installed.path.join("plugin.json"))
2204 .unwrap();
2205 assert_eq!(validated.inventory.skills, 1);
2206 assert_eq!(validated.inventory.commands, 1);
2207 assert_eq!(validated.inventory.agents, 1);
2208 assert_eq!(validated.inventory.hooks, 1);
2209
2210 let config = crate::discovery::DiscoveryConfig {
2211 workspace: tmp.path().join("workspace"),
2212 user_plugins_dir: plugins.clone(),
2213 workspace_plugins_dir: tmp.path().join("workspace/.codewhale/plugins"),
2214 builtin_plugin_dirs: Vec::new(),
2215 state_path: tmp.path().join("state.json"),
2216 };
2217 let registry = crate::discovery::discover_with_config(&config);
2218 let loaded = registry.get("combo-widget").unwrap();
2219 assert!(!loaded.trusted());
2220 assert!(!loaded.enabled);
2221 assert_eq!(loaded.inventory.commands, 1);
2222 assert_eq!(loaded.inventory.agents, 1);
2223 assert_eq!(loaded.inventory.hooks, 1);
2224 }
2225
2226 #[test]
2227 fn plugin_json_beside_dsh_package_keeps_dsh_name_and_version_and_refuses_mismatch() {
2228 let tmp = tempfile::tempdir().unwrap();
2229 let make_pair = |tag: &str, pkg_ver: Option<&str>, pj: serde_json::Value| {
2230 let mut package = serde_json::json!({
2231 "name": "@org/my-tool",
2232 "description": "From package.json",
2233 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2234 });
2235 if let Some(ver) = pkg_ver {
2236 package["version"] = serde_json::json!(ver);
2237 }
2238 let dir = write_dsh_base_package(
2239 &tmp.path().join(tag),
2240 package,
2241 minimal_dsh_patch_with_skill(),
2242 );
2243 write_minimal_skill(&dir.join("custom-skills"), "guide");
2244 fs::create_dir_all(dir.join("commands")).unwrap();
2245 fs::write(dir.join("commands/ping.md"), "ping\n").unwrap();
2246 fs::write(
2247 dir.join("plugin.json"),
2248 serde_json::to_string_pretty(&pj).unwrap(),
2249 )
2250 .unwrap();
2251 dir
2252 };
2253
2254 let wrong_name = make_pair(
2255 "wrong-name",
2256 Some("1.0.0"),
2257 serde_json::json!({
2258 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2259 "name": "other-name",
2260 "version": "1.0.0",
2261 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
2262 }),
2263 );
2264 let err = dsh::convert_package(&wrong_name, &tmp.path().join("out-wrong-name"))
2265 .unwrap_err()
2266 .to_string();
2267 assert!(err.contains("plugin.json"), "{err}");
2268 assert!(err.contains("package.json"), "{err}");
2269 assert!(err.contains("my-tool"), "{err}");
2270
2271 let wrong_ver = make_pair(
2272 "wrong-ver",
2273 Some("1.0.0"),
2274 serde_json::json!({
2275 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2276 "name": "my-tool",
2277 "version": "2.0.0",
2278 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
2279 }),
2280 );
2281 let err = dsh::convert_package(&wrong_ver, &tmp.path().join("out-wrong-ver"))
2282 .unwrap_err()
2283 .to_string();
2284 assert!(err.contains("plugin.json"), "{err}");
2285 assert!(err.contains("package.json"), "{err}");
2286 assert!(err.contains("2.0.0"), "{err}");
2287
2288 let meta_ignored = make_pair(
2289 "meta-ignored",
2290 Some("1.0.0"),
2291 serde_json::json!({
2292 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2293 "name": "my-tool",
2294 "description": "From plugin.json (ignored)",
2295 "author": {"name": "Someone"},
2296 "homepage": "https://example.invalid",
2297 "repository": "https://example.invalid/repo",
2298 "license": "MIT",
2299 "keywords": ["alpha"],
2300 "extensions": {
2301 "net.codewhale": {"commands": {"path": "commands"}},
2302 "com.example.vendor": {"ignored": true}
2303 }
2304 }),
2305 );
2306 let out_ignored = tmp.path().join("out-meta-ignored");
2307 let converted = dsh::convert_package(&meta_ignored, &out_ignored).unwrap();
2308 assert!(
2309 converted
2310 .diagnostics
2311 .iter()
2312 .any(|line| line.contains("plugin.json")
2313 && line.contains("package.json")
2314 && line.contains("description")
2315 && line.contains("author")),
2316 "{:?}",
2317 converted.diagnostics
2318 );
2319 let emitted: serde_json::Value =
2320 serde_json::from_slice(&fs::read(out_ignored.join("plugin.json")).unwrap()).unwrap();
2321 assert_eq!(emitted["name"], "my-tool");
2322 assert_eq!(emitted["version"], "1.0.0");
2323 assert_eq!(emitted["description"], "From package.json");
2324 assert!(emitted.get("author").is_none());
2325 assert!(emitted["extensions"].get("com.example.vendor").is_none());
2326
2327 let pkg_no_ver = make_pair(
2328 "pkg-no-ver",
2329 None,
2330 serde_json::json!({
2331 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2332 "name": "my-tool",
2333 "version": "9.9.9",
2334 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
2335 }),
2336 );
2337 let out_no_ver = tmp.path().join("out-no-ver");
2338 dsh::convert_package(&pkg_no_ver, &out_no_ver).unwrap();
2339 let emitted_no_ver: serde_json::Value =
2340 serde_json::from_slice(&fs::read(out_no_ver.join("plugin.json")).unwrap()).unwrap();
2341 assert!(emitted_no_ver.get("version").is_none());
2342 }
2343
2344 #[test]
2345 fn plugin_json_beside_dsh_package_may_not_declare_skills_or_connectors() {
2346 let tmp = tempfile::tempdir().unwrap();
2347 let setup = |tag: &str, ext: serde_json::Value| {
2348 let dir = write_dsh_base_package(
2349 &tmp.path().join(tag),
2350 serde_json::json!({
2351 "name": "tool-pkg",
2352 "version": "1.0.0",
2353 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2354 }),
2355 minimal_dsh_patch_with_skill(),
2356 );
2357 write_minimal_skill(&dir.join("custom-skills"), "guide");
2358 fs::create_dir_all(dir.join("commands")).unwrap();
2359 fs::write(dir.join("commands/ping.md"), "ping\n").unwrap();
2360 fs::write(
2361 dir.join("plugin.json"),
2362 serde_json::json!({
2363 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2364 "name": "tool-pkg",
2365 "version": "1.0.0",
2366 "extensions": {"net.codewhale": ext}
2367 })
2368 .to_string(),
2369 )
2370 .unwrap();
2371 dir
2372 };
2373
2374 for (key, val) in [
2375 ("skills", serde_json::json!({"path": "custom-skills"})),
2376 ("native", serde_json::json!({"path": "index.mjs"})),
2377 ("lsp", serde_json::json!({"path": "lsp"})),
2378 (
2379 "providers",
2380 serde_json::json!({"acme": {"base_url": "https://example.invalid"}}),
2381 ),
2382 (
2383 "capabilities",
2384 serde_json::json!({"network_hosts": ["api.example.com"]}),
2385 ),
2386 ("when", serde_json::json!({"binaries": ["node"]})),
2387 ("display_name", serde_json::json!("Pretty")),
2388 ("icon", serde_json::json!("icon.svg")),
2389 ] {
2390 let pkg = setup(&format!("forbid-{key}"), serde_json::json!({key: val}));
2391 let err = dsh::convert_package(&pkg, &tmp.path().join(format!("out-{key}")))
2392 .unwrap_err()
2393 .to_string();
2394 assert!(err.contains("plugin.json"), "{key}: {err}");
2395 assert!(err.contains("package.json"), "{key}: {err}");
2396 assert!(err.contains(key), "{key}: {err}");
2397 }
2398
2399 let with_mcp_json = setup(
2400 "sibling-mcp-json",
2401 serde_json::json!({"commands": {"path": "commands"}}),
2402 );
2403 fs::write(
2404 with_mcp_json.join("mcp.json"),
2405 r#"{"mcpServers":{"s":{"type":"http","url":"https://example.invalid"}}}"#,
2406 )
2407 .unwrap();
2408 let err = dsh::convert_package(&with_mcp_json, &tmp.path().join("out-mcp-json"))
2409 .unwrap_err()
2410 .to_string();
2411 assert!(err.contains("plugin.json"), "{err}");
2412 assert!(err.contains("package.json"), "{err}");
2413 assert!(err.contains("mcp.json"), "{err}");
2414
2415 let with_unpatched_skills = setup(
2416 "unpatched-skills-dir",
2417 serde_json::json!({"commands": {"path": "commands"}}),
2418 );
2419 write_minimal_skill(&with_unpatched_skills.join("skills"), "auto-picked");
2420 let err = dsh::convert_package(
2421 &with_unpatched_skills,
2422 &tmp.path().join("out-unpatched-skills"),
2423 )
2424 .unwrap_err()
2425 .to_string();
2426 assert!(err.contains("plugin.json"), "{err}");
2427 assert!(err.contains("package.json"), "{err}");
2428 assert!(err.contains("skills/"), "{err}");
2429
2430 let patched_root_skills = write_dsh_base_package(
2431 &tmp.path().join("patched-root-skills"),
2432 serde_json::json!({
2433 "name": "tool-pkg",
2434 "version": "1.0.0",
2435 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2436 }),
2437 "- insert:\n - id: root-skills\n name: '@deepseek-ai/dsh-skill-filesystem'\n config:\n customSkillDirs:\n - skills\n",
2438 );
2439 write_minimal_skill(&patched_root_skills.join("skills"), "patched");
2440 fs::create_dir_all(patched_root_skills.join("commands")).unwrap();
2441 fs::write(patched_root_skills.join("commands/ping.md"), "ping\n").unwrap();
2442 fs::write(
2443 patched_root_skills.join("plugin.json"),
2444 serde_json::json!({
2445 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2446 "name": "tool-pkg",
2447 "version": "1.0.0",
2448 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
2449 })
2450 .to_string(),
2451 )
2452 .unwrap();
2453 let converted = dsh::convert_package(
2454 &patched_root_skills,
2455 &tmp.path().join("out-patched-root-skills"),
2456 )
2457 .unwrap();
2458 assert_eq!(converted.skills, ["patched"]);
2459 assert_eq!(converted.commands, ["commands/ping.md"]);
2460 }
2461
2462 #[test]
2463 fn hooks_from_plugin_json_and_hook_bridge_patch_row_are_refused() {
2464 let tmp = tempfile::tempdir().unwrap();
2465 for (label, bridge_pkg) in [
2466 ("claude", "@deepseek-ai/dsh-hooks-claude-code"),
2467 ("codex", "@deepseek-ai/dsh-hooks-codex"),
2468 ] {
2469 let dir = write_dsh_base_package(
2470 &tmp.path().join(format!("dup-hooks-{label}")),
2471 serde_json::json!({
2472 "name": "hook-clash",
2473 "version": "1.0.0",
2474 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2475 }),
2476 &format!(
2477 "- insert:\n - id: bridge-hooks\n name: '{bridge_pkg}'\n config:\n configPath: bridge-hooks.json\n"
2478 ),
2479 );
2480 fs::write(dir.join("bridge-hooks.json"), "{}").unwrap();
2481 fs::create_dir_all(dir.join("hooks")).unwrap();
2482 fs::write(
2483 dir.join("hooks/hooks.toml"),
2484 "enabled = true\n[[hooks]]\nname = \"cw\"\nevent = \"turn_end\"\ncommand = \"true\"\n",
2485 )
2486 .unwrap();
2487 fs::write(
2488 dir.join("plugin.json"),
2489 serde_json::json!({
2490 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2491 "name": "hook-clash",
2492 "version": "1.0.0",
2493 "extensions": {"net.codewhale": {"hooks": {"path": "hooks"}}}
2494 })
2495 .to_string(),
2496 )
2497 .unwrap();
2498
2499 let err = dsh::convert_package(&dir, &tmp.path().join(format!("out-{label}")))
2500 .unwrap_err()
2501 .to_string();
2502 assert!(err.contains("package.json"), "{label}: {err}");
2503 assert!(err.contains("plugin.json"), "{label}: {err}");
2504 assert!(err.contains("hooks"), "{label}: {err}");
2505 }
2506 }
2507
2508 #[test]
2509 fn other_manifest_spellings_beside_dsh_package_are_refused() {
2510 let tmp = tempfile::tempdir().unwrap();
2511 for spelling in [
2512 "kimi.plugin.json",
2513 "plugin.toml",
2514 ".claude-plugin/plugin.json",
2515 ".plugin/plugin.json",
2516 ".github/plugin/plugin.json",
2517 ] {
2518 let dir = write_dsh_base_package(
2519 &tmp.path().join(spelling.replace(['/', '.'], "_")),
2520 serde_json::json!({
2521 "name": "other-manifest",
2522 "version": "1.0.0",
2523 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2524 }),
2525 minimal_dsh_patch_with_skill(),
2526 );
2527 write_minimal_skill(&dir.join("custom-skills"), "guide");
2528 let target = dir.join(spelling);
2529 fs::create_dir_all(target.parent().unwrap()).unwrap();
2530 fs::write(
2531 &target,
2532 if spelling.ends_with(".toml") {
2533 "schema_version = 1\n[plugin]\nname = \"other-manifest\"\nversion = \"1.0.0\"\n"
2534 } else {
2535 r#"{"name":"other-manifest"}"#
2536 },
2537 )
2538 .unwrap();
2539
2540 assert_eq!(
2541 PluginInstallSource::parse(dir.to_str().unwrap()).unwrap(),
2542 PluginInstallSource::Dsh(dir.clone()),
2543 "{spelling} must still route to DSH"
2544 );
2545 let err = dsh::convert_package(
2546 &dir,
2547 &tmp.path()
2548 .join(format!("out-{}", spelling.replace(['/', '.'], "_"))),
2549 )
2550 .unwrap_err()
2551 .to_string();
2552 assert!(err.contains("package.json"), "{spelling}: {err}");
2553 assert!(err.contains(spelling), "{spelling}: {err}");
2554 }
2555
2556 let non_object_bundle = write_dsh_base_package(
2557 &tmp.path().join("non-object-dsh-bundle"),
2558 serde_json::json!({
2559 "name": "non-object",
2560 "version": "1.0.0",
2561 "dsh": {"bundle": "not-an-object"}
2562 }),
2563 "[]\n",
2564 );
2565 fs::write(
2566 non_object_bundle.join("plugin.json"),
2567 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"non-object"}"#,
2568 )
2569 .unwrap();
2570 assert_eq!(
2571 PluginInstallSource::parse(non_object_bundle.to_str().unwrap()).unwrap(),
2572 PluginInstallSource::Dsh(non_object_bundle.clone())
2573 );
2574 assert!(dsh::convert_package(&non_object_bundle, &tmp.path().join("out-non-obj")).is_err());
2575 }
2576
2577 #[test]
2578 fn plain_dsh_package_with_no_plugin_json_keeps_behavior_with_skills_dir_or_mcp_json() {
2579 let tmp = tempfile::tempdir().unwrap();
2580 let dir = write_dsh_base_package(
2581 &tmp.path().join("plain-dsh"),
2582 serde_json::json!({
2583 "name": "plain-dsh",
2584 "version": "1.0.0",
2585 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2586 }),
2587 minimal_dsh_patch_with_skill(),
2588 );
2589 write_minimal_skill(&dir.join("custom-skills"), "guide");
2590 write_minimal_skill(&dir.join("skills"), "unreferenced");
2591 fs::write(dir.join("mcp.json"), r#"{"mcpServers":{}}"#).unwrap();
2592
2593 let out = tmp.path().join("out-plain-dsh");
2594 let converted = dsh::convert_package(&dir, &out).unwrap();
2595 assert_eq!(converted.skills, ["guide"]);
2596 assert!(converted.commands.is_empty());
2597 assert!(converted.agents.is_empty());
2598 assert!(converted.hooks.is_empty());
2599 assert!(!out.join("skills/unreferenced").exists());
2600 assert!(!out.join("mcp.json").exists());
2601
2602 let emitted_manifest: serde_json::Value =
2603 serde_json::from_slice(&fs::read(out.join("plugin.json")).unwrap()).unwrap();
2604 let net_codewhale = emitted_manifest
2605 .get("extensions")
2606 .and_then(|ext| ext.get("net.codewhale"));
2607 for forbidden in ["commands", "agents", "hooks"] {
2608 assert!(
2609 net_codewhale.and_then(|obj| obj.get(forbidden)).is_none(),
2610 "{forbidden} must be omitted from plugin.json"
2611 );
2612 }
2613 let conversion_json: serde_json::Value =
2614 serde_json::from_slice(&fs::read(out.join("CONVERSION.json")).unwrap()).unwrap();
2615 for key in ["commands", "agents", "hooks"] {
2616 assert!(conversion_json.get(key).is_none());
2617 assert!(conversion_json["counts"].get(key).is_none());
2618 }
2619 let conversion_md = fs::read_to_string(out.join("CONVERSION.md")).unwrap();
2620 assert!(!conversion_md.contains("Merged from sibling plugin.json"));
2621 assert!(conversion_md.contains("install hook, network request or credential lookup ran"));
2622 assert!(conversion_md.contains("Only files inside the selected package were read"));
2623
2624 let fetched = ["acorn@8.14.0".to_string(), "zod@4.1.0".to_string()];
2625 let mut staged = converted.clone();
2626 staged
2627 .diagnostics
2628 .push(dsh::fetched_npm_note(&fetched).unwrap());
2629 let staged_md = dsh::conversion_markdown(&staged, true);
2630 assert!(staged_md.contains(
2631 "Fetched from registry.npmjs.org (sha512-verified; install scripts not run): acorn@8.14.0, zod@4.1.0"
2632 ));
2633 assert!(!staged_md.contains("network request"));
2634 assert!(!staged_md.contains("Only files inside the selected package were read"));
2635 let many: Vec<String> = (0..45).map(|index| format!("p{index}@1.0.0")).collect();
2636 assert!(
2637 dsh::fetched_npm_note(&many)
2638 .unwrap()
2639 .ends_with("p39@1.0.0, +5 more")
2640 );
2641 assert!(dsh::fetched_npm_note(&[]).is_none());
2642 }
2643
2644 #[cfg(unix)]
2645 #[test]
2646 fn dsh_custom_skill_dirs_refuse_a_symlinked_skill_dir_inside_the_package() {
2647 let tmp = tempfile::tempdir().unwrap();
2648 let dir = write_dsh_base_package(
2649 &tmp.path().join("leak-pkg"),
2650 serde_json::json!({
2651 "name": "@demo/leak",
2652 "version": "1.0.0",
2653 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2654 }),
2655 minimal_dsh_patch_with_skill(),
2656 );
2657 write_minimal_skill(&dir.join("custom-skills"), "guide");
2658
2659 let outside = tmp.path().join("outside");
2660 fs::create_dir_all(&outside).unwrap();
2661 fs::write(
2662 outside.join("SKILL.md"),
2663 "---\nname: leaked\ndescription: outside skill\n---\nbody\n",
2664 )
2665 .unwrap();
2666 fs::write(outside.join("secret.txt"), "TOP-SECRET-OUTSIDE-PACKAGE\n").unwrap();
2667 std::os::unix::fs::symlink(&outside, dir.join("custom-skills/leak")).unwrap();
2668
2669 let err = dsh::convert_package(&dir, &tmp.path().join("out-leak"))
2670 .unwrap_err()
2671 .to_string();
2672 assert!(err.contains("links or reparse points"), "{err}");
2673 assert!(!tmp.path().join("out-leak").exists());
2674 }
2675
2676 #[test]
2677 fn component_paths_in_sibling_plugin_json_cannot_escape_or_follow_links() {
2678 let tmp = tempfile::tempdir().unwrap();
2679 let outside = tmp.path().join("outside.md");
2680 fs::write(&outside, "secret\n").unwrap();
2681
2682 let make = |tag: &str, commands_path: &str| {
2683 let dir = write_dsh_base_package(
2684 &tmp.path().join(tag),
2685 serde_json::json!({
2686 "name": "sec-pkg",
2687 "version": "1.0.0",
2688 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2689 }),
2690 minimal_dsh_patch_with_skill(),
2691 );
2692 write_minimal_skill(&dir.join("custom-skills"), "guide");
2693 fs::write(
2694 dir.join("plugin.json"),
2695 serde_json::json!({
2696 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2697 "name": "sec-pkg",
2698 "version": "1.0.0",
2699 "extensions": {"net.codewhale": {"commands": {"path": commands_path}}}
2700 })
2701 .to_string(),
2702 )
2703 .unwrap();
2704 dir
2705 };
2706
2707 for (tag, bad_path) in [
2708 ("parent", "../outside.md"),
2709 ("abs", "/etc/passwd"),
2710 ("win-abs", "C:\\Users\\demo\\.ssh\\id_rsa"),
2711 ("dot-env", ".env"),
2712 ("ssh", ".ssh/id_rsa"),
2713 ("creds", "credentials.json"),
2714 ("dot", "."),
2715 ] {
2716 let dir = make(tag, bad_path);
2717 if bad_path == ".env" || bad_path == "credentials.json" {
2718 fs::write(dir.join(bad_path), "SECRET=1\n").unwrap();
2719 }
2720 assert!(
2721 dsh::convert_package(&dir, &tmp.path().join(format!("out-{tag}"))).is_err(),
2722 "{tag} ({bad_path}) must refuse"
2723 );
2724 }
2725
2726 let hidden_in_dir = make("hidden-in-dir", "commands");
2727 fs::create_dir_all(hidden_in_dir.join("commands")).unwrap();
2728 fs::write(hidden_in_dir.join("commands/.env"), "SECRET=1\n").unwrap();
2729 assert!(dsh::convert_package(&hidden_in_dir, &tmp.path().join("out-hidden-in-dir")).is_err());
2730
2731 #[cfg(unix)]
2732 {
2733 let linked_cmd = make("linked-cmd", "commands");
2734 fs::create_dir_all(linked_cmd.join("commands")).unwrap();
2735 std::os::unix::fs::symlink(&outside, linked_cmd.join("commands/link.md")).unwrap();
2736 assert!(dsh::convert_package(&linked_cmd, &tmp.path().join("out-linked-cmd")).is_err());
2737
2738 let linked_pj = write_dsh_base_package(
2739 &tmp.path().join("linked-pj"),
2740 serde_json::json!({
2741 "name": "sec-pkg",
2742 "version": "1.0.0",
2743 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2744 }),
2745 minimal_dsh_patch_with_skill(),
2746 );
2747 write_minimal_skill(&linked_pj.join("custom-skills"), "guide");
2748 let outside_pj = tmp.path().join("outside-plugin.json");
2749 fs::write(
2750 &outside_pj,
2751 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"sec-pkg"}"#,
2752 )
2753 .unwrap();
2754 std::os::unix::fs::symlink(&outside_pj, linked_pj.join("plugin.json")).unwrap();
2755 assert!(dsh::convert_package(&linked_pj, &tmp.path().join("out-linked-pj")).is_err());
2756
2757 let hardlinked = make("hardlinked", "commands");
2758 fs::create_dir_all(hardlinked.join("commands")).unwrap();
2759 fs::hard_link(&outside, hardlinked.join("commands/hard.md")).unwrap();
2760 assert!(dsh::convert_package(&hardlinked, &tmp.path().join("out-hardlinked")).is_err());
2761 }
2762 }
2763
2764 #[tokio::test]
2765 async fn existing_codewhale_install_keeps_update_semantics_when_dsh_added() {
2766 let tmp = tempfile::tempdir().unwrap();
2767 let plugins = tmp.path().join("plugins");
2768 let source = tmp.path().join("evolved-plugin");
2769 fs::create_dir_all(source.join("commands")).unwrap();
2770 fs::write(source.join("commands/ping.md"), "ping v1\n").unwrap();
2771 fs::write(
2772 source.join("plugin.json"),
2773 serde_json::json!({
2774 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2775 "name": "evolved",
2776 "version": "1.0.0",
2777 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
2778 })
2779 .to_string(),
2780 )
2781 .unwrap();
2782
2783 let outcome = install(
2784 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
2785 &plugins,
2786 DEFAULT_MAX_SIZE_BYTES,
2787 &allow_all(),
2788 false,
2789 &no_conflict(),
2790 )
2791 .await
2792 .unwrap();
2793 let PluginInstallOutcome::Installed(installed) = outcome else {
2794 panic!("expected initial install");
2795 };
2796 let marker: serde_json::Value = serde_json::from_str(
2797 &fs::read_to_string(installed.path.join(INSTALLED_FROM_MARKER)).unwrap(),
2798 )
2799 .unwrap();
2800 assert!(marker["spec"].as_str().unwrap().starts_with("path:"));
2801
2802 fs::write(
2803 source.join("package.json"),
2804 serde_json::json!({
2805 "name": "evolved",
2806 "version": "1.0.0",
2807 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2808 })
2809 .to_string(),
2810 )
2811 .unwrap();
2812 fs::write(source.join("cordis.patch.yml"), "[]\n").unwrap();
2813 fs::write(source.join("commands/ping.md"), "ping v2\n").unwrap();
2814
2815 assert_eq!(
2816 PluginInstallSource::parse(source.to_str().unwrap()).unwrap(),
2817 PluginInstallSource::Dsh(source.clone())
2818 );
2819
2820 let updated = update("evolved", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
2821 .await
2822 .unwrap();
2823 let PluginUpdateResult::Updated(updated_bundle) = updated else {
2824 panic!("expected LocalPath update");
2825 };
2826 assert_eq!(
2827 fs::read_to_string(updated_bundle.path.join("commands/ping.md")).unwrap(),
2828 "ping v2\n"
2829 );
2830 assert!(!updated_bundle.path.join("CONVERSION.json").exists());
2831 }
2832
2833 #[tokio::test]
2834 async fn merged_bundle_review_shows_commands_agents_hooks_and_fails_closed_on_tamper() {
2835 let tmp = tempfile::tempdir().unwrap();
2836 let plugins = tmp.path().join("plugins");
2837 let pkg = write_dsh_base_package(
2838 &tmp.path().join("review-pkg"),
2839 serde_json::json!({
2840 "name": "review-pkg",
2841 "version": "1.0.0",
2842 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2843 }),
2844 "[]\n",
2845 );
2846 fs::create_dir_all(pkg.join("commands")).unwrap();
2847 fs::write(pkg.join("commands/hello.md"), "hello v1\n").unwrap();
2848 fs::create_dir_all(pkg.join("agents")).unwrap();
2849 fs::write(
2850 pkg.join("agents/scout.toml"),
2851 "id = \"scout\"\n[role]\nname = \"scout\"\ndescription = \"Scouts\"\nprompt = \"Scout.\"\n",
2852 )
2853 .unwrap();
2854 fs::create_dir_all(pkg.join("hooks")).unwrap();
2855 fs::write(
2856 pkg.join("hooks/hooks.toml"),
2857 "enabled = true\n[[hooks]]\nname = \"guard\"\nevent = \"turn_end\"\ncommand = \"true\"\n",
2858 )
2859 .unwrap();
2860 fs::write(
2861 pkg.join("plugin.json"),
2862 serde_json::json!({
2863 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2864 "name": "review-pkg",
2865 "version": "1.0.0",
2866 "extensions": {
2867 "net.codewhale": {
2868 "commands": {"path": "commands"},
2869 "agents": {"path": "agents"},
2870 "hooks": {"path": "hooks"}
2871 }
2872 }
2873 })
2874 .to_string(),
2875 )
2876 .unwrap();
2877
2878 let (conversion, reviewed_hash) = preview_dsh(&pkg).unwrap();
2879 assert_eq!(conversion.commands, ["commands/hello.md"]);
2880 assert_eq!(conversion.agents, ["agents/scout.toml"]);
2881 assert_eq!(conversion.hooks, ["hooks/hooks.toml"]);
2882
2883 fs::write(pkg.join("commands/hello.md"), "tampered\n").unwrap();
2884 let err = install_with_expected_content_hash(
2885 PluginInstallSource::parse(pkg.to_str().unwrap()).unwrap(),
2886 &plugins,
2887 DEFAULT_MAX_SIZE_BYTES,
2888 &allow_all(),
2889 &no_conflict(),
2890 &reviewed_hash,
2891 )
2892 .await
2893 .unwrap_err();
2894 assert!(err.downcast_ref::<PluginContentMismatch>().is_some());
2895 assert!(!plugins.join("review-pkg").exists());
2896
2897 let (updated_conversion, updated_hash) = preview_dsh(&pkg).unwrap();
2898 assert_eq!(updated_conversion.commands, ["commands/hello.md"]);
2899 let outcome = install_with_expected_content_hash(
2900 PluginInstallSource::parse(pkg.to_str().unwrap()).unwrap(),
2901 &plugins,
2902 DEFAULT_MAX_SIZE_BYTES,
2903 &allow_all(),
2904 &no_conflict(),
2905 &updated_hash,
2906 )
2907 .await
2908 .unwrap();
2909 let PluginInstallOutcome::Installed(installed) = outcome else {
2910 panic!("expected install");
2911 };
2912 let receipt_md = fs::read_to_string(installed.path.join("CONVERSION.md")).unwrap();
2913 assert!(receipt_md.contains("commands/hello.md"), "{receipt_md}");
2914 assert!(receipt_md.contains("agents/scout.toml"), "{receipt_md}");
2915 assert!(receipt_md.contains("hooks/hooks.toml"), "{receipt_md}");
2916 let receipt_json: serde_json::Value =
2917 serde_json::from_slice(&fs::read(installed.path.join("CONVERSION.json")).unwrap()).unwrap();
2918 assert_eq!(receipt_json["counts"]["commands"], 1);
2919 assert_eq!(receipt_json["counts"]["agents"], 1);
2920 assert_eq!(receipt_json["counts"]["hooks"], 1);
2921
2922 fs::write(pkg.join("commands/hello.md"), "hello v3\n").unwrap();
2923 let PluginUpdateResult::Updated(refreshed) =
2924 update("review-pkg", &plugins, DEFAULT_MAX_SIZE_BYTES, &allow_all())
2925 .await
2926 .unwrap()
2927 else {
2928 panic!("expected DSH update");
2929 };
2930 assert_eq!(
2931 fs::read_to_string(refreshed.path.join("commands/hello.md")).unwrap(),
2932 "hello v3\n"
2933 );
2934 }
2935
2936 #[test]
2937 fn package_with_native_code_and_plugin_json_commands_prevents_bytes_drift_and_collisions() {
2938 let tmp = tempfile::tempdir().unwrap();
2939 let pkg = write_dsh_base_package(
2940 &tmp.path().join("native-plus-cmd"),
2941 serde_json::json!({
2942 "name": "@demo/native-plus-cmd",
2943 "version": "1.0.0",
2944 "main": "index.js",
2945 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
2946 }),
2947 "- insert:\n - id: native-mod\n name: '@demo/native-plus-cmd'\n",
2948 );
2949 fs::write(pkg.join("index.js"), "export function apply() {}\n").unwrap();
2950 fs::create_dir_all(pkg.join("extra")).unwrap();
2951 fs::write(pkg.join("extra/run.md"), "Run custom command.\n").unwrap();
2952 fs::create_dir_all(pkg.join("commands")).unwrap();
2953 fs::write(pkg.join("commands/built.md"), "Built-in command.\n").unwrap();
2954 fs::write(
2955 pkg.join("plugin.json"),
2956 serde_json::json!({
2957 "$schema": "https://agent-plugins.org/schemas/plugin.json",
2958 "name": "native-plus-cmd",
2959 "version": "1.0.0",
2960 "extensions": {
2961 "net.codewhale": {
2962 "commands": {"paths": ["commands/built.md", "extra/run.md"]}
2963 }
2964 }
2965 })
2966 .to_string(),
2967 )
2968 .unwrap();
2969
2970 let out = tmp.path().join("out-native-plus-cmd");
2971 let converted = dsh::convert_package(&pkg, &out).unwrap();
2972 assert!(converted.requires_native);
2973 assert_eq!(
2974 converted.commands,
2975 ["commands/built.md", "commands/extra/run.md"]
2976 );
2977 assert_eq!(
2978 fs::read(out.join("source/commands/built.md")).unwrap(),
2979 fs::read(out.join("commands/built.md")).unwrap()
2980 );
2981 assert_eq!(
2982 fs::read(out.join("source/extra/run.md")).unwrap(),
2983 fs::read(out.join("commands/extra/run.md")).unwrap()
2984 );
2985 let validated =
2986 crate::manifest::PluginManifest::validate_from_path(&out.join("plugin.json")).unwrap();
2987 assert_eq!(validated.inventory.native, 1);
2988 assert_eq!(validated.inventory.commands, 2);
2989 }
2990
2991 #[test]
2992 fn case_variant_plugin_json_beside_dsh_package_is_handled_on_case_insensitive_fs() {
2993 let tmp = tempfile::tempdir().unwrap();
2994 let probe = tmp.path().join("case_probe.txt");
2995 fs::write(&probe, "x").unwrap();
2996 let case_insensitive = fs::symlink_metadata(tmp.path().join("CASE_PROBE.TXT")).is_ok();
2997
2998 let pkg = write_dsh_base_package(
2999 &tmp.path().join("case-pkg"),
3000 serde_json::json!({
3001 "name": "case-pkg",
3002 "version": "1.0.0",
3003 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3004 }),
3005 minimal_dsh_patch_with_skill(),
3006 );
3007 write_minimal_skill(&pkg.join("custom-skills"), "guide");
3008 fs::create_dir_all(pkg.join("commands")).unwrap();
3009 let crlf_cmd = "Line one\r\nLine two\r\n";
3010 fs::write(pkg.join("commands/hello.md"), crlf_cmd).unwrap();
3011 let crlf_pj = "{\r\n \"$schema\": \"https://agent-plugins.org/schemas/plugin.json\",\r\n \"name\": \"wrong-case-pkg\",\r\n \"extensions\": {\"net.codewhale\": {\"commands\": {\"path\": \"commands\"}}}\r\n}\r\n";
3012 fs::write(pkg.join("Plugin.JSON"), crlf_pj).unwrap();
3013
3014 if case_insensitive {
3015 assert_eq!(
3016 PluginInstallSource::parse(pkg.to_str().unwrap()).unwrap(),
3017 PluginInstallSource::Dsh(pkg.clone())
3018 );
3019 let err = dsh::convert_package(&pkg, &tmp.path().join("out-case-bad"))
3020 .unwrap_err()
3021 .to_string();
3022 assert!(err.contains("plugin.json"), "{err}");
3023 assert!(err.contains("package.json"), "{err}");
3024
3025 let valid_crlf_pj = "{\r\n \"$schema\": \"https://agent-plugins.org/schemas/plugin.json\",\r\n \"name\": \"case-pkg\",\r\n \"version\": \"1.0.0\",\r\n \"extensions\": {\"net.codewhale\": {\"commands\": {\"path\": \"commands\"}}}\r\n}\r\n";
3026 fs::write(pkg.join("Plugin.JSON"), valid_crlf_pj).unwrap();
3027 let out_ok = tmp.path().join("out-case-ok");
3028 let converted = dsh::convert_package(&pkg, &out_ok).unwrap();
3029 assert_eq!(converted.commands, ["commands/hello.md"]);
3030 assert_eq!(
3031 fs::read(out_ok.join("commands/hello.md")).unwrap(),
3032 crlf_cmd.as_bytes()
3033 );
3034 } else {
3035 let converted = dsh::convert_package(&pkg, &tmp.path().join("out-case-sens")).unwrap();
3036 assert!(converted.commands.is_empty());
3037 }
3038 }
3039
3040 #[test]
3041 fn tarball_with_dsh_package_and_plugin_json_merges_and_enforces_rules() {
3042 let tmp = tempfile::tempdir().unwrap();
3043 let dsh_pkg = serde_json::to_vec(&serde_json::json!({
3044 "name": "@acme/tar-combo",
3045 "version": "1.0.0",
3046 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3047 }))
3048 .unwrap();
3049 let patch = minimal_dsh_patch_with_skill().as_bytes();
3050 let skill = b"---\nname: guide\ndescription: demo\n---\nbody\n";
3051 let cmd = b"# Tar command\n";
3052 let valid_pj = serde_json::to_vec(&serde_json::json!({
3053 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3054 "name": "tar-combo",
3055 "version": "1.0.0",
3056 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
3057 }))
3058 .unwrap();
3059
3060 let ok_tar = tarball(&[
3061 ("repo/package.json", &dsh_pkg),
3062 ("repo/cordis.patch.yml", patch),
3063 ("repo/custom-skills/guide/SKILL.md", skill),
3064 ("repo/commands/hello.md", cmd),
3065 ("repo/plugin.json", &valid_pj),
3066 ]);
3067 let staged = tarball::stage_tarball(&ok_tar, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None).unwrap();
3068 assert_eq!(staged.name, "tar-combo");
3069 assert!(staged.staged_path.join("commands/hello.md").is_file());
3070 assert!(staged.staged_path.join("CONVERSION.json").is_file());
3071 let validated = crate::manifest::PluginManifest::validate_from_path(
3072 &staged.staged_path.join("plugin.json"),
3073 )
3074 .unwrap();
3075 assert_eq!(validated.inventory.skills, 1);
3076 assert_eq!(validated.inventory.commands, 1);
3077
3078 let forbidden_pj = serde_json::to_vec(&serde_json::json!({
3079 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3080 "name": "tar-combo",
3081 "version": "1.0.0",
3082 "extensions": {"net.codewhale": {"native": {"path": "index.mjs"}}}
3083 }))
3084 .unwrap();
3085 let bad_tar = tarball(&[
3086 ("repo/package.json", &dsh_pkg),
3087 ("repo/cordis.patch.yml", patch),
3088 ("repo/custom-skills/guide/SKILL.md", skill),
3089 ("repo/index.mjs", b"export function apply() {}\n"),
3090 ("repo/plugin.json", &forbidden_pj),
3091 ]);
3092 assert!(tarball::stage_tarball(&bad_tar, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None).is_err());
3093
3094 let huge_pkg_json = vec![b' '; 1_048_577];
3095 let oversized_pkg_tar = tarball(&[
3096 ("repo/package.json", &huge_pkg_json),
3097 ("repo/plugin.json", &valid_pj),
3098 ]);
3099 assert!(
3100 tarball::stage_tarball(&oversized_pkg_tar, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None)
3101 .is_err()
3102 );
3103
3104 let multi_tar = tarball(&[
3105 ("a/package.json", &dsh_pkg),
3106 ("a/cordis.patch.yml", patch),
3107 ("a/custom-skills/guide/SKILL.md", skill),
3108 ("b/plugin.json", &valid_pj),
3109 ("b/commands/hello.md", cmd),
3110 ]);
3111 assert!(tarball::stage_tarball(&multi_tar, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None).is_err());
3112 }
3113
3114 #[test]
3115 fn native_root_with_nested_dsh_integration_installs_as_one_bundle() {
3116 let tmp = tempfile::tempdir().unwrap();
3117 let plugin_json = serde_json::to_vec(&serde_json::json!({
3118 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3119 "name": "computer-use",
3120 "version": "0.16.3"
3121 }))
3122 .unwrap();
3123 let root_package = br#"{"name":"codewhale-cu-plugin","version":"0.16.3","private":true}"#;
3124 let dsh_package = serde_json::to_vec(&serde_json::json!({
3125 "name": "@codewhale/computer-use-dsh",
3126 "version": "0.6.0",
3127 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3128 }))
3129 .unwrap();
3130 let patch = minimal_dsh_patch_with_skill().as_bytes();
3131
3132 let archive = tarball(&[
3133 ("computer-use/plugin.json", &plugin_json),
3134 ("computer-use/package.json", root_package),
3135 ("computer-use/integrations/dsh/package.json", &dsh_package),
3136 ("computer-use/integrations/dsh/cordis.patch.yml", patch),
3137 ]);
3138 let staged = stage_tarball(&archive, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None).unwrap();
3139 assert_eq!(staged.name, "computer-use");
3140 assert!(!staged.staged_path.join("CONVERSION.json").exists());
3141 assert!(
3142 staged
3143 .staged_path
3144 .join("integrations/dsh/package.json")
3145 .is_file()
3146 );
3147
3148 let siblings = tarball(&[
3149 ("repo/native/plugin.json", &plugin_json),
3150 ("repo/harness/package.json", &dsh_package),
3151 ("repo/harness/cordis.patch.yml", patch),
3152 ]);
3153 let err = scan_tarball(&siblings, DEFAULT_MAX_SIZE_BYTES).unwrap_err();
3154 assert!(
3155 matches!(
3156 err.downcast_ref::<PluginInstallError>(),
3157 Some(PluginInstallError::PluginTomlRoots(2))
3158 ),
3159 "got: {err:#}"
3160 );
3161 }
3162
3163 #[test]
3164 fn tarball_with_dsh_package_and_other_manifest_spelling_is_refused() {
3165 let tmp = tempfile::tempdir().unwrap();
3166 let dsh_pkg = serde_json::to_vec(&serde_json::json!({
3167 "name": "other-tar",
3168 "version": "1.0.0",
3169 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3170 }))
3171 .unwrap();
3172 let patch = minimal_dsh_patch_with_skill().as_bytes();
3173 let skill = b"---\nname: guide\ndescription: demo\n---\nbody\n";
3174
3175 for (path, body) in [
3176 (
3177 "repo/.claude-plugin/plugin.json",
3178 &br#"{"name":"other-tar"}"#[..],
3179 ),
3180 ("repo/kimi.plugin.json", &br#"{"name":"other-tar"}"#[..]),
3181 ] {
3182 let archive = tarball(&[
3183 ("repo/package.json", &dsh_pkg),
3184 ("repo/cordis.patch.yml", patch),
3185 ("repo/custom-skills/guide/SKILL.md", skill),
3186 (path, body),
3187 ]);
3188 let err = tarball::stage_tarball(&archive, tmp.path(), DEFAULT_MAX_SIZE_BYTES, None)
3189 .unwrap_err()
3190 .to_string();
3191 assert!(err.contains("package.json"), "{path}: {err}");
3192 }
3193 }
3194
3195 #[test]
3196 fn native_dsh_bundle_allows_root_skills_only_when_skill_filesystem_row_is_active() {
3197 let tmp = tempfile::tempdir().unwrap();
3198 let active_pkg = write_dsh_base_package(
3199 &tmp.path().join("native-active-skills"),
3200 serde_json::json!({
3201 "name": "@demo/native-skills",
3202 "version": "1.0.0",
3203 "main": "index.js",
3204 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3205 }),
3206 "- insert:\n - id: native-mod\n name: '@demo/native-skills'\n - id: root-skills\n name: '@deepseek-ai/dsh-skill-filesystem'\n config:\n customSkillDirs: [skills]\n",
3207 );
3208 fs::write(active_pkg.join("index.js"), "export function apply() {}\n").unwrap();
3209 write_minimal_skill(&active_pkg.join("skills"), "guide");
3210 fs::create_dir_all(active_pkg.join("commands")).unwrap();
3211 fs::write(active_pkg.join("commands/hello.md"), "# Hello\n").unwrap();
3212 fs::write(
3213 active_pkg.join("plugin.json"),
3214 serde_json::json!({
3215 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3216 "name": "native-skills",
3217 "version": "1.0.0",
3218 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
3219 })
3220 .to_string(),
3221 )
3222 .unwrap();
3223
3224 let converted =
3225 dsh::convert_package(&active_pkg, &tmp.path().join("out-native-active")).unwrap();
3226 assert!(converted.requires_native);
3227 assert_eq!(converted.commands, ["commands/hello.md"]);
3228
3229 let disabled_pkg = write_dsh_base_package(
3230 &tmp.path().join("native-disabled-skills"),
3231 serde_json::json!({
3232 "name": "@demo/native-skills",
3233 "version": "1.0.0",
3234 "main": "index.js",
3235 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3236 }),
3237 "- insert:\n - id: native-mod\n name: '@demo/native-skills'\n - id: root-skills\n name: '@deepseek-ai/dsh-skill-filesystem'\n disabled: true\n config:\n customSkillDirs: [skills]\n",
3238 );
3239 fs::write(
3240 disabled_pkg.join("index.js"),
3241 "export function apply() {}\n",
3242 )
3243 .unwrap();
3244 write_minimal_skill(&disabled_pkg.join("skills"), "guide");
3245 fs::create_dir_all(disabled_pkg.join("commands")).unwrap();
3246 fs::write(disabled_pkg.join("commands/hello.md"), "# Hello\n").unwrap();
3247 fs::write(
3248 disabled_pkg.join("plugin.json"),
3249 fs::read(active_pkg.join("plugin.json")).unwrap(),
3250 )
3251 .unwrap();
3252
3253 let err = dsh::convert_package(&disabled_pkg, &tmp.path().join("out-native-disabled"))
3254 .unwrap_err()
3255 .to_string();
3256 assert!(err.contains("skills/"), "{err}");
3257
3258 let missing_row_pkg = write_dsh_base_package(
3259 &tmp.path().join("native-missing-skills"),
3260 serde_json::json!({
3261 "name": "@demo/native-skills",
3262 "version": "1.0.0",
3263 "main": "index.js",
3264 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3265 }),
3266 "- insert:\n - id: native-mod\n name: '@demo/native-skills'\n",
3267 );
3268 fs::write(
3269 missing_row_pkg.join("index.js"),
3270 "export function apply() {}\n",
3271 )
3272 .unwrap();
3273 write_minimal_skill(&missing_row_pkg.join("skills"), "guide");
3274 fs::create_dir_all(missing_row_pkg.join("commands")).unwrap();
3275 fs::write(missing_row_pkg.join("commands/hello.md"), "# Hello\n").unwrap();
3276 fs::write(
3277 missing_row_pkg.join("plugin.json"),
3278 fs::read(active_pkg.join("plugin.json")).unwrap(),
3279 )
3280 .unwrap();
3281 let err = dsh::convert_package(&missing_row_pkg, &tmp.path().join("out-native-missing"))
3282 .unwrap_err()
3283 .to_string();
3284 assert!(err.contains("skills/"), "{err}");
3285 }
3286
3287 #[cfg(unix)]
3288 #[tokio::test]
3289 async fn hardlinks_are_rejected_in_local_bundle_and_dsh_routing() {
3290 let tmp = tempfile::tempdir().unwrap();
3291 let plugins = tmp.path().join("plugins");
3292
3293 let outside_cmd = tmp.path().join("outside-cmd.md");
3294 fs::write(&outside_cmd, "outside\n").unwrap();
3295 let local_bundle = tmp.path().join("local-hardlink");
3296 fs::create_dir_all(local_bundle.join("commands")).unwrap();
3297 fs::write(
3298 local_bundle.join("plugin.json"),
3299 serde_json::json!({
3300 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3301 "name": "local-hardlink",
3302 "version": "1.0.0",
3303 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
3304 })
3305 .to_string(),
3306 )
3307 .unwrap();
3308 fs::hard_link(&outside_cmd, local_bundle.join("commands/linked.md")).unwrap();
3309 let err = install(
3310 PluginInstallSource::parse(local_bundle.to_str().unwrap()).unwrap(),
3311 &plugins,
3312 DEFAULT_MAX_SIZE_BYTES,
3313 &allow_all(),
3314 false,
3315 &no_conflict(),
3316 )
3317 .await
3318 .unwrap_err();
3319 assert!(
3320 format!("{err:#}").contains("hard link"),
3321 "expected hard link refusal, got: {err:#}"
3322 );
3323
3324 let outside_pkg_json = tmp.path().join("outside-package.json");
3325 fs::write(
3326 &outside_pkg_json,
3327 serde_json::json!({
3328 "name": "hardlink-dsh",
3329 "version": "1.0.0",
3330 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3331 })
3332 .to_string(),
3333 )
3334 .unwrap();
3335 let dsh_hardlink = tmp.path().join("dsh-hardlink");
3336 fs::create_dir_all(&dsh_hardlink).unwrap();
3337 fs::hard_link(&outside_pkg_json, dsh_hardlink.join("package.json")).unwrap();
3338 fs::write(
3339 dsh_hardlink.join("plugin.json"),
3340 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"hardlink-dsh","version":"1.0.0"}"#,
3341 )
3342 .unwrap();
3343 assert!(PluginInstallSource::parse(dsh_hardlink.to_str().unwrap()).is_err());
3344
3345 let bad_pkg_json = tmp.path().join("dsh-malformed");
3346 fs::create_dir_all(&bad_pkg_json).unwrap();
3347 fs::write(bad_pkg_json.join("package.json"), "{not-json").unwrap();
3348 fs::write(
3349 bad_pkg_json.join("plugin.json"),
3350 r#"{"$schema":"https://agent-plugins.org/schemas/plugin.json","name":"bad-pkg","version":"1.0.0"}"#,
3351 )
3352 .unwrap();
3353 assert!(PluginInstallSource::parse(bad_pkg_json.to_str().unwrap()).is_err());
3354 }
3355
3356 #[tokio::test]
3357 async fn plugin_json_only_folder_still_installs_by_its_plugin_json() {
3358 let tmp = tempfile::tempdir().unwrap();
3359 let plugins = tmp.path().join("plugins");
3360
3361 let pure_src = tmp.path().join("pure-plugin");
3362 fs::create_dir_all(pure_src.join("commands")).unwrap();
3363 fs::write(pure_src.join("commands/hello.md"), "# Hello\n").unwrap();
3364 fs::write(
3365 pure_src.join("plugin.json"),
3366 serde_json::json!({
3367 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3368 "name": "pure-plugin",
3369 "version": "1.0.0",
3370 "description": "Plain plugin.json",
3371 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
3372 })
3373 .to_string(),
3374 )
3375 .unwrap();
3376
3377 let source_parsed = PluginInstallSource::parse(pure_src.to_str().unwrap()).unwrap();
3378 assert_eq!(
3379 source_parsed,
3380 PluginInstallSource::LocalPath(pure_src.clone())
3381 );
3382 let expected =
3383 crate::manifest::PluginManifest::validate_from_path(&pure_src.join("plugin.json")).unwrap();
3384 let PluginInstallOutcome::Installed(installed_pure) = install(
3385 source_parsed,
3386 &plugins,
3387 DEFAULT_MAX_SIZE_BYTES,
3388 &allow_all(),
3389 false,
3390 &no_conflict(),
3391 )
3392 .await
3393 .unwrap() else {
3394 panic!("expected pure local install");
3395 };
3396 assert!(!installed_pure.path.join("CONVERSION.json").exists());
3397 let actual_pure = crate::manifest::PluginManifest::validate_from_path(
3398 &installed_pure.path.join("plugin.json"),
3399 )
3400 .unwrap();
3401 assert_eq!(installed_pure.content_hash, expected.content_hash);
3402 assert_eq!(
3403 actual_pure.content_hash,
3404 installed_pure.installed_content_hash
3405 );
3406 assert_eq!(actual_pure.capability_hash, expected.capability_hash);
3407
3408 let npm_src = tmp.path().join("npm-helper-plugin");
3409 fs::create_dir_all(npm_src.join("commands")).unwrap();
3410 fs::write(npm_src.join("commands/hello.md"), "# Hello\n").unwrap();
3411 fs::write(
3412 npm_src.join("package.json"),
3413 serde_json::json!({
3414 "name": "@demo/helper-scripts",
3415 "version": "9.9.9",
3416 "scripts": {"test": "echo ok"}
3417 })
3418 .to_string(),
3419 )
3420 .unwrap();
3421 fs::write(
3422 npm_src.join("plugin.json"),
3423 serde_json::json!({
3424 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3425 "name": "npm-helper-plugin",
3426 "version": "1.0.0",
3427 "description": "Plain plugin.json beside npm package.json",
3428 "extensions": {"net.codewhale": {"commands": {"path": "commands"}}}
3429 })
3430 .to_string(),
3431 )
3432 .unwrap();
3433 let expected_npm =
3434 crate::manifest::PluginManifest::validate_from_path(&npm_src.join("plugin.json")).unwrap();
3435 let npm_parsed = PluginInstallSource::parse(npm_src.to_str().unwrap()).unwrap();
3436 assert_eq!(npm_parsed, PluginInstallSource::LocalPath(npm_src.clone()));
3437 let PluginInstallOutcome::Installed(installed_npm) = install(
3438 npm_parsed,
3439 &plugins,
3440 DEFAULT_MAX_SIZE_BYTES,
3441 &allow_all(),
3442 false,
3443 &no_conflict(),
3444 )
3445 .await
3446 .unwrap() else {
3447 panic!("expected local install with ordinary package.json");
3448 };
3449 assert!(!installed_npm.path.join("CONVERSION.json").exists());
3450 let actual_npm = crate::manifest::PluginManifest::validate_from_path(
3451 &installed_npm.path.join("plugin.json"),
3452 )
3453 .unwrap();
3454 assert_eq!(actual_npm.manifest.plugin.name, "npm-helper-plugin");
3455 assert_eq!(installed_npm.content_hash, expected_npm.content_hash);
3456 assert_eq!(
3457 actual_npm.content_hash,
3458 installed_npm.installed_content_hash
3459 );
3460 assert_eq!(actual_npm.capability_hash, expected_npm.capability_hash);
3461 }
3462
3463 #[tokio::test]
3464 async fn a_hook_from_plugin_json_is_in_the_review_and_the_capability_hash() {
3465 let tmp = tempfile::tempdir().unwrap();
3466 let plugins = tmp.path().join("plugins");
3467
3468 let hook_a =
3469 "enabled = true\n[[hooks]]\nname = \"guard\"\nevent = \"turn_end\"\ncommand = \"true\"\n";
3470 let hook_b =
3471 "enabled = true\n[[hooks]]\nname = \"alt\"\nevent = \"turn_end\"\ncommand = \"true\"\n";
3472
3473 let plain = tmp.path().join("plain-hook-bundle");
3474 fs::create_dir_all(plain.join("hooks")).unwrap();
3475 fs::write(plain.join("hooks/a.toml"), hook_a).unwrap();
3476 fs::write(
3477 plain.join("plugin.json"),
3478 serde_json::json!({
3479 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3480 "name": "hook-parity",
3481 "version": "1.0.0",
3482 "extensions": {"net.codewhale": {"hooks": {"path": "hooks/a.toml"}}}
3483 })
3484 .to_string(),
3485 )
3486 .unwrap();
3487 let validated_plain =
3488 crate::manifest::PluginManifest::validate_from_path(&plain.join("plugin.json")).unwrap();
3489
3490 let dsh_pkg = write_dsh_base_package(
3491 &tmp.path().join("dsh-hook-bundle"),
3492 serde_json::json!({
3493 "name": "hook-parity",
3494 "version": " 1.0.0 ",
3495 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3496 }),
3497 "[]\n",
3498 );
3499 fs::create_dir_all(dsh_pkg.join("hooks")).unwrap();
3500 fs::write(dsh_pkg.join("hooks/a.toml"), hook_a).unwrap();
3501 fs::write(dsh_pkg.join("hooks/b.toml"), hook_b).unwrap();
3502 fs::create_dir_all(dsh_pkg.join("empty-commands")).unwrap();
3503 let sibling_pj_a = serde_json::json!({
3504 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3505 "name": "hook-parity",
3506 "version": "1.0.0",
3507 "extensions": {
3508 "net.codewhale": {
3509 "commands": {"path": "empty-commands"},
3510 "hooks": {"path": "hooks/a.toml"}
3511 }
3512 }
3513 })
3514 .to_string();
3515 fs::write(dsh_pkg.join("plugin.json"), &sibling_pj_a).unwrap();
3516
3517 let (previewed, reviewed_hash) = preview_dsh(&dsh_pkg).unwrap();
3518 assert_eq!(previewed.hooks, ["hooks/a.toml"]);
3519 assert!(previewed.commands.is_empty());
3520
3521 let PluginInstallOutcome::Installed(installed) = install_with_expected_content_hash(
3522 PluginInstallSource::parse(dsh_pkg.to_str().unwrap()).unwrap(),
3523 &plugins,
3524 DEFAULT_MAX_SIZE_BYTES,
3525 &allow_all(),
3526 &no_conflict(),
3527 &reviewed_hash,
3528 )
3529 .await
3530 .unwrap() else {
3531 panic!("expected install");
3532 };
3533 let validated_dsh =
3534 crate::manifest::PluginManifest::validate_from_path(&installed.path.join("plugin.json"))
3535 .unwrap();
3536 assert_eq!(
3537 serde_json::to_value(&validated_dsh.manifest.capabilities).unwrap(),
3538 serde_json::to_value(&validated_plain.manifest.capabilities).unwrap()
3539 );
3540 assert_eq!(
3541 validated_dsh.capability_hash,
3542 validated_plain.capability_hash
3543 );
3544 assert!(installed.path.join("hooks/a.toml").is_file());
3545 assert!(!installed.path.join("empty-commands").exists());
3546
3547 fs::write(
3548 dsh_pkg.join("hooks/a.toml"),
3549 hook_a.replace("\"true\"", "\"false\""),
3550 )
3551 .unwrap();
3552 let err_hook = install_with_expected_content_hash(
3553 PluginInstallSource::parse(dsh_pkg.to_str().unwrap()).unwrap(),
3554 &plugins,
3555 DEFAULT_MAX_SIZE_BYTES,
3556 &allow_all(),
3557 &no_conflict(),
3558 &reviewed_hash,
3559 )
3560 .await
3561 .unwrap_err();
3562 assert!(err_hook.downcast_ref::<PluginContentMismatch>().is_some());
3563
3564 fs::write(dsh_pkg.join("hooks/a.toml"), hook_a).unwrap();
3565 let (_, clean_hash) = preview_dsh(&dsh_pkg).unwrap();
3566 assert_eq!(clean_hash, reviewed_hash);
3567
3568 fs::write(
3569 dsh_pkg.join("plugin.json"),
3570 sibling_pj_a.replace("hooks/a.toml", "hooks/b.toml"),
3571 )
3572 .unwrap();
3573 let err_pj = install_with_expected_content_hash(
3574 PluginInstallSource::parse(dsh_pkg.to_str().unwrap()).unwrap(),
3575 &plugins,
3576 DEFAULT_MAX_SIZE_BYTES,
3577 &allow_all(),
3578 &no_conflict(),
3579 &reviewed_hash,
3580 )
3581 .await
3582 .unwrap_err();
3583 assert!(err_pj.downcast_ref::<PluginContentMismatch>().is_some());
3584
3585 let empty_only = write_dsh_base_package(
3586 &tmp.path().join("empty-only-cmd"),
3587 serde_json::json!({
3588 "name": "empty-only-cmd",
3589 "version": "1.0.0",
3590 "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}
3591 }),
3592 "[]\n",
3593 );
3594 fs::create_dir_all(empty_only.join("empty-commands")).unwrap();
3595 fs::write(
3596 empty_only.join("plugin.json"),
3597 serde_json::json!({
3598 "$schema": "https://agent-plugins.org/schemas/plugin.json",
3599 "name": "empty-only-cmd",
3600 "version": "1.0.0",
3601 "extensions": {"net.codewhale": {"commands": {"path": "empty-commands"}}}
3602 })
3603 .to_string(),
3604 )
3605 .unwrap();
3606 assert!(dsh::convert_package(&empty_only, &tmp.path().join("out-empty-only")).is_err());
3607 }
3608
3609 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3610 async fn prepare_remote_install_leaves_plugins_dir_empty_and_checks_exact_hash() {
3611 let tmp = tempfile::tempdir().unwrap();
3612 let plugins = tmp.path().join("user-plugins");
3613 let bytes = remote_bundle_bytes("remote-preview", b"hello");
3614 let url = serve_bodies(vec![bytes]);
3615 let source = match PluginInstallSource::parse(&url).unwrap() {
3616 PluginInstallSource::Remote(remote) => remote,
3617 other => panic!("expected remote source, got {other:?}"),
3618 };
3619
3620 let needs_approval = prepare_remote_install(
3621 source.clone(),
3622 DEFAULT_MAX_SIZE_BYTES,
3623 &NetworkPolicy::default(),
3624 )
3625 .await
3626 .unwrap();
3627 assert!(matches!(
3628 needs_approval,
3629 RemotePreviewOutcome::NeedsApproval(_)
3630 ));
3631 assert!(!plugins.exists());
3632
3633 let prepared = match prepare_remote_install(source, DEFAULT_MAX_SIZE_BYTES, &loopback_policy())
3634 .await
3635 .unwrap()
3636 {
3637 RemotePreviewOutcome::Ready(prepared) => prepared,
3638 other => panic!("expected ready remote preview, got {other:?}"),
3639 };
3640 assert_eq!(prepared.name, "remote-preview");
3641 assert!(!plugins.exists());
3642
3643 let mismatch = install_prepared_remote(
3644 &prepared,
3645 &plugins,
3646 DEFAULT_MAX_SIZE_BYTES,
3647 &loopback_policy(),
3648 &no_conflict(),
3649 "0000000000000000000000000000000000000000000000000000000000000000",
3650 )
3651 .await
3652 .unwrap_err();
3653 assert!(mismatch.downcast_ref::<PluginContentMismatch>().is_some());
3654 assert!(!plugins.join("remote-preview").exists());
3655
3656 let outcome = install_prepared_remote(
3657 &prepared,
3658 &plugins,
3659 DEFAULT_MAX_SIZE_BYTES,
3660 &loopback_policy(),
3661 &no_conflict(),
3662 &prepared.content_hash,
3663 )
3664 .await
3665 .unwrap();
3666 assert!(matches!(outcome, PluginInstallOutcome::Installed(_)));
3667 assert!(plugins.join("remote-preview").is_dir());
3668 }
3669
3670 #[tokio::test]
3671 async fn dsh_connection_template_installs_as_written() {
3672 let template = Path::new(env!("CARGO_MANIFEST_DIR"))
3673 .join("../skills/assets/dsh-creator/skills/cordis-plugin-development/templates/mcp");
3674 let tmp = tempfile::tempdir().unwrap();
3675 let out = tmp.path().join("converted-template");
3676 let converted = dsh::convert_package(&template, &out).unwrap();
3677 assert_eq!(converted.remote_servers, vec!["demo".to_string()]);
3678 assert!(converted.network_hosts.contains(&"127.0.0.1".to_string()));
3679
3680 let mcp_json: serde_json::Value =
3681 serde_json::from_str(&fs::read_to_string(out.join("mcp.json")).unwrap()).unwrap();
3682 assert_eq!(mcp_json["mcpServers"]["demo"]["type"], "streamable-http");
3683 assert_eq!(
3684 mcp_json["mcpServers"]["demo"]["url"],
3685 "http://127.0.0.1:3000/mcp"
3686 );
3687 assert_eq!(
3688 mcp_json["mcpServers"]["demo"]["extensions"]["net.codewhale"]["required"],
3689 true
3690 );
3691
3692 let validated =
3693 crate::manifest::PluginManifest::validate_from_path(&out.join("plugin.json")).unwrap();
3694 let server = &validated.manifest.mcp_servers.as_ref().unwrap()["demo"];
3695 assert!(server.required);
3696 assert!(server.is_enabled());
3697 assert_eq!(server.url.as_deref(), Some("http://127.0.0.1:3000/mcp"));
3698 assert!(
3699 validated
3700 .manifest
3701 .capabilities
3702 .network_hosts
3703 .contains(&"127.0.0.1".to_string())
3704 );
3705
3706 let plugins = tmp.path().join("user-plugins");
3707 let outcome = install(
3708 PluginInstallSource::parse(template.to_str().unwrap()).unwrap(),
3709 &plugins,
3710 DEFAULT_MAX_SIZE_BYTES,
3711 &allow_all(),
3712 false,
3713 &no_conflict(),
3714 )
3715 .await
3716 .unwrap();
3717 let PluginInstallOutcome::Installed(installed) = outcome else {
3718 panic!("expected installed template");
3719 };
3720 let installed_mcp: serde_json::Value =
3721 serde_json::from_str(&fs::read_to_string(installed.path.join("mcp.json")).unwrap())
3722 .unwrap();
3723 assert_eq!(installed_mcp, mcp_json);
3724 }
3725
3726 #[test]
3727 fn dsh_fail_on_startup_error_false_or_absent_keeps_today_output() {
3728 let tmp = tempfile::tempdir().unwrap();
3729 let absent_pkg = write_dsh_base_package(
3730 &tmp.path().join("absent"),
3731 serde_json::json!({
3732 "name": "@demo/absent",
3733 "version": "1.0.0",
3734 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
3735 }),
3736 "- insert:\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: https://example.com/mcp\n",
3737 );
3738 let false_pkg = write_dsh_base_package(
3739 &tmp.path().join("false"),
3740 serde_json::json!({
3741 "name": "@demo/false",
3742 "version": "1.0.0",
3743 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
3744 }),
3745 "- insert:\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: https://example.com/mcp\n failOnStartupError: false\n",
3746 );
3747 let out_absent = tmp.path().join("out-absent");
3748 let out_false = tmp.path().join("out-false");
3749 dsh::convert_package(&absent_pkg, &out_absent).unwrap();
3750 dsh::convert_package(&false_pkg, &out_false).unwrap();
3751
3752 let absent_mcp: serde_json::Value =
3753 serde_json::from_str(&fs::read_to_string(out_absent.join("mcp.json")).unwrap()).unwrap();
3754 let false_mcp: serde_json::Value =
3755 serde_json::from_str(&fs::read_to_string(out_false.join("mcp.json")).unwrap()).unwrap();
3756 assert_eq!(absent_mcp, false_mcp);
3757 assert_eq!(
3758 false_mcp["mcpServers"]["demo"]["extensions"]["net.codewhale"],
3759 serde_json::json!({})
3760 );
3761
3762 let validated =
3763 crate::manifest::PluginManifest::validate_from_path(&out_false.join("plugin.json"))
3764 .unwrap();
3765 assert!(!validated.manifest.mcp_servers.as_ref().unwrap()["demo"].required);
3766 }
3767
3768 #[test]
3769 fn dsh_fail_on_startup_error_non_boolean_is_refused() {
3770 let tmp = tempfile::tempdir().unwrap();
3771 for (label, flag_yaml) in [
3772 ("string", "\"true\""),
3773 ("number", "1"),
3774 ("map", "{ enable: true }"),
3775 ("null", "null"),
3776 ] {
3777 let pkg = write_dsh_base_package(
3778 &tmp.path().join(label),
3779 serde_json::json!({
3780 "name": format!("@demo/{label}"),
3781 "version": "1.0.0",
3782 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
3783 }),
3784 &format!(
3785 "- insert:\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: demo\n transport: streamable-http\n url: https://example.com/mcp\n failOnStartupError: {flag_yaml}\n"
3786 ),
3787 );
3788 let err = dsh::convert_package(&pkg, &tmp.path().join(format!("out-{label}")))
3789 .unwrap_err()
3790 .to_string();
3791 assert!(err.contains("boolean"), "{label}: {err}");
3792 }
3793 }
3794
3795 #[test]
3796 fn dsh_row_turned_off_with_the_flag_converts_and_is_not_enabled() {
3797 let tmp = tempfile::tempdir().unwrap();
3798 let pkg = write_dsh_base_package(
3799 &tmp.path().join("turned-off"),
3800 serde_json::json!({
3801 "name": "@demo/turned-off",
3802 "version": "1.0.0",
3803 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
3804 }),
3805 "- insert:\n - id: demo-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n disabled: true\n config:\n serverName: demo\n transport: streamable-http\n url: http://127.0.0.1:3000/mcp\n failOnStartupError: true\n",
3806 );
3807 let out = tmp.path().join("out-turned-off");
3808 dsh::convert_package(&pkg, &out).unwrap();
3809
3810 let mcp_json: serde_json::Value =
3811 serde_json::from_str(&fs::read_to_string(out.join("mcp.json")).unwrap()).unwrap();
3812 assert_eq!(
3813 mcp_json["mcpServers"]["demo"]["extensions"]["net.codewhale"],
3814 serde_json::json!({ "required": true, "disabled": true })
3815 );
3816
3817 let validated =
3818 crate::manifest::PluginManifest::validate_from_path(&out.join("plugin.json")).unwrap();
3819 let server = &validated.manifest.mcp_servers.as_ref().unwrap()["demo"];
3820 assert!(server.required);
3821 assert!(server.disabled);
3822 assert!(!server.is_enabled());
3823 }
3824
3825 #[test]
3826 fn dsh_named_group_module_is_included_in_reviewed_module_closure() {
3827 let tmp = tempfile::tempdir().unwrap();
3828 let pkg = write_dsh_base_package(
3829 &tmp.path().join("named-group"),
3830 serde_json::json!({
3831 "name": "demo-named-group",
3832 "version": "1.0.0",
3833 "type": "module",
3834 "exports": {
3835 ".": { "default": "./lib/index.js" },
3836 "./bundle": { "default": "./lib/bundle.js" }
3837 },
3838 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
3839 }),
3840 "- insert:\n - id: demo-bundle\n name: demo-named-group/bundle\n group: true\n config:\n - id: demo-core\n name: demo-named-group\n",
3841 );
3842 fs::create_dir_all(pkg.join("lib")).unwrap();
3843 fs::write(pkg.join("lib/index.js"), "export function apply() {}\n").unwrap();
3844 fs::write(
3845 pkg.join("lib/bundle.js"),
3846 "export default class Bundle {}\n",
3847 )
3848 .unwrap();
3849
3850 let out = tmp.path().join("out-named-group");
3851 dsh::convert_package(&pkg, &out).unwrap();
3852 let comp: serde_json::Value =
3853 serde_json::from_str(&fs::read_to_string(out.join("native/composition.json")).unwrap())
3854 .unwrap();
3855 let modules = comp["modules"].as_array().unwrap();
3856 assert!(
3857 modules
3858 .iter()
3859 .any(|m| m["name"] == "demo-named-group/bundle" && m["path"] == "lib/bundle.js"),
3860 "expected demo-named-group/bundle in reviewed module closure, got {modules:?}"
3861 );
3862 }
3863
3864 #[test]
3865 fn dsh_npm_deps_scans_bundled_js_asset_above_two_mib_within_eight_mib_cap() {
3866 let tmp = tempfile::tempdir().unwrap();
3867 let manifest = serde_json::json!({
3868 "name": "@demo/large-asset",
3869 "version": "1.0.0",
3870 "type": "module",
3871 "main": "./lib/index.js",
3872 "dsh": { "bundle": { "patch": "./cordis.patch.yml" } }
3873 });
3874 let pkg = write_dsh_base_package(
3875 &tmp.path().join("large-asset"),
3876 manifest,
3877 "- insert:\n - id: demo-large\n name: '@demo/large-asset'\n",
3878 );
3879 fs::create_dir_all(pkg.join("lib")).unwrap();
3880 let mut big = String::with_capacity(2_500_000);
3881 big.push_str("export function apply() {}\n// ");
3882 big.push_str(&"a".repeat(2_400_000));
3883 big.push('\n');
3884 fs::write(pkg.join("lib/index.js"), big).unwrap();
3885
3886 let policy = codewhale_net::network_policy::NetworkPolicy::default();
3887 let no_dependencies = dsh::Value::Map(Vec::new());
3888 let stage = npm_deps::maybe_stage_with_dependencies(&pkg, &no_dependencies, &[], &policy)
3889 .expect("2.4 MiB bundled JS asset should scan cleanly within 8 MiB limit");
3890 assert!(stage.is_none());
3891 }
3892
3892 lines RUST