-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathtemplates.rs
More file actions
3742 lines (3335 loc) · 127 KB
/
Copy pathtemplates.rs
File metadata and controls
3742 lines (3335 loc) · 127 KB
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::utils::http_client;
use crate::utils::template_schema;
use anyhow::{Context, Result};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
/// The running StarForge CLI version — used for template compatibility checks.
pub const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TemplateRegistry {
#[serde(default)]
pub templates: Vec<TemplateEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum TemplateSource {
Git {
url: String,
#[serde(default)]
branch: Option<String>,
},
Local {
path: String,
},
Builtin {
id: String,
},
}
impl Default for TemplateSource {
fn default() -> Self {
TemplateSource::Builtin { id: String::new() }
}
}
impl std::fmt::Display for TemplateSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TemplateSource::Git { url, branch } => {
if let Some(branch) = branch {
write!(f, "git:{}@{}", url, branch)
} else {
write!(f, "git:{}", url)
}
}
TemplateSource::Local { path } => write!(f, "local:{}", path),
TemplateSource::Builtin { id } => write!(f, "builtin:{}", id),
}
}
}
/// Maintenance state of a marketplace template.
///
/// Surfaced to users as a lightweight trust signal so they can tell at a
/// glance whether a template is being kept up to date or has been abandoned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum MaintenanceStatus {
/// Updated recently and accepting changes.
Active,
/// Stable and still supported, but not under active development.
Maintained,
/// No longer maintained; use with caution.
Deprecated,
/// Maintenance state has not been declared.
#[default]
Unknown,
}
impl MaintenanceStatus {
/// Short human-readable label used in trust indicators.
pub fn label(&self) -> &'static str {
match self {
MaintenanceStatus::Active => "Actively maintained",
MaintenanceStatus::Maintained => "Maintained",
MaintenanceStatus::Deprecated => "Deprecated",
MaintenanceStatus::Unknown => "Unknown maintenance",
}
}
}
fn deserialize_findings_opt<'de, D>(
deserializer: D,
) -> std::result::Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
struct FindingsVisitor;
impl<'de> serde::de::Visitor<'de> for FindingsVisitor {
type Value = Option<String>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a string, integer, or null")
}
fn visit_none<E>(self) -> std::result::Result<Self::Value, E> {
Ok(None)
}
fn visit_unit<E>(self) -> std::result::Result<Self::Value, E> {
Ok(None)
}
fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E> {
Ok(Some(value.to_string()))
}
fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E> {
Ok(Some(value))
}
fn visit_i64<E>(self, value: i64) -> std::result::Result<Self::Value, E> {
Ok(Some(value.to_string()))
}
fn visit_u64<E>(self, value: u64) -> std::result::Result<Self::Value, E> {
Ok(Some(value.to_string()))
}
}
deserializer.deserialize_any(FindingsVisitor)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityReview {
pub status: String,
pub auditor: Option<String>,
pub audited_at: Option<String>,
/// Number of findings raised by the audit. Integer to match the registry
/// schema and the published registry, which report a count.
pub findings: Option<u32>,
pub score: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangelogEntry {
pub version: String,
pub date: String,
pub notes: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TemplateEntry {
pub name: String,
#[serde(default)]
pub repository: Option<String>,
#[serde(default)]
pub security_review: Option<SecurityReview>,
#[serde(default)]
pub changelog: Option<Vec<ChangelogEntry>>,
pub description: String,
pub version: String,
pub source: TemplateSource,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub path: Option<String>,
#[serde(default)]
pub author: String,
#[serde(default)]
pub downloads: u32,
#[serde(default)]
pub verified: bool,
#[serde(default)]
pub created_at: String,
#[serde(default)]
pub updated_at: String,
/// Minimum StarForge CLI version required by this template (semver, e.g. "0.1.0").
/// `None` means no minimum — the template is compatible with all CLI versions.
#[serde(default)]
pub cli_version_min: Option<String>,
/// Maximum StarForge CLI version supported by this template (semver, e.g. "1.99.99").
/// `None` means no upper bound.
#[serde(default)]
pub cli_version_max: Option<String>,
/// Whether the template ships user-facing documentation (e.g. a README).
#[serde(default)]
pub documented: bool,
/// Declared maintenance state of the template.
#[serde(default)]
pub maintenance: MaintenanceStatus,
/// SPDX license identifier (e.g. "MIT", "Apache-2.0"). `None` if not declared.
#[serde(default)]
pub license: Option<String>,
/// URL of the template's source repository (e.g. GitHub link).
#[serde(default)]
pub repository_url: Option<String>,
/// Optional homepage for the template project.
#[serde(default)]
pub homepage: Option<String>,
/// Optional documentation URL for the template.
#[serde(default)]
pub documentation: Option<String>,
/// Categories that describe the template's purpose or domain.
#[serde(default)]
pub categories: Vec<String>,
/// Whether this template has been selected as featured by curators.
#[serde(default)]
pub featured: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TemplateUpdateImpact {
pub severity: String,
pub breaking_changes: bool,
pub summary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TemplateUpdateReport {
pub template_name: String,
pub previous_version: Option<String>,
pub latest_version: String,
pub update_available: bool,
pub compatibility: String,
pub impact: TemplateUpdateImpact,
pub migration_guidance: Vec<String>,
pub rollback_steps: Vec<String>,
pub backup_path: Option<String>,
pub tracked_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
struct TemplateUpdateState {
template_name: String,
backup_path: Option<String>,
previous_version: Option<String>,
last_report: Option<TemplateUpdateReport>,
}
/// Outcome of a template-vs-CLI compatibility check.
#[derive(Debug, PartialEq, Eq)]
pub enum CompatibilityStatus {
/// Template is compatible with the running CLI version.
Compatible,
/// Template requires a newer CLI version than what is running.
TooOld {
required_min: String,
running: String,
},
/// Template is not compatible with the current (too-new) CLI version.
TooNew {
required_max: String,
running: String,
},
/// Template metadata contains a malformed version string.
MalformedMetadata { reason: String },
}
/// Parse a semver string `"major.minor.patch"` into `(major, minor, patch)`.
///
/// Returns `Err` when the string cannot be parsed.
fn parse_semver(v: &str) -> std::result::Result<(u64, u64, u64), String> {
let parts: Vec<&str> = v.splitn(3, '.').collect();
if parts.len() != 3 {
return Err(format!(
"'{}' is not a valid semver string (expected major.minor.patch)",
v
));
}
let parse = |s: &str| {
s.parse::<u64>()
.map_err(|_| format!("non-numeric component '{}' in version '{}'", s, v))
};
Ok((parse(parts[0])?, parse(parts[1])?, parse(parts[2])?))
}
/// Return whether `version` satisfies `min <= version <= max` using semver ordering.
///
/// Either bound may be `None`, meaning unbounded in that direction.
pub fn check_version_range(
version: &str,
min: Option<&str>,
max: Option<&str>,
) -> CompatibilityStatus {
let running = match parse_semver(version) {
Ok(v) => v,
Err(reason) => return CompatibilityStatus::MalformedMetadata { reason },
};
if let Some(min_str) = min {
match parse_semver(min_str) {
Ok(min_v) => {
if running < min_v {
return CompatibilityStatus::TooOld {
required_min: min_str.to_string(),
running: version.to_string(),
};
}
}
Err(reason) => return CompatibilityStatus::MalformedMetadata { reason },
}
}
if let Some(max_str) = max {
match parse_semver(max_str) {
Ok(max_v) => {
if running > max_v {
return CompatibilityStatus::TooNew {
required_max: max_str.to_string(),
running: version.to_string(),
};
}
}
Err(reason) => return CompatibilityStatus::MalformedMetadata { reason },
}
}
CompatibilityStatus::Compatible
}
/// Check whether `entry` is compatible with the currently running StarForge CLI.
///
/// Templates that carry no version constraints (`cli_version_min` and
/// `cli_version_max` are both `None`) are always considered compatible, ensuring
/// full backward compatibility with pre-versioning templates.
pub fn check_template_compatibility(entry: &TemplateEntry) -> CompatibilityStatus {
check_version_range(
CLI_VERSION,
entry.cli_version_min.as_deref(),
entry.cli_version_max.as_deref(),
)
}
/// Validate that `entry` is compatible with the running CLI and return an
/// actionable error message if it is not.
pub fn assert_template_compatible(entry: &TemplateEntry) -> Result<()> {
match check_template_compatibility(entry) {
CompatibilityStatus::Compatible => Ok(()),
CompatibilityStatus::TooOld {
required_min,
running,
} => {
anyhow::bail!(
"Template '{}' requires StarForge >= {} but you are running {}.\n\
Please upgrade StarForge: https://github.com/Nanle-code/StarForge#installation",
entry.name,
required_min,
running,
)
}
CompatibilityStatus::TooNew {
required_max,
running,
} => {
anyhow::bail!(
"Template '{}' only supports StarForge <= {} but you are running {}.\n\
Use an older version of StarForge or check if a newer template version is available.",
entry.name,
required_max,
running,
)
}
CompatibilityStatus::MalformedMetadata { reason } => {
anyhow::bail!(
"Template '{}' has malformed version metadata: {}.\n\
Contact the template author to fix the cli_version_min / cli_version_max fields.",
entry.name,
reason,
)
}
}
}
fn infer_template_version_from_dir(path: &Path) -> Option<String> {
let cargo_toml = path.join("Cargo.toml");
if cargo_toml.exists() {
if let Ok(content) = fs::read_to_string(&cargo_toml) {
for line in content.lines() {
let trimmed = line.trim();
if let Some((_, value)) = trimmed.split_once("version") {
let value = value.trim().trim_matches('"');
if !value.is_empty() {
return Some(value.to_string());
}
}
}
}
}
let package_json = path.join("package.json");
if package_json.exists() {
if let Ok(content) = fs::read_to_string(&package_json) {
for line in content.lines() {
let trimmed = line.trim();
if let Some((_, value)) = trimmed.split_once("\"version\"") {
let value = value.trim().trim_matches(':').trim().trim_matches('"');
if !value.is_empty() {
return Some(value.to_string());
}
}
}
}
}
None
}
fn build_update_report(
template_name: &str,
previous_version: Option<&str>,
latest_version: &str,
entry: &TemplateEntry,
) -> Result<TemplateUpdateReport> {
let update_available = previous_version != Some(latest_version);
let compatibility = match check_template_compatibility(entry) {
CompatibilityStatus::Compatible => "Compatible with the current StarForge CLI".to_string(),
CompatibilityStatus::TooOld {
required_min,
running,
} => {
format!(
"Requires StarForge >= {} but the running CLI is {}",
required_min, running
)
}
CompatibilityStatus::TooNew {
required_max,
running,
} => {
format!(
"Requires StarForge <= {} but the running CLI is {}",
required_max, running
)
}
CompatibilityStatus::MalformedMetadata { reason } => {
format!("Version metadata is malformed: {}", reason)
}
};
let mut migration_guidance = Vec::new();
let mut severity = "low".to_string();
let mut breaking_changes = false;
let mut impact_summary =
"No material changes are expected for this template update.".to_string();
if update_available {
impact_summary = format!(
"The template is moving from {} to {}.",
previous_version.unwrap_or("an unknown version"),
latest_version
);
if let Some(latest) = entry.changelog.as_ref().and_then(|c| c.first()) {
let notes = latest.notes.clone();
if notes.to_lowercase().contains("breaking")
|| notes.to_lowercase().contains("migration")
|| notes.to_lowercase().contains("removed")
|| notes.to_lowercase().contains("deprecated")
{
breaking_changes = true;
severity = "high".to_string();
impact_summary.push_str(
" The release notes mention breaking or migration-sensitive changes.",
);
}
}
if previous_version.is_some() && latest_version.contains('.') {
let current_parts: Vec<&str> =
previous_version.unwrap_or_default().split('.').collect();
let latest_parts: Vec<&str> = latest_version.split('.').collect();
if current_parts.first() != latest_parts.first() {
severity = "high".to_string();
impact_summary.push_str(" The version jump appears to be a major release.");
breaking_changes = true;
} else if current_parts.get(1) != latest_parts.get(1) {
severity = "medium".to_string();
impact_summary
.push_str(" The update introduces a feature or compatibility change.");
}
}
migration_guidance.push("Review the release notes and regenerate any custom project scaffolding before shipping changes.".to_string());
migration_guidance.push(
"Re-run your template smoke test after the update to confirm everything still works."
.to_string(),
);
if breaking_changes {
migration_guidance.push("Treat this as a breaking update and plan a migration or rollback path before applying it broadly.".to_string());
}
}
if !compatibility.contains("Compatible") {
migration_guidance.push(format!("Compatibility note: {}", compatibility));
}
let rollback_steps = vec![
"The update process keeps a backup copy of the previous template contents.".to_string(),
format!("Use `starforge template rollback {}` to restore the previous template state if needed.", template_name),
];
Ok(TemplateUpdateReport {
template_name: template_name.to_string(),
previous_version: previous_version.map(str::to_string),
latest_version: latest_version.to_string(),
update_available,
compatibility,
impact: TemplateUpdateImpact {
severity: severity.clone(),
breaking_changes,
summary: impact_summary,
},
migration_guidance,
rollback_steps,
backup_path: None,
tracked_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
.to_string(),
})
}
fn write_update_state(template_path: &Path, state: &TemplateUpdateState) -> Result<()> {
let state_file = template_path.join(".starforge-update-state.json");
let contents = serde_json::to_string_pretty(state)?;
fs::write(&state_file, contents)
.with_context(|| format!("Failed to persist update state to {}", state_file.display()))?;
Ok(())
}
fn read_update_state(template_path: &Path) -> Result<Option<TemplateUpdateState>> {
let state_file = template_path.join(".starforge-update-state.json");
if !state_file.exists() {
return Ok(None);
}
let contents = fs::read_to_string(&state_file)
.with_context(|| format!("Failed to read update state from {}", state_file.display()))?;
let state = serde_json::from_str(&contents)
.with_context(|| format!("Failed to parse update state from {}", state_file.display()))?;
Ok(Some(state))
}
impl TemplateEntry {
/// Compute a 0-100 quality/trust score from the available signals.
///
/// The score blends verification status, documentation, usage (downloads)
/// and maintenance state so that dependable templates rank higher and are
/// easier to discover in a growing community catalog.
pub fn quality_score(&self) -> u8 {
let mut score: i32 = 0;
// Verified templates have been vetted — the strongest trust signal.
if self.verified {
score += 40;
}
// Documentation makes a template far easier to adopt.
if self.documented {
score += 20;
}
// Usage is a proxy for community confidence (capped so a single
// wildly-popular template cannot dominate the ranking).
score += (self.downloads / 50).min(30) as i32;
// Maintenance state rewards living projects and penalizes dead ones.
score += match self.maintenance {
MaintenanceStatus::Active => 10,
MaintenanceStatus::Maintained => 5,
MaintenanceStatus::Deprecated => -25,
MaintenanceStatus::Unknown => 0,
};
score.clamp(0, 100) as u8
}
/// Compact trust/quality badge strings for inline display in list/search output.
///
/// Returns short tokens like `[VERIFIED]`, `[DOCS]`, `[ACTIVE]`, `[DEPRECATED]`,
/// `[POPULAR]` that can be joined and appended to a single summary line.
pub fn trust_indicators(&self) -> Vec<String> {
let mut badges = Vec::new();
if self.verified {
badges.push("[VERIFIED]".to_string());
}
if self.documented {
badges.push("[DOCS]".to_string());
}
match self.maintenance {
MaintenanceStatus::Active => badges.push("[ACTIVE]".to_string()),
MaintenanceStatus::Maintained => badges.push("[MAINTAINED]".to_string()),
MaintenanceStatus::Deprecated => badges.push("[DEPRECATED]".to_string()),
MaintenanceStatus::Unknown => {}
}
if self.downloads >= 1000 {
badges.push("[POPULAR]".to_string());
}
if self.featured {
badges.push("[FEATURED]".to_string());
}
if self.is_trending() {
badges.push("[TRENDING]".to_string());
}
if self.is_spam_suspected() {
badges.push("[SUSPECT]".to_string());
}
badges
}
/// Estimate whether the template is likely a low-quality or spammy submission.
pub fn is_spam_suspected(&self) -> bool {
if self.verified {
return false;
}
let low_confidence = self.description.len() < 50 || self.tags.is_empty();
let poor_quality = self.quality_score() < 30;
let deprecated = self.maintenance == MaintenanceStatus::Deprecated;
poor_quality && (low_confidence || deprecated)
}
/// Return whether the template has recently shown activity or popularity.
pub fn is_trending(&self) -> bool {
if self.downloads >= 500 {
return true;
}
self.updated_recently()
}
pub fn updated_recently(&self) -> bool {
if self.updated_at.trim().is_empty() {
return false;
}
if let Ok(timestamp) = chrono::DateTime::parse_from_rfc3339(&self.updated_at) {
let age =
chrono::Utc::now().signed_duration_since(timestamp.with_timezone(&chrono::Utc));
age.num_days() <= 30
} else {
false
}
}
/// A broad health score reflecting quality, maintenance, trending, and
/// featured status.
pub fn health_score(&self) -> u8 {
let mut score = self.quality_score() as i32;
if self.is_trending() {
score += 5;
}
if self.featured {
score += 5;
}
if self.is_spam_suspected() {
score -= 15;
}
if self.maintenance == MaintenanceStatus::Deprecated {
score -= 10;
}
score.clamp(0, 100) as u8
}
}
#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
struct TemplateManifest {
name: Option<String>,
description: Option<String>,
version: Option<String>,
source: Option<String>,
#[serde(default)]
tags: Vec<String>,
}
const DEFAULT_REGISTRY: &str = include_str!("../../templates/registry.json");
const DEFAULT_REGISTRY_URL: &str =
"https://starforge-protocol.github.io/starforge/templates/registry.json";
fn registry_path() -> Result<PathBuf> {
let dir = crate::utils::config::config_dir().join("templates");
ensure_private_directory(&dir)?;
Ok(dir.join("registry.json"))
}
/// Create a cache directory with owner-only permissions and reject symlinked
/// directories. Cache contents influence generated projects and must not be
/// redirected into an attacker-controlled location.
fn ensure_private_directory(path: &Path) -> Result<()> {
if path.exists() {
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() || !metadata.is_dir() {
anyhow::bail!("Refusing unsafe cache directory: {}", path.display());
}
} else {
fs::create_dir_all(path).with_context(|| format!("Failed to create {}", path.display()))?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
/// Verify that the SHA-256 checksum of `bytes` matches `expected_hex`.
///
/// On mismatch, returns an error containing both the expected and actual hex strings.
pub fn verify_archive_checksum(bytes: &[u8], expected_hex: &str) -> Result<()> {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
let actual_bytes = hasher.finalize();
let actual_hex = hex::encode(actual_bytes);
let expected_clean = expected_hex.trim();
if !actual_hex.eq_ignore_ascii_case(expected_clean) {
anyhow::bail!(
"Checksum mismatch for template archive: expected {}, got {}",
expected_clean,
actual_hex
);
}
Ok(())
}
/// Returns true if the path looks like a supported template archive.
pub fn is_archive_path(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.map(|e| e.eq_ignore_ascii_case("zip"))
.unwrap_or(false)
}
/// Unix file-type bits (`st_mode & S_IFMT`) that mark a ZIP entry as a symlink,
/// as opposed to a regular file (`S_IFREG`) or directory (`S_IFDIR`).
const UNIX_S_IFMT: u32 = 0o170000;
const UNIX_S_IFLNK: u32 = 0o120000;
/// True if a Unix `unix_mode()` value (upper bits of a ZIP entry's external
/// attributes) marks the entry as a symlink rather than a regular file or
/// directory. Archives written on non-Unix systems have no such bits set.
fn is_symlink_mode(mode: u32) -> bool {
mode & UNIX_S_IFMT == UNIX_S_IFLNK
}
/// Extract a `.zip` template package into `dest`.
///
/// Rejects the whole archive — rather than silently dropping individual
/// entries — if any entry uses an absolute path, a `..` parent-traversal
/// component, resolves outside `dest` (zip-slip), or is a symlink. A
/// template package should never need any of these, and partially
/// extracting an otherwise-malicious archive would be misleading.
pub fn extract_zip_archive(archive: &Path, dest: &Path) -> Result<()> {
use zip::ZipArchive;
if !dest.exists() {
fs::create_dir_all(dest)?;
}
let file = fs::File::open(archive)
.with_context(|| format!("Failed to open archive {}", archive.display()))?;
let mut archive = ZipArchive::new(file)
.with_context(|| format!("Failed to read ZIP archive {}", archive.display()))?;
let dest_canon = dest.canonicalize().unwrap_or_else(|_| dest.to_path_buf());
for i in 0..archive.len() {
let mut entry = archive.by_index(i)?;
let raw_name = entry.name().to_string();
// `enclosed_name()` returns None for entries with an absolute path or a
// `..` component that would escape the archive root — reject those
// outright instead of quietly skipping them.
let entry_path = entry.enclosed_name().map(|p| p.to_path_buf()).ok_or_else(|| {
anyhow::anyhow!(
"Archive entry '{}' uses an absolute path or parent traversal ('..'), which is not allowed",
raw_name
)
})?;
if let Some(mode) = entry.unix_mode() {
if is_symlink_mode(mode) {
anyhow::bail!(
"Archive entry '{}' is a symlink, which is not allowed",
raw_name
);
}
}
let out_path = dest_canon.join(&entry_path);
if !out_path.starts_with(&dest_canon) {
anyhow::bail!(
"Archive entry '{}' escapes the destination directory (zip-slip)",
entry_path.display()
);
}
if entry.name().ends_with('/') {
fs::create_dir_all(&out_path)?;
} else {
if let Some(parent) = out_path.parent() {
fs::create_dir_all(parent)?;
}
let mut outfile = fs::File::create(&out_path)?;
std::io::copy(&mut entry, &mut outfile)?;
}
}
Ok(())
}
/// If `path` is a single top-level directory, return that directory; otherwise `path`.
pub fn normalize_template_root(path: &Path) -> Result<PathBuf> {
if !path.is_dir() {
return Ok(path.to_path_buf());
}
let mut entries = fs::read_dir(path)?
.filter_map(|e| e.ok())
.filter(|e| {
let name = e.file_name();
name != ".git" && name != "__MACOSX" && !name.to_string_lossy().starts_with('.')
})
.collect::<Vec<_>>();
entries.retain(|e| {
let n = e.file_name();
n != ".DS_Store"
});
if entries.len() == 1 && entries[0].path().is_dir() {
return Ok(entries[0].path());
}
Ok(path.to_path_buf())
}
/// Resolve a template path: directories are used as-is; ZIP archives are extracted to a temp dir.
pub fn resolve_template_source(path: &Path) -> Result<(PathBuf, Option<tempfile::TempDir>)> {
if is_archive_path(path) {
let temp =
tempfile::tempdir().context("Failed to create temp dir for archive extraction")?;
extract_zip_archive(path, temp.path())?;
let root = normalize_template_root(temp.path())?;
Ok((root, Some(temp)))
} else if path.is_dir() {
Ok((path.to_path_buf(), None))
} else {
anyhow::bail!(
"Template path must be a directory or .zip archive: {}",
path.display()
);
}
}
fn template_storage_dir() -> Result<PathBuf> {
let dir = crate::utils::config::config_dir()
.join("templates")
.join("storage");
ensure_private_directory(&dir)?;
Ok(dir)
}
fn template_cache_dir() -> Result<PathBuf> {
let dir = crate::utils::config::config_dir().join("template-cache");
ensure_private_directory(&dir)?;
Ok(dir)
}
/// Clone a git-sourced template into `~/.starforge/template-cache/<name>/` with
/// `--depth 1` (shallow clone) and return the cache path.
///
/// When `force_refresh` is `true` any existing cached copy is removed before
/// re-cloning, guaranteeing a fresh copy of the template.
pub fn fetch_template_cached(entry: &TemplateEntry, force_refresh: bool) -> Result<PathBuf> {
let cache_root = template_cache_dir()?;
let dest = cache_root.join(&entry.name);
if let Ok(metadata) = fs::symlink_metadata(&dest) {
if metadata.file_type().is_symlink() || !metadata.is_dir() {
anyhow::bail!("Refusing unsafe cached template path: {}", dest.display());
}
}
if dest.exists() {
let mut should_refresh = force_refresh;
if !should_refresh {
if let Ok(metadata) = fs::metadata(&dest) {
if let Ok(modified) = metadata.modified() {
use std::time::{Duration, SystemTime};
let ttl = Duration::from_secs(24 * 60 * 60); // 24 hours TTL
if SystemTime::now().duration_since(modified).unwrap_or(ttl) >= ttl {
should_refresh = true;
}
}
}
}
if should_refresh {
// Rename existing cache to a temporary name to preserve it in case refresh fails
let temp_old = cache_root.join(format!("{}.old", entry.name));
// Remove any existing temp_old directory
if temp_old.exists() {
fs::remove_dir_all(&temp_old)?;
}
fs::rename(&dest, &temp_old)?;
// Try to fetch new template
match fetch_template(entry, &dest) {
Ok(_) => {
// Success - clean up the old temp directory
fs::remove_dir_all(&temp_old).ok(); // Ignore errors during cleanup
Ok(dest)
}
Err(_) => {
// Failed - restore old cache and use it
if dest.exists() {
fs::remove_dir_all(&dest)?;
}
fs::rename(&temp_old, &dest)?;
Ok(dest)
}
}
} else {
Ok(dest)
}
} else {
fetch_template(entry, &dest)?;
Ok(dest)
}
}
/// Return the `src/lib.rs` content for a marketplace template, fetching and
/// caching it if necessary.
///
/// Returns `None` when the template name is not found in the registry.
pub async fn template_source_content(name: &str, force_refresh: bool) -> Result<Option<String>> {
let registry = load_registry().await?;
let entry = match registry.templates.into_iter().find(|t| t.name == name) {
Some(e) => e,
None => return Ok(None),
};
let cache_path = fetch_template_cached(&entry, force_refresh)?;
let lib_rs = cache_path.join("src").join("lib.rs");
if lib_rs.exists() {
let content = fs::read_to_string(&lib_rs)
.with_context(|| format!("Failed to read {}", lib_rs.display()))?;
Ok(Some(content))
} else {
Ok(None)
}
}
const REGISTRY_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
/// Whether the locally cached registry file is still within its TTL window.
fn is_cache_fresh(cache_path: &Path) -> bool {
fs::metadata(cache_path)
.and_then(|m| m.modified())
.map(|modified| {
std::time::SystemTime::now()
.duration_since(modified)
.unwrap_or(REGISTRY_CACHE_TTL)
< REGISTRY_CACHE_TTL
})
.unwrap_or(false)
}
/// Read and parse the locally cached registry file, if present and valid.
fn read_cached_registry(cache_path: &Path) -> Option<TemplateRegistry> {
let contents = fs::read_to_string(cache_path).ok()?;
parse_registry_checked(
&contents,
&format!("cached registry {}", cache_path.display()),
)
.ok()
}
/// Reset a file's modification time to now without changing its contents.
///
/// Used after a `304 Not Modified` response to restart the cache's TTL
/// window without re-downloading or re-writing the (unchanged) body.
fn touch(path: &Path) {
if let Ok(contents) = fs::read(path) {
let _ = fs::write(path, contents);
}
}
/// Read the ETag stored alongside the cached registry, if any.
fn read_stored_etag() -> Option<String> {
let etag_path = registry_etag_path().ok()?;
let etag = fs::read_to_string(etag_path).ok()?;
let etag = etag.trim();
if etag.is_empty() {
None