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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
use crate::{
common::{
config::{NinjaConfig, ShurikenReference},
registry::{
ArmoryItem, download_shuriken, get_shuriken_from_registries,
get_shurikens_from_registries,
},
types::{ArmoryMetadata, FieldValue, ShurikenState},
},
scripting::{NinjaEngine, dsl::DslContext},
shuriken::{Shuriken, ShurikenConfig},
utils::{create_tar_gz_bytes, load_shurikens, normalize_shuriken_name},
};
use futures_util::future::join_all;
use anyhow::{Context, Error, Result};
use dirs_next as dirs;
use either::Either::{self, Left, Right};
use log::{debug, info, warn};
use serde_cbor::to_vec;
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
env, io,
path::{Path, PathBuf},
str,
sync::Arc,
};
use tokio::{
fs::{self, File},
io::{AsyncReadExt, AsyncWriteExt},
sync::Mutex,
sync::RwLock,
};
const MAGIC: &[u8; 6] = b"HSRZEG";
/// A thin wrapper around a spawned process. We keep it simple: the
/// ManagedProcess owns a `tokio::process::Child` and provides async helpers.
/// The main orchestrator for managing Shurikens and their lifecycle.
///
/// `ShurikenManager` handles all operations related to Shuriken services,
/// including startup, configuration, installation, and lifecycle management.
/// It maintains the scripting engine, configuration, and in-memory state.
///
/// # Fields
/// - `root_path`: Base directory where Ninja stores data (~/.ninja)
/// - `engine`: Lua scripting engine for executing Shuriken scripts
/// - `shurikens`: Cached map of loaded Shurikens by name
/// - `config`: Global Ninja configuration including registries
#[derive(Clone, Debug)]
pub struct ShurikenManager {
pub root_path: PathBuf,
pub engine: Arc<Mutex<NinjaEngine>>,
pub shurikens: Arc<RwLock<HashMap<String, Shuriken>>>,
pub config: Arc<RwLock<crate::common::config::NinjaConfig>>,
}
impl ShurikenManager {
/// Creates a new `ShurikenManager` instance.
///
/// Initializes the Ninja directory structure (~/.ninja), loads existing Shurikens,
/// creates a Lua scripting engine, and loads or generates the global configuration.
///
/// # Returns
/// - `Ok(ShurikenManager)` on success
/// - `Err` if home directory cannot be found or initialization fails
///
/// # Panics
/// None - all errors are returned as Results
pub async fn new() -> Result<Self> {
let exe_dir = dirs::home_dir()
.ok_or_else(|| Error::msg("Could not find home directory"))?
.join(".ninja");
fs::create_dir_all(&exe_dir).await?;
let shurikens_dir = exe_dir.join("shurikens");
let projects_dir = exe_dir.join("projects");
// Create shurikens directory if it doesn't exist
if !shurikens_dir.exists() {
fs::create_dir(&shurikens_dir).await?;
}
if !projects_dir.exists() {
fs::create_dir(&projects_dir).await?;
}
let shurikens = load_shurikens(&exe_dir).await?;
let engine = NinjaEngine::new()
.await
.map_err(|e| Error::msg(e.to_string()))?;
let config = if exe_dir.join("config.toml").exists() {
let content = fs::read_to_string(exe_dir.join("config.toml")).await?;
let config: NinjaConfig = toml::from_str(content.as_str())
.map_err(|e| Error::msg(format!("Failed to parse config.toml: {}", e)))?;
Arc::new(RwLock::new(config))
} else {
let config = NinjaConfig::new();
config.generate_default_config(&exe_dir).await?;
Arc::new(RwLock::new(config))
};
Ok(Self {
root_path: exe_dir,
engine: Arc::new(Mutex::new(engine)),
shurikens: Arc::new(RwLock::new(shurikens)),
config,
})
}
/// Updates the state of a Shuriken (internal helper).
///
/// # Arguments
/// - `shuriken`: The Shuriken instance to update
/// - `new_state`: The new state to set
async fn update_state(&self, shuriken: Shuriken, new_state: ShurikenState) {
let mut state_lock = shuriken.state.lock().await;
*state_lock = new_state;
}
/// Starts a Shuriken by name.
///
/// Executes the Shuriken's startup script and begins running the service.
/// Updates the Shuriken's state to `Running` on success.
///
/// # Arguments
/// - `name`: The name of the Shuriken to start
///
/// # Returns
/// - `Ok(())` if startup completed successfully
/// - `Err` if Shuriken not found, script execution fails, or startup errors occur
pub async fn start(&self, name: &str) -> Result<()> {
let normalized_name = normalize_shuriken_name(name);
info!("Starting shuriken: {}", name);
let shurikens = self.shurikens.read().await;
let shuriken = shurikens
.get(&normalized_name)
.ok_or_else(|| {
warn!("Shuriken not found: {}", name);
anyhow::Error::msg(format!("No such shuriken: {}", name))
})?
.clone();
drop(shurikens);
let shuriken_dir = self.root_path.join("shurikens").join(&normalized_name);
if !shuriken_dir.exists() {
warn!("Shuriken directory not found: {}", shuriken_dir.display());
return Err(anyhow::Error::msg(format!(
"Shuriken directory not found: {}",
shuriken_dir.display()
)));
}
debug!("Starting process for shuriken: {}", normalized_name);
if let Err(e) = shuriken
.start(
&*self.engine.lock().await,
&shuriken_dir,
Some(self.clone()),
)
.await
{
warn!("Failed to start shuriken '{}': {}", name, e);
return Err(anyhow::Error::msg(format!(
"Failed to start shuriken '{}': {}",
name, e
)));
}
self.update_state(shuriken, ShurikenState::Running).await;
info!("Successfully started shuriken: {}", name);
Ok(())
}
/// Reloads all Shurikens from disk.
///
/// Rescans the ~/.ninja/shurikens directory and updates the in-memory cache.
/// Useful after manual file changes or to get latest state from disk.
///
/// # Returns
/// - `Ok(())` on success
/// - `Err` if file system operations fail
pub async fn refresh(&self) -> Result<()> {
info!("Refreshing shurikens from disk");
let new_shurikens = load_shurikens(&self.root_path).await?;
let count = new_shurikens.len();
*self.shurikens.write().await = new_shurikens;
info!("Shuriken manager refreshed. Found {} shurikens.", count);
Ok(())
}
/// Configures a Shuriken using its configuration script.
///
/// Executes the Shuriken's `post_config` function to apply configuration settings.
/// Configuration values are templated and written to the Shuriken's config file.
///
/// # Arguments
/// - `name`: The name of the Shuriken to configure
///
/// # Returns
/// - `Ok(())` if configuration completed successfully
/// - `Err` if Shuriken not found or configuration fails
pub async fn configure(&self, name: &str) -> Result<()> {
info!("Configuring shuriken: {}", name);
let normalized_name = normalize_shuriken_name(name);
let partial_shuriken = &self.shurikens.write().await;
let shuriken = partial_shuriken.get(&normalized_name);
if let Some(shuriken) = shuriken {
let path = &self.root_path;
shuriken
.configure(path, &*self.engine.lock().await, Some(self.clone()))
.await?
} else {
warn!("Shuriken not found for configuration: {}", name);
}
Ok(())
}
/// Removes the lock file for a Shuriken.
///
/// Forces the Shuriken to be considered "not running" by removing its lock file.
/// Useful for recovering from crashed processes.
///
/// # Arguments
/// - `name`: The name of the Shuriken
///
/// # Returns
/// - `Ok(())` if lock file successfully removed or didn't exist
/// - `Err` if operation fails
pub async fn lockpick(&self, name: &str) -> Result<()> {
info!("Lockpicking shuriken: {}", name);
let normalized_name = normalize_shuriken_name(name);
let partial_shuriken = &self.shurikens.write().await;
let shuriken = partial_shuriken.get(&normalized_name);
if let Some(shuriken) = shuriken {
let path = &self.root_path;
shuriken.lockpick(path).await?
} else {
warn!("Shuriken not found for lockpick: {}", name);
}
Ok(())
}
/// Saves configuration options for a Shuriken.
///
/// Persists configuration to disk as TOML and updates the in-memory cache.
/// Creates necessary directories if they don't exist.
///
/// # Arguments
/// - `name`: The name of the Shuriken
/// - `data`: Configuration key-value pairs to save
///
/// # Returns
/// - `Ok(())` if configuration saved successfully
/// - `Err` if file operations fail
pub async fn save_config(&self, name: &str, data: HashMap<String, FieldValue>) -> Result<()> {
info!("Saving config for shuriken: {}", name);
debug!("Config data: {:#?}", data);
let normalized_name = normalize_shuriken_name(name);
// Update in-memory config
{
let mut shurikens = self.shurikens.write().await;
if let Some(shuriken) = shurikens.get_mut(&normalized_name) {
if let Some(config) = &mut shuriken.config {
config.options = Some(data.clone());
} else {
shuriken.config = Some(ShurikenConfig {
config_path: PathBuf::from("options.toml"),
options: Some(data.clone()),
});
}
}
}
// Write to disk
let serialized_data = toml::ser::to_string_pretty(&data)?;
let options_path = self
.root_path
.join("shurikens")
.join(&normalized_name)
.join(".ninja")
.join("options.toml");
// Ensure the parent directory exists
if let Some(parent) = options_path.parent() {
fs::create_dir_all(parent).await?;
}
// Remove old file if it exists
if options_path.exists() {
fs::remove_file(&options_path).await?;
}
fs::write(&options_path, serialized_data).await?;
Ok(())
}
/// Stops a running Shuriken.
///
/// Executes the Shuriken's stop script and halts the service.
/// Updates the Shuriken's state to `Idle` on success.
///
/// # Arguments
/// - `name`: The name of the Shuriken to stop
///
/// # Returns
/// - `Ok(())` if stop completed successfully
/// - `Err` if Shuriken not found or stop script fails
pub async fn stop(&self, name: &str) -> Result<()> {
let normalized_name = normalize_shuriken_name(name);
let shurikens = self.shurikens.read().await;
let mut shuriken = shurikens
.get(&normalized_name)
.ok_or_else(|| anyhow::Error::msg(format!("No such shuriken: {}", name)))?
.clone();
drop(shurikens);
let shuriken_dir = self.root_path.join("shurikens").join(&normalized_name);
if !shuriken_dir.exists() {
return Err(anyhow::Error::msg(format!(
"Shuriken directory not found: {}",
shuriken_dir.display()
)));
}
if let Err(e) = shuriken
.stop(
&*self.engine.lock().await,
&shuriken_dir,
Some(self.clone()),
)
.await
{
return Err(anyhow::Error::msg(format!(
"Failed to stop shuriken '{}': {}",
name, e
)));
}
self.update_state(shuriken, ShurikenState::Idle).await;
Ok(())
}
/// Retrieves a Shuriken by name.
///
/// # Arguments
/// - `name`: The name of the Shuriken to retrieve
///
/// # Returns
/// - `Ok(Shuriken)` if found
/// - `Err` if Shuriken not found
pub async fn get(&self, name: String) -> Result<Shuriken> {
debug!("Getting shuriken: {}", name);
let partial_shuriken = &self.shurikens.read().await;
let maybe_shuriken = partial_shuriken.get(&name);
info!(
"Getting shuriken '{}' from shurikens: {}",
name,
partial_shuriken
.keys()
.cloned()
.collect::<Vec<String>>()
.join(", ")
);
if let Some(shuriken) = maybe_shuriken {
debug!("Shuriken metadata: {:?}", shuriken.metadata);
debug!("Shuriken config: {:?}", shuriken.config);
Ok(shuriken.clone())
} else {
warn!("Shuriken '{}' not found", name);
Err(anyhow::Error::msg(format!(
"No shuriken of name {} found",
name
)))
}
}
/// Lists all available Shurikens.
///
/// # Arguments
/// - `state`: If `true`, returns names with their current state; if `false`, returns only names
///
/// # Returns
/// - `Ok(Left(vec))` with state information if `state` is true
/// - `Ok(Right(vec))` with just names if `state` is false
/// - `Err` if operation fails
pub async fn list(
&self,
state: bool,
) -> Result<Either<Vec<(String, ShurikenState)>, Vec<String>>> {
if state {
let shurikens = self.shurikens.read().await;
let futures = shurikens
.iter()
.map(async |(name, shuriken)| {
let state = shuriken.state.lock().await;
(name.clone(), state.clone())
})
.collect::<Vec<_>>();
let values = join_all(futures).await;
debug!("Listing shurikens with state: {:?}", values);
Ok(Left(values))
} else {
let shurikens = self.shurikens.read().await;
let keys: Vec<String> = shurikens.keys().cloned().collect();
debug!("Listing shuriken names: {:?}", keys);
Ok(Right(keys))
}
}
/// Creates a new DSL context for script execution.
///
/// # Returns
/// A `DslContext` that can be used to interpret Ninja DSL commands
pub fn dsl_ctx(&self) -> DslContext {
DslContext {
selected: Arc::new(RwLock::new(None)),
manager: self.clone(),
}
}
/// Packages a Shuriken into a distributable `.shuriken` file.
///
/// Creates a signed archive containing metadata, the Shuriken directory, and SHA256 checksum.
/// Format: MAGIC + metadata_length + metadata + archive_length + archive + signature
///
/// # Arguments
/// - `meta`: Metadata for the packaged Shuriken
/// - `path`: Path to the Shuriken directory to package
/// - `output`: Optional output directory (defaults to ~/.ninja/blacksmith)
///
/// # Returns
/// - `Ok(())` if packaging succeeded
/// - `Err` if metadata is too large, archive creation fails, or I/O fails
pub async fn forge(
&self,
meta: ArmoryMetadata,
path: PathBuf,
output: Option<PathBuf>,
) -> Result<()> {
let output = output.unwrap_or_else(|| self.root_path.join("blacksmith"));
if !output.exists() {
fs::create_dir_all(&output).await?;
}
let path = &self.root_path.join("shurikens").join(path);
let shuriken_path = output.join(format!("{}-{}.shuriken", meta.id, meta.platform));
let mut file = File::create(shuriken_path).await?;
// ---- 1) Serialize metadata ----
let serialized_metadata = to_vec(&meta)?;
if serialized_metadata.len() > u16::MAX as usize {
return Err(anyhow::Error::msg(
"Metadata too large to fit in u16 length field",
));
}
// ---- 2) Build archive bytes (tar.gz) in a blocking thread ----
let archive = {
let path_clone = path.clone();
tokio::task::spawn_blocking(move || create_tar_gz_bytes(&path_clone)).await??
};
let archive_len = archive.len();
if archive_len > u32::MAX as usize {
return Err(anyhow::Error::msg(
"Archive too large to fit in u32 length field",
));
}
// ---- 3) Compute signature = SHA256(archive) ----
let mut hasher = Sha256::new();
hasher.update(&archive);
let signature = hasher.finalize(); // 32 bytes
// ---- 4) Write in correct order ----
// [MAGIC] // 4 bytes
// [metadata_length] // u16 LE
// [metadata] // CBOR
// [archive_length] // u32 LE
// [archive] // tar.gz
// [signature] // 32 bytes SHA-256(archive)
// MAGIC
file.write_all(MAGIC).await?;
// metadata_length (u16 LE)
let meta_len_le = (serialized_metadata.len() as u16).to_le_bytes();
file.write_all(&meta_len_le).await?;
// metadata
file.write_all(&serialized_metadata).await?;
// archive_length (u32 LE)
let archive_len_le = (archive_len as u32).to_le_bytes();
file.write_all(&archive_len_le).await?;
// archive
file.write_all(&archive).await?;
// signature
file.write_all(&signature).await?;
Ok(())
}
/// Removes a Shuriken from the system.
///
/// Deletes the Shuriken directory and removes it from the cache.
///
/// # Arguments
/// - `name`: The name of the Shuriken to remove
///
/// # Returns
/// - `Ok(())` if removal succeeded
/// - `Err` if Shuriken not found or deletion fails
pub async fn remove(&self, name: &str) -> Result<()> {
info!("Removing shuriken: {}", name);
let normalized_name = normalize_shuriken_name(name);
warn!("Deleting {}.", name);
fs::remove_dir_all(format!("shurikens/{}", normalized_name)).await?;
let _ = &self.shurikens.write().await.remove(&normalized_name);
info!("Successfully deleted shuriken {}, refreshing.", name);
#[cfg(debug_assertions)]
dbg!("{:#?}", &self.shurikens);
Ok(())
}
/// Resets and reinitializes the Lua scripting engine.
///
/// Useful when you need to clear engine state between operations.
/// Creates a new engine instance with all modules.
///
/// # Returns
/// - `Ok(())` on success
/// - `Err` if engine initialization fails
pub async fn reset_engine(&self) -> Result<()> {
let new_engine = NinjaEngine::new()
.await
.map_err(|e| Error::msg(e.to_string()))?;
*self.engine.lock().await = new_engine; // don't ask i need to reset the engine everytime i run scripts in gui.
Ok(())
}
// -------------------- Installation functions --------------------
/// Installs a Shuriken from various sources.
///
/// Automatically detects the source type and installs accordingly:
/// - Registry reference (e.g., "registry:shuriken")
/// - Direct URL
/// - Local file path
///
/// # Arguments
/// - `name`: The Shuriken source (reference, URL, or file path)
///
/// # Returns
/// - `Ok(())` if installation completed
/// - `Err` if source is invalid or installation fails
pub async fn install(&self, name: &str) -> Result<()> {
if ShurikenReference::parse(&name).is_ok() {
let reference = ShurikenReference::parse(&name)?;
self.install_from_registry(&reference).await
} else if url::Url::parse(&name).is_ok() {
self.install_url(&name).await
} else {
self.install_file(&PathBuf::from(name)).await
}
}
/// Installs a Shuriken from a direct URL.
///
/// Downloads the .shuriken file and installs it.
///
/// # Arguments
/// - `url`: The download URL for the .shuriken file
///
/// # Returns
/// - `Ok(())` if installation succeeded
/// - `Err` if download or installation fails
pub async fn install_url(&self, url: &str) -> Result<()> {
let temp_path = self.root_path.join("temp_shuriken.shuriken");
download_shuriken(&temp_path, url).await?;
let result = self.install_file(&temp_path).await;
let _ = fs::remove_file(temp_path).await; // clean up temp file
result
}
/// Install a shuriken from a registry reference (e.g., "my-registry:my-shuriken")
pub async fn install_from_registry(
&self,
reference: &crate::common::config::ShurikenReference,
) -> Result<()> {
let registries = &self.config.read().await.registries;
let download_url =
crate::common::config::resolve_download_url(registries, reference).await?;
info!(
"Installing shuriken {} from {}",
reference.shuriken, download_url
);
self.install_url(&download_url).await
}
/// Installs a Shuriken from a local file.
///
/// Validates the .shuriken file format (magic bytes, metadata, checksum),
/// extracts the archive, verifies platform compatibility, and runs postinstall hooks.
///
/// # Arguments
/// - `path`: Path to the .shuriken file
///
/// # Returns
/// - `Ok(())` if installation succeeded
/// - `Err` if file is invalid, corrupted, incompatible, or extraction fails
///
/// # File Format
/// - MAGIC (6 bytes): "HSRZEG"
/// - metadata_length (u16 LE)
/// - metadata (CBOR encoded)
/// - archive_length (u32 LE)
/// - archive (tar.gz)
/// - signature (32 bytes SHA256)
pub async fn install_file(&self, path: &Path) -> Result<(), anyhow::Error> {
use sha2::{Digest, Sha256};
use std::io::Cursor;
info!("Starting installation");
if !path.exists() {
return Err(anyhow::Error::msg("Path does not exist"));
}
let mut file = tokio::fs::File::open(&path)
.await
.map_err(|e| io::Error::other(format!("Failed to open shuriken file: {e}")))?;
// 1) MAGIC (6 bytes)
let mut magic_buf = [0u8; 6];
file.read_exact(&mut magic_buf).await?;
if &magic_buf != MAGIC {
return Err(anyhow::Error::msg("Invalid shuriken file (bad MAGIC)."));
}
// this comment is just a small change
// 2) metadata_length (u16 LE)
let mut meta_len_buf = [0u8; 2];
file.read_exact(&mut meta_len_buf).await?;
let metadata_length = u16::from_le_bytes(meta_len_buf) as usize;
const MAX_METADATA: usize = 64 * 1024; // 64 KB
if metadata_length > MAX_METADATA {
return Err(anyhow::Error::msg("Metadata too large"));
}
// 3) metadata (CBOR)
let mut metadata_buf = vec![0u8; metadata_length];
file.read_exact(&mut metadata_buf).await?;
let metadata: ArmoryMetadata =
serde_cbor::from_slice(&metadata_buf).context("Failed to parse metadata CBOR")?;
info!("Metadata parsing complete");
debug!("MAGIC: {:?}", magic_buf);
debug!("meta_len: {}", metadata_length);
debug!("metadata: {:#?}", metadata);
// 4) archive_length (u32 LE)
let mut archive_len_buf = [0u8; 4];
file.read_exact(&mut archive_len_buf).await?;
let archive_length = u32::from_le_bytes(archive_len_buf) as usize;
const MAX_ARCHIVE: usize = 1024 * 1024 * 1024; // 1 GB
if archive_length > MAX_ARCHIVE {
return Err(anyhow::Error::msg("Archive too large"));
}
// 5) archive (exactly archive_length bytes)
let mut archive_buf = vec![0u8; archive_length];
file.read_exact(&mut archive_buf).await?;
// 6) signature (rest of the file)
let mut signature = [0u8; 32];
file.read_exact(&mut signature).await?;
// Verify checksum = SHA256(MAGIC + metadata_len + metadata + archive_len + archive)
let mut hasher = Sha256::new();
hasher.update(&archive_buf);
let digest = hasher.finalize();
if digest.as_slice() != signature {
return Err(anyhow::Error::msg(
"Shuriken file signature mismatch (archive corrupted or tampered).",
));
}
// Platform check
if !metadata.platform.contains(env::consts::OS)
&& !metadata.platform.contains(env::consts::ARCH)
{
return Err(anyhow::Error::msg(
"Unsupported platform. Current platform is not the same as the shuriken's destined platform.",
));
}
// Unpack archive in blocking task
let archive_cursor = Cursor::new(archive_buf);
let archive_name = normalize_shuriken_name(&metadata.name);
let unpack_path = self.root_path.clone().join("shurikens").join(&archive_name);
let root_path = self.root_path.clone().join("shurikens").join(&archive_name);
tokio::task::spawn_blocking(move || -> Result<(), anyhow::Error> {
let gz_decoder = flate2::read::GzDecoder::new(archive_cursor);
let mut archive = tar::Archive::new(gz_decoder);
archive.unpack(&unpack_path)?;
Ok(())
})
.await??;
// Run postinstall script if present
if let Some(pi_script) = &metadata.postinstall {
info!("Running postinstall script");
let path = root_path.join(pi_script);
let engine = &self.engine.lock().await;
engine
.execute_file(&path, Some(&root_path), Some(self.clone()))
.await?;
}
// save config so the paths are correct when we launch.
self.refresh().await?;
self.configure(&metadata.name).await?;
Ok(())
}
/// Fetches all available Shurikens from all configured registries.
///
/// # Returns
/// A vector of `ArmoryItem` entries from all registries
pub async fn registry_get_all_shurikens(&self) -> Vec<ArmoryItem> {
let registries: Vec<String> = self
.config
.read()
.await
.registries
.values()
.cloned()
.collect::<Vec<_>>();
let shurikens = get_shurikens_from_registries(®istries).await;
shurikens
}
/// Fetches a specific Shuriken from any configured registry.
///
/// # Arguments
/// - `name`: The name of the Shuriken to fetch
///
/// # Returns
/// - `Some(ArmoryItem)` if found in a registry
/// - `None` if not found
pub async fn registry_get_shuriken(&self, name: String) -> Option<ArmoryItem> {
let partial_registries = &self.config.read().await.registries;
let registries: Vec<String> = partial_registries.values().cloned().collect::<Vec<_>>();
get_shuriken_from_registries(name, ®istries).await
}
// -------------------- Project management API --------------------
/// Lists all projects in the projects directory.
///
/// # Returns
/// - `Ok(Vec<String>)` with project names
/// - `Err` if directory access fails
pub async fn get_projects(&self) -> Result<Vec<String>> {
let path = &self.root_path.join("projects");
let mut entries: Vec<String> = Vec::new();
let mut fs_entries = fs::read_dir(path).await?;
while let Some(entry) = fs_entries.next_entry().await? {
let path = entry.path();
if path.is_dir()
&& let Some(name) = path.file_name().and_then(|n| n.to_str())
{
if name == "pma" || name == "fancy-index" {
continue;
}
entries.push(name.to_string());
}
}
Ok(entries)
}
}