fidius-cli 0.0.4

CLI for the Fidius plugin framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
// Copyright 2026 Colliery, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::path::Path;

use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};

type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;

// ─── Dependency resolution ───────────────────────────────────────────────────

/// Resolve a dependency string to a Cargo.toml dependency value.
///
/// Logic:
/// 1. If `value` is a path that exists on disk → `{ path = "..." }`
/// 2. If `version_override` is set → `"<version>"`
/// 3. Check crates.io for `value` → if found, use latest version
/// 4. Warn and fall back to `{ path = "<value>" }`
fn resolve_dep(value: &str, version_override: Option<&str>) -> String {
    // Check if it's a filesystem path
    if Path::new(value).exists() {
        // Canonicalize so the path works from any crate directory
        if let Ok(abs) = std::fs::canonicalize(value) {
            return format!("{{ path = \"{}\" }}", abs.display());
        }
        return format!("{{ path = \"{}\" }}", value);
    }

    // If version explicitly pinned, use it
    if let Some(ver) = version_override {
        return format!("\"{}\"", ver);
    }

    // Try crates.io
    if let Some(ver) = check_crates_io(value) {
        return format!("\"{}\"", ver);
    }

    // Warn and fall back to path dep
    eprintln!(
        "warning: could not find '{}' as a local path or on crates.io, using path dep",
        value
    );
    format!("{{ path = \"{}\" }}", value)
}

/// Check crates.io for a crate and return its latest version, if found.
fn check_crates_io(name: &str) -> Option<String> {
    let url = format!("https://crates.io/api/v1/crates/{}", name);
    let mut response = ureq::get(&url)
        .header(
            "User-Agent",
            "fidius-cli (https://github.com/colliery-io/fidius)",
        )
        .call()
        .ok()?;

    let body_str = response.body_mut().read_to_string().ok()?;
    let body: serde_json::Value = serde_json::from_str(&body_str).ok()?;
    body["crate"]["max_stable_version"]
        .as_str()
        .map(String::from)
}

// ─── init-interface ──────────────────────────────────────────────────────────

pub fn init_interface(
    name: &str,
    trait_name: &str,
    path: Option<&Path>,
    version: Option<&str>,
    extension: Option<&str>,
) -> Result {
    let base = path.unwrap_or_else(|| Path::new("."));
    let crate_dir = base.join(name);

    if crate_dir.exists() {
        return Err(format!("directory '{}' already exists", crate_dir.display()).into());
    }

    let src_dir = crate_dir.join("src");
    std::fs::create_dir_all(&src_dir)?;

    // Resolve fidius dependency
    let fidius_dep = resolve_dep("fidius", version);

    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"

[dependencies]
fidius = {fidius_dep}
"#
    );

    let lib_rs = format!(
        r#"pub use fidius::{{plugin_impl, PluginError}};

#[fidius::plugin_interface(version = 1, buffer = PluginAllocated)]
pub trait {trait_name}: Send + Sync {{
    fn process(&self, input: String) -> String;
}}
"#
    );

    std::fs::write(crate_dir.join("Cargo.toml"), cargo_toml)?;
    std::fs::write(src_dir.join("lib.rs"), lib_rs)?;

    // Write fidius.toml with interface metadata (extension, etc.)
    if let Some(ext) = extension {
        let fidius_toml = format!("extension = \"{ext}\"\n");
        std::fs::write(crate_dir.join("fidius.toml"), fidius_toml)?;
    }

    println!("Created interface crate: {}", crate_dir.display());
    Ok(())
}

// ─── init-plugin ─────────────────────────────────────────────────────────────

pub fn init_plugin(
    name: &str,
    interface: &str,
    trait_name: &str,
    path: Option<&Path>,
    version: Option<&str>,
) -> Result {
    let base = path.unwrap_or_else(|| Path::new("."));
    let crate_dir = base.join(name);

    if crate_dir.exists() {
        return Err(format!("directory '{}' already exists", crate_dir.display()).into());
    }

    let src_dir = crate_dir.join("src");
    std::fs::create_dir_all(&src_dir)?;

    // Resolve dependencies
    let interface_dep = resolve_dep(interface, version);
    let fidius_dep = resolve_dep("fidius", version);

    // Extract the crate name from the interface value (strip path components)
    let interface_crate = Path::new(interface)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(interface);

    // Convert crate name to Rust identifier (hyphens → underscores)
    let interface_mod = interface_crate.replace('-', "_");

    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
{interface_crate} = {interface_dep}
fidius = {fidius_dep}
"#
    );

    let struct_name = format!("My{trait_name}");

    let lib_rs = format!(
        r#"use {interface_mod}::{{plugin_impl, {trait_name}, PluginError, __fidius_{trait_name}}};

pub struct {struct_name};

#[plugin_impl({trait_name})]
impl {trait_name} for {struct_name} {{
    fn process(&self, input: String) -> String {{
        format!("processed: {{}}", input)
    }}
}}

fidius::fidius_plugin_registry!();
"#
    );

    std::fs::write(crate_dir.join("Cargo.toml"), cargo_toml)?;
    std::fs::write(src_dir.join("lib.rs"), lib_rs)?;

    // Read interface's fidius.toml for extension (if interface is a local path)
    let interface_path = Path::new(interface);
    let extension = if interface_path.is_dir() {
        let fidius_toml_path = interface_path.join("fidius.toml");
        if fidius_toml_path.exists() {
            let content = std::fs::read_to_string(&fidius_toml_path)?;
            let table: toml::Table = content.parse().unwrap_or_default();
            table
                .get("extension")
                .and_then(|v| v.as_str())
                .map(String::from)
        } else {
            None
        }
    } else {
        None
    };

    // Generate package.toml
    let ext_line = match &extension {
        Some(ext) => format!("\nextension = \"{ext}\""),
        None => String::new(),
    };
    let package_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
interface = "{interface_crate}"
interface_version = 1{ext_line}

[metadata]
"#
    );
    std::fs::write(crate_dir.join("package.toml"), package_toml)?;

    println!("Created plugin crate: {}", crate_dir.display());
    Ok(())
}

// ─── keygen ──────────────────────────────────────────────────────────────────

pub fn keygen(out: &str) -> Result {
    use rand::rngs::OsRng;

    let signing_key = SigningKey::generate(&mut OsRng);
    let verifying_key = signing_key.verifying_key();

    let secret_path = format!("{}.secret", out);
    let public_path = format!("{}.public", out);

    std::fs::write(&secret_path, signing_key.to_bytes())?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&secret_path, std::fs::Permissions::from_mode(0o600))?;
    }
    std::fs::write(&public_path, verifying_key.to_bytes())?;

    println!("Generated keypair:");
    println!("  Secret: {}", secret_path);
    println!("  Public: {}", public_path);
    Ok(())
}

// ─── sign ────────────────────────────────────────────────────────────────────

pub fn sign(key_path: &Path, dylib_path: &Path) -> Result {
    let key_bytes: [u8; 32] = std::fs::read(key_path)?
        .try_into()
        .map_err(|_| "secret key must be exactly 32 bytes")?;

    let signing_key = SigningKey::from_bytes(&key_bytes);
    let dylib_bytes = std::fs::read(dylib_path)?;
    let signature = signing_key.sign(&dylib_bytes);

    let sig_path = dylib_path.with_extension(format!(
        "{}.sig",
        dylib_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
    ));

    std::fs::write(&sig_path, signature.to_bytes())?;
    println!("Signed: {} -> {}", dylib_path.display(), sig_path.display());
    Ok(())
}

// ─── verify ──────────────────────────────────────────────────────────────────

pub fn verify(key_path: &Path, dylib_path: &Path) -> Result {
    let key_bytes: [u8; 32] = std::fs::read(key_path)?
        .try_into()
        .map_err(|_| "public key must be exactly 32 bytes")?;

    let verifying_key =
        VerifyingKey::from_bytes(&key_bytes).map_err(|e| format!("invalid public key: {e}"))?;

    let dylib_bytes = std::fs::read(dylib_path)?;

    let sig_path = dylib_path.with_extension(format!(
        "{}.sig",
        dylib_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
    ));

    let sig_bytes: [u8; 64] = std::fs::read(&sig_path)
        .map_err(|_| format!("signature file not found: {}", sig_path.display()))?
        .try_into()
        .map_err(|_| "signature must be exactly 64 bytes")?;

    let signature = Signature::from_bytes(&sig_bytes);

    match verifying_key.verify(&dylib_bytes, &signature) {
        Ok(()) => {
            println!("Signature valid: {}", dylib_path.display());
            Ok(())
        }
        Err(_) => Err(format!("Signature INVALID: {}", dylib_path.display()).into()),
    }
}

// ─── inspect ─────────────────────────────────────────────────────────────────

pub fn inspect(dylib_path: &Path) -> Result {
    let loaded = fidius_host::loader::load_library(dylib_path)
        .map_err(|e| format!("failed to load {}: {e}", dylib_path.display()))?;

    println!("Plugin Registry: {}", dylib_path.display());
    println!("  Plugins: {}", loaded.plugins.len());
    println!();

    for (i, plugin) in loaded.plugins.iter().enumerate() {
        let info = &plugin.info;
        println!("  [{}] {}", i, info.name);
        println!("      Interface: {}", info.interface_name);
        println!("      Interface hash: {:#018x}", info.interface_hash);
        println!("      Interface version: {}", info.interface_version);
        println!("      Buffer strategy: {:?}", info.buffer_strategy);
        println!("      Wire format: {:?}", info.wire_format);
        println!("      Capabilities: {:#018x}", info.capabilities);
    }

    Ok(())
}

// ─── package validate ────────────────────────────────────────────────────────

pub fn package_validate(dir: &Path) -> Result {
    let manifest = fidius_core::package::load_manifest_untyped(dir)?;
    let pkg = &manifest.package;

    println!("Package: {} v{}", pkg.name, pkg.version);
    println!(
        "  Interface: {} (version {})",
        pkg.interface, pkg.interface_version
    );
    println!(
        "  Metadata: {} field(s)",
        manifest.metadata.as_table().map_or(0, |t| t.len())
    );
    println!("\nManifest valid.");
    Ok(())
}

// ─── package build ───────────────────────────────────────────────────────────

pub fn package_build(dir: &Path, release: bool) -> Result {
    let manifest = fidius_core::package::load_manifest_untyped(dir)?;
    let cargo_toml = dir.join("Cargo.toml");
    if !cargo_toml.exists() {
        return Err(format!("Cargo.toml not found in {}", dir.display()).into());
    }

    println!(
        "Building package: {} v{}",
        manifest.package.name, manifest.package.version
    );

    let mut cmd = std::process::Command::new("cargo");
    cmd.arg("build").arg("--manifest-path").arg(&cargo_toml);
    if release {
        cmd.arg("--release");
    }

    let output = cmd.output()?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("build failed:\n{}", stderr).into());
    }

    let profile = if release { "release" } else { "debug" };
    println!(
        "Build successful. Output in {}/target/{}/",
        dir.display(),
        profile
    );
    Ok(())
}

// ─── package inspect ─────────────────────────────────────────────────────────

pub fn package_inspect(dir: &Path) -> Result {
    let manifest = fidius_core::package::load_manifest_untyped(dir)?;
    let pkg = &manifest.package;

    println!("Package: {}", dir.display());
    println!("  Name: {}", pkg.name);
    println!("  Version: {}", pkg.version);
    println!("  Interface: {}", pkg.interface);
    println!("  Interface version: {}", pkg.interface_version);
    if let Some(table) = manifest.metadata.as_table() {
        println!("  Metadata:");
        for (key, value) in table {
            println!("    {} = {}", key, value);
        }
    }
    Ok(())
}

// ─── package sign ────────────────────────────────────────────────────────────

pub fn package_sign(key_path: &Path, dir: &Path) -> Result {
    if !dir.join("package.toml").exists() {
        return Err(format!("package.toml not found in {}", dir.display()).into());
    }

    let key_bytes: [u8; 32] = std::fs::read(key_path)?
        .try_into()
        .map_err(|_| "secret key must be exactly 32 bytes")?;

    let signing_key = SigningKey::from_bytes(&key_bytes);
    let digest = fidius_core::package::package_digest(dir)?;
    let signature = signing_key.sign(&digest);

    let sig_path = dir.join("package.sig");
    std::fs::write(&sig_path, signature.to_bytes())?;
    println!(
        "Signed package: {} -> {}",
        dir.display(),
        sig_path.display()
    );
    Ok(())
}

// ─── package verify ──────────────────────────────────────────────────────────

pub fn package_verify(key_path: &Path, dir: &Path) -> Result {
    if !dir.join("package.toml").exists() {
        return Err(format!("package.toml not found in {}", dir.display()).into());
    }

    let key_bytes: [u8; 32] = std::fs::read(key_path)?
        .try_into()
        .map_err(|_| "public key must be exactly 32 bytes")?;

    let verifying_key =
        VerifyingKey::from_bytes(&key_bytes).map_err(|e| format!("invalid public key: {e}"))?;

    let sig_path = dir.join("package.sig");
    let sig_bytes: [u8; 64] = std::fs::read(&sig_path)
        .map_err(|_| format!("signature file not found: {}", sig_path.display()))?
        .try_into()
        .map_err(|_| "signature must be exactly 64 bytes")?;

    let signature = Signature::from_bytes(&sig_bytes);
    let digest = fidius_core::package::package_digest(dir)?;

    match verifying_key.verify(&digest, &signature) {
        Ok(()) => {
            println!("Package signature valid: {}", dir.display());
            Ok(())
        }
        Err(_) => Err(format!("Package signature INVALID: {}", dir.display()).into()),
    }
}

// ─── package pack ───────────────────────────────────────────────────────────

pub fn package_pack(dir: &Path, output: Option<&Path>) -> Result {
    let result = fidius_core::package::pack_package(dir, output)?;

    if result.unsigned {
        eprintln!("warning: package is unsigned (no package.sig found)");
    }

    let size = std::fs::metadata(&result.path)?.len();
    let human_size = if size >= 1024 * 1024 {
        format!("{:.1} MB", size as f64 / (1024.0 * 1024.0))
    } else if size >= 1024 {
        format!("{:.1} KB", size as f64 / 1024.0)
    } else {
        format!("{size} B")
    };

    println!("Packed: {} ({human_size})", result.path.display());
    Ok(())
}

// ─── package unpack ─────────────────────────────────────────────────────────

pub fn package_unpack(archive: &Path, dest: Option<&Path>) -> Result {
    let dest = dest.unwrap_or_else(|| Path::new("."));
    let pkg_dir = fidius_core::package::unpack_package(archive, dest)?;
    println!("Unpacked: {}", pkg_dir.display());
    Ok(())
}