forge-guard 0.1.9

Pre-deployment smart contract auditing framework for Foundry
Documentation
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Plugin architecture — extensible plugin system for forge-guard.
//!
//! Plugins can be either:
//! - **Built-in**: Rust types implementing the `Plugin` trait, registered at compile time.
//! - **External**: Standalone binaries or scripts that communicate via a JSON IPC protocol
//!   (stdin → JSON context, stdout → JSON findings, stderr → logs).

use crate::core::{Finding, ForgeGuardError, ProjectConfig, Severity};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Instant;

// ── Re-export the core trait ─────────────────────────────────────

/// Re-export the Plugin trait for plugin authors.
pub use Plugin as PluginTrait;

/// Result from a plugin execution.
pub type PluginResult = std::result::Result<Vec<Finding>, ForgeGuardError>;

/// Context passed to plugins during execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginContext {
    /// The current project configuration.
    pub config: ProjectConfig,
    /// Source files being analyzed (absolute paths).
    pub source_files: Vec<PathBuf>,
    /// Additional metadata (chain name, flags, etc.).
    #[serde(default)]
    pub metadata: HashMap<String, String>,
}

impl PluginContext {
    /// Create a new plugin context.
    pub fn new(config: &ProjectConfig, source_files: Vec<PathBuf>) -> Self {
        Self {
            config: config.clone(),
            source_files,
            metadata: HashMap::new(),
        }
    }

    /// Add a metadata key-value pair.
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }
}

/// Core trait that all built-in plugins must implement.
pub trait Plugin: Send + Sync {
    /// Plugin name (e.g., "my-custom-check").
    fn name(&self) -> &'static str;
    /// Plugin version.
    fn version(&self) -> &'static str;
    /// Human-readable description.
    fn description(&self) -> &'static str;
    /// Execute the plugin's analysis logic and return findings.
    fn execute(&self, ctx: &PluginContext) -> PluginResult;
    /// Whether this plugin can run in offline mode.
    fn supports_offline(&self) -> bool {
        true
    }
    /// Whether this plugin requires RPC access.
    fn requires_rpc(&self) -> bool {
        false
    }
}

// ── IPC Protocol for external (subprocess) plugins ──────────────

/// JSON message sent *to* a plugin binary (stdin).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginIpcInput {
    /// Protocol version for forward compatibility.
    pub protocol_version: String,
    /// Plugin name as defined in plugin.toml.
    pub plugin_name: String,
    /// The analysis context (project, files, metadata).
    pub context: PluginContext,
}

/// JSON message expected *from* a plugin binary (stdout).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginIpcOutput {
    /// Whether execution was successful.
    pub success: bool,
    /// Findings discovered by the plugin.
    #[serde(default)]
    pub findings: Vec<PluginIpcFinding>,
    /// Optional error message if not successful.
    #[serde(default)]
    pub error: Option<String>,
    /// Execution statistics.
    #[serde(default)]
    pub stats: PluginExecutionStats,
}

/// A finding as reported by an external plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginIpcFinding {
    /// Human-readable title.
    pub title: String,
    /// Detailed description.
    pub description: String,
    /// Severity: "critical", "high", "medium", "low", "informational"
    pub severity: String,
    /// File path (relative to project root).
    #[serde(default)]
    pub file: Option<String>,
    /// Line number.
    #[serde(default)]
    pub line: Option<usize>,
    /// Column number.
    #[serde(default)]
    pub column: Option<usize>,
    /// Code snippet.
    #[serde(default)]
    pub code_snippet: Option<String>,
    /// Recommended remediation.
    #[serde(default)]
    pub recommendation: Option<String>,
    /// Category of vulnerability.
    #[serde(default)]
    pub category: Option<String>,
    /// Whether this finding blocks deployment.
    #[serde(default)]
    pub blocks_deployment: bool,
    /// Additional references (CVE IDs, links, etc.).
    #[serde(default)]
    pub references: Vec<String>,
}

/// Execution statistics for a plugin run.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PluginExecutionStats {
    /// Number of files analyzed.
    #[serde(default)]
    pub files_analyzed: u32,
    /// Execution time in milliseconds.
    #[serde(default)]
    pub duration_ms: u64,
}

fn parse_plugin_finding(f: &PluginIpcFinding) -> Finding {
    let severity = match f.severity.to_lowercase().as_str() {
        "critical" => Severity::Critical,
        "high" => Severity::High,
        "medium" => Severity::Medium,
        "low" => Severity::Low,
        _ => Severity::Informational,
    };
    Finding::builder()
        .title(&f.title)
        .description(&f.description)
        .severity(severity)
        .file(f.file.clone().unwrap_or_default())
        .location(f.line.unwrap_or(0), f.column.unwrap_or(0))
        .code(f.code_snippet.as_deref().unwrap_or(""))
        .recommendation(f.recommendation.as_deref().unwrap_or(""))
        .category(f.category.as_deref().unwrap_or("Plugin"))
        .blocks_deployment(f.blocks_deployment)
        .build()
}

impl From<PluginIpcFinding> for Finding {
    fn from(f: PluginIpcFinding) -> Self {
        parse_plugin_finding(&f)
    }
}

// ── Metadata ────────────────────────────────────────────────────

/// Metadata about a registered plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginInfo {
    pub name: String,
    pub version: String,
    pub description: String,
    pub enabled: bool,
    pub plugin_type: PluginType,
    pub path: Option<PathBuf>,
}

/// Whether a plugin is built-in or external.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum PluginType {
    Builtin,
    External,
}

// ── Execution result ────────────────────────────────────────────

/// The result of executing a single plugin.
#[derive(Debug, Clone)]
pub struct PluginExecutionResult {
    pub plugin_name: String,
    pub findings: Vec<Finding>,
    pub duration: std::time::Duration,
    pub success: bool,
    pub error: Option<String>,
}

// ── Plugin Registry ─────────────────────────────────────────────

/// The plugin registry manages plugin discovery, registration, and execution.
pub struct PluginRegistry {
    config: ProjectConfig,
    /// External plugins discovered via plugin.toml files.
    external_plugins: Vec<PluginInfo>,
    /// Built-in plugins registered programmatically.
    builtin_plugins: Vec<PluginInfo>,
    /// The actual built-in plugin instances (not serialized).
    builtin_instances: HashMap<String, Box<dyn Plugin>>,
}

impl Clone for PluginRegistry {
    fn clone(&self) -> Self {
        // Note: builtin_instances are intentionally not cloned because
        // Box<dyn Plugin> does not implement Clone. The clone preserves
        // config and plugin metadata but loses the instance map (it gets
        // re-populated by re-registering plugins on the cloned registry).
        Self {
            config: self.config.clone(),
            external_plugins: self.external_plugins.clone(),
            builtin_plugins: self.builtin_plugins.clone(),
            builtin_instances: HashMap::new(),
        }
    }
}

impl std::fmt::Debug for PluginRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PluginRegistry")
            .field("config", &self.config)
            .field("external_plugins", &self.external_plugins)
            .field("builtin_plugins", &self.builtin_plugins)
            .finish()
    }
}

impl PluginRegistry {
    /// Create a new registry, scanning configured directories for plugins.
    pub fn new(config: &ProjectConfig) -> Result<Self, ForgeGuardError> {
        let mut registry = Self {
            config: config.clone(),
            external_plugins: Vec::new(),
            builtin_plugins: Vec::new(),
            builtin_instances: HashMap::new(),
        };
        registry.scan_plugin_dirs()?;
        Ok(registry)
    }

    /// Register a built-in plugin. Returns an error if a plugin with the same name exists.
    pub fn register_builtin(&mut self, plugin: Box<dyn Plugin>) {
        let name = plugin.name().to_string();
        let version = plugin.version().to_string();
        let description = plugin.description().to_string();
        let enabled = !self.config.plugins.disabled.contains(&name);

        // Remove previous registration if any
        self.builtin_plugins.retain(|p| p.name != name);

        self.builtin_plugins.push(PluginInfo {
            name: name.clone(),
            version,
            description,
            enabled,
            plugin_type: PluginType::Builtin,
            path: None,
        });
        self.builtin_instances.insert(name, plugin);
    }

    /// Scan configured directories for external plugins.
    fn scan_plugin_dirs(&mut self) -> Result<(), ForgeGuardError> {
        let dirs = &self.config.plugin_dirs;
        // If no dirs configured, use the default from PluginConfig
        let default_dir = PathBuf::from(".forge-guard/plugins");
        let search_dirs: Vec<&PathBuf> = if dirs.is_empty() {
            // Use the default .forge-guard/plugins directory
            if default_dir.exists() {
                vec![&default_dir]
            } else {
                Vec::new()
            }
        } else {
            dirs.iter().collect()
        };

        for dir in search_dirs {
            if dir.exists() && dir.is_dir() {
                if let Ok(entries) = std::fs::read_dir(dir) {
                    for entry in entries.flatten() {
                        let path = entry.path();
                        if path.is_dir() {
                            let meta_file = path.join("plugin.toml");
                            if meta_file.exists() {
                                if let Ok(info) = self.load_plugin_meta(&meta_file) {
                                    // Don't add duplicates
                                    if !self.external_plugins.iter().any(|p| p.name == info.name) {
                                        self.external_plugins.push(info);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Load plugin metadata from a TOML file.
    fn load_plugin_meta(&self, path: &Path) -> Result<PluginInfo, ForgeGuardError> {
        let content = std::fs::read_to_string(path)?;
        #[derive(Deserialize)]
        struct PluginMeta {
            name: String,
            version: String,
            description: String,
        }
        let meta: PluginMeta = toml::from_str(&content)?;

        let enabled = !self.config.plugins.disabled.contains(&meta.name);
        Ok(PluginInfo {
            name: meta.name,
            version: meta.version,
            description: meta.description,
            enabled,
            plugin_type: PluginType::External,
            path: path.parent().map(|p| p.to_path_buf()),
        })
    }

    /// List all registered plugins (both built-in and external).
    pub fn list_plugins(&self) -> Vec<PluginInfo> {
        let mut all = self.builtin_plugins.clone();
        all.extend(self.external_plugins.clone());
        // Sort: built-in first, then external
        all.sort_by_key(|p| match p.plugin_type {
            PluginType::Builtin => 0,
            PluginType::External => 1,
        });
        all
    }

    /// Get info for a specific plugin by name.
    pub fn get_plugin(&self, name: &str) -> Option<PluginInfo> {
        self.builtin_plugins
            .iter()
            .chain(self.external_plugins.iter())
            .find(|p| p.name == name)
            .cloned()
    }

    /// Get the number of registered plugins.
    pub fn plugin_count(&self) -> usize {
        self.builtin_plugins.len() + self.external_plugins.len()
    }

    /// Get the number of enabled plugins.
    pub fn enabled_count(&self) -> usize {
        self.list_plugins().iter().filter(|p| p.enabled).count()
    }

    // ── Plugin Execution ───────────────────────────────────────

    /// Execute all enabled plugins and return their findings.
    ///
    /// Built-in plugins are executed in-process. External plugins are executed
    /// as subprocesses via the JSON IPC protocol.
    pub fn execute_all(&self, ctx: &PluginContext) -> Vec<PluginExecutionResult> {
        let mut results = Vec::new();

        // Execute built-in plugins
        for info in &self.builtin_plugins {
            if !info.enabled {
                continue;
            }
            if let Some(instance) = self.builtin_instances.get(&info.name) {
                let result = self.execute_builtin(instance.as_ref(), info, ctx);
                results.push(result);
            }
        }

        // Execute external plugins
        for info in &self.external_plugins {
            if !info.enabled {
                continue;
            }
            let result = self.execute_external(info, ctx);
            results.push(result);
        }

        results
    }

    /// Execute a single built-in plugin.
    fn execute_builtin(
        &self,
        plugin: &dyn Plugin,
        info: &PluginInfo,
        ctx: &PluginContext,
    ) -> PluginExecutionResult {
        let start = Instant::now();
        match plugin.execute(ctx) {
            Ok(findings) => PluginExecutionResult {
                plugin_name: info.name.clone(),
                findings,
                duration: start.elapsed(),
                success: true,
                error: None,
            },
            Err(e) => PluginExecutionResult {
                plugin_name: info.name.clone(),
                findings: Vec::new(),
                duration: start.elapsed(),
                success: false,
                error: Some(e.to_string()),
            },
        }
    }

    /// Execute an external plugin as a subprocess.
    fn execute_external(&self, info: &PluginInfo, ctx: &PluginContext) -> PluginExecutionResult {
        let start = Instant::now();
        let plugin_dir = match &info.path {
            Some(p) => p.clone(),
            None => {
                return PluginExecutionResult {
                    plugin_name: info.name.clone(),
                    findings: Vec::new(),
                    duration: start.elapsed(),
                    success: false,
                    error: Some("Plugin path unknown".to_string()),
                };
            }
        };

        // Determine the binary/script to execute
        let binary = Self::find_plugin_binary(&plugin_dir);
        if binary.is_none() {
            return PluginExecutionResult {
                plugin_name: info.name.clone(),
                findings: Vec::new(),
                duration: start.elapsed(),
                success: false,
                error: Some(format!(
                    "No executable found in plugin directory: {}",
                    plugin_dir.display()
                )),
            };
        }
        let binary = binary.unwrap();

        // Build the IPC input
        let input = PluginIpcInput {
            protocol_version: "1.0".to_string(),
            plugin_name: info.name.clone(),
            context: ctx.clone(),
        };

        // Serialize to JSON
        let input_json = match serde_json::to_string(&input) {
            Ok(j) => j,
            Err(e) => {
                return PluginExecutionResult {
                    plugin_name: info.name.clone(),
                    findings: Vec::new(),
                    duration: start.elapsed(),
                    success: false,
                    error: Some(format!("Failed to serialize IPC input: {}", e)),
                };
            }
        };

        // Spawn the subprocess
        let output = match std::process::Command::new(&binary)
            .args(["--forge-guard-ipc"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
        {
            Ok(mut child) => {
                // Write input to stdin
                use std::io::Write;
                if let Some(mut stdin) = child.stdin.take() {
                    let _ = stdin.write_all(input_json.as_bytes());
                    // Close stdin to signal end of input
                    drop(stdin);
                }

                // Wait for the process to finish with a timeout
                match child.wait_with_output() {
                    Ok(output) => output,
                    Err(e) => {
                        return PluginExecutionResult {
                            plugin_name: info.name.clone(),
                            findings: Vec::new(),
                            duration: start.elapsed(),
                            success: false,
                            error: Some(format!("Failed to wait for plugin process: {}", e)),
                        };
                    }
                }
            }
            Err(e) => {
                return PluginExecutionResult {
                    plugin_name: info.name.clone(),
                    findings: Vec::new(),
                    duration: start.elapsed(),
                    success: false,
                    error: Some(format!("Failed to spawn plugin process: {}", e)),
                };
            }
        };

        // Log stderr output (plugin diagnostics)
        if !output.stderr.is_empty() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            for line in stderr.lines() {
                if !line.is_empty() {
                    eprintln!("  [plugin:{}] {}", info.name, line);
                }
            }
        }

        // Parse stdout as JSON findings
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return PluginExecutionResult {
                plugin_name: info.name.clone(),
                findings: Vec::new(),
                duration: start.elapsed(),
                success: false,
                error: Some(format!(
                    "Plugin exited with code {}: {}",
                    output.status.code().unwrap_or(-1),
                    stderr.lines().next().unwrap_or("unknown error")
                )),
            };
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        match serde_json::from_str::<PluginIpcOutput>(&stdout) {
            Ok(ipc_output) => {
                let findings: Vec<Finding> =
                    ipc_output.findings.into_iter().map(|f| f.into()).collect();

                if ipc_output.success {
                    PluginExecutionResult {
                        plugin_name: info.name.clone(),
                        findings,
                        duration: start.elapsed(),
                        success: true,
                        error: None,
                    }
                } else {
                    PluginExecutionResult {
                        plugin_name: info.name.clone(),
                        findings,
                        duration: start.elapsed(),
                        success: false,
                        error: ipc_output.error,
                    }
                }
            }
            Err(e) => PluginExecutionResult {
                plugin_name: info.name.clone(),
                findings: Vec::new(),
                duration: start.elapsed(),
                success: false,
                error: Some(format!(
                    "Failed to parse plugin IPC output: {}. Raw stdout: {}",
                    e,
                    stdout.chars().take(200).collect::<String>()
                )),
            },
        }
    }

    /// Find the executable binary in a plugin directory.
    /// Looks for: the directory name (without prefix), main binary, or a shell script.
    fn find_plugin_binary(dir: &Path) -> Option<PathBuf> {
        // Try the directory name as the binary (e.g., plugin "my-check" → "my-check")
        if let Some(dir_name) = dir.file_name() {
            let candidates = [
                dir.join(dir_name),
                dir.join("target").join("release").join(dir_name),
                dir.join("target").join("debug").join(dir_name),
            ];
            for candidate in &candidates {
                if candidate.exists() && is_executable(candidate) {
                    return Some(candidate.clone());
                }
            }
        }

        // Try common script names
        let script_candidates = [
            dir.join("run.sh"),
            dir.join("main.py"),
            dir.join("index.js"),
            dir.join("plugin"),
        ];
        for candidate in &script_candidates {
            if candidate.exists() {
                return Some(candidate.clone());
            }
        }

        None
    }

    /// Enable a plugin by name.
    pub fn enable_plugin(&mut self, name: &str) -> bool {
        let mut found = false;
        for plugin in &mut self.builtin_plugins {
            if plugin.name == name {
                plugin.enabled = true;
                found = true;
            }
        }
        for plugin in &mut self.external_plugins {
            if plugin.name == name {
                plugin.enabled = true;
                found = true;
            }
        }
        found
    }

    /// Disable a plugin by name.
    pub fn disable_plugin(&mut self, name: &str) -> bool {
        let mut found = false;
        for plugin in &mut self.builtin_plugins {
            if plugin.name == name {
                plugin.enabled = false;
                found = true;
            }
        }
        for plugin in &mut self.external_plugins {
            if plugin.name == name {
                plugin.enabled = false;
                found = true;
            }
        }
        found
    }
}

#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    path.is_file()
        && path
            .metadata()
            .map(|m| m.permissions().mode() & 0o111 != 0)
            .unwrap_or(false)
}

#[cfg(not(unix))]
fn is_executable(path: &Path) -> bool {
    path.is_file()
}

// ── Built-in Example Plugin ────────────────────────────────────

/// A built-in example plugin for demonstration and self-testing.
pub struct ExamplePlugin;

impl Plugin for ExamplePlugin {
    fn name(&self) -> &'static str {
        "forge-guard-example"
    }

    fn version(&self) -> &'static str {
        "0.1.0"
    }

    fn description(&self) -> &'static str {
        "Example plugin demonstrating the plugin API"
    }

    fn execute(&self, ctx: &PluginContext) -> PluginResult {
        eprintln!(
            "  [plugin:{}] Analyzing {} source files",
            self.name(),
            ctx.source_files.len()
        );
        Ok(Vec::new())
    }
}

/// A built-in "no-op" plugin that warns about missing RPC.
pub struct OfflineGuardPlugin;

impl Plugin for OfflineGuardPlugin {
    fn name(&self) -> &'static str {
        "forge-guard-offline-guard"
    }

    fn version(&self) -> &'static str {
        "0.1.0"
    }

    fn description(&self) -> &'static str {
        "Warns when plugins requiring RPC are enabled but --offline is set"
    }

    fn execute(&self, ctx: &PluginContext) -> PluginResult {
        let offline = ctx
            .metadata
            .get("offline")
            .map(|s| s == "true")
            .unwrap_or(false);
        if offline {
            // In offline mode, this plugin just verifies no findings exist
            return Ok(Vec::new());
        }
        Ok(Vec::new())
    }
}

// ── Convenience initializer for common built-in plugins ────────

/// Register the default set of built-in plugins into a registry.
pub fn register_default_plugins(registry: &mut PluginRegistry) {
    registry.register_builtin(Box::new(ExamplePlugin));
    registry.register_builtin(Box::new(OfflineGuardPlugin));
}