1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
5
6use semver::Version;
7use serde_json::Value;
8use sha2::{Digest, Sha256};
9use unicode_casefold::UnicodeCaseFold;
10use unicode_normalization::UnicodeNormalization;
11use walkdir::WalkDir;
12
13use crate::{
14 FolderbaseError, PlannedTemplateAddition, Result, TemplateAnswerType, TemplateAnswerValue,
15 TemplateArtifactKind, TemplateDescriptor, TemplatePackage, TemplateRenderPlan,
16};
17
18const BUILTIN_TEMPLATES: [(&str, &str, &str); 8] = [
19 (
20 "folderbase.person",
21 "0.2.0",
22 include_str!("../assets/templates/0.2/person/template.json"),
23 ),
24 (
25 "folderbase.organization",
26 "0.2.0",
27 include_str!("../assets/templates/0.2/organization/template.json"),
28 ),
29 (
30 "folderbase.engagement",
31 "0.2.0",
32 include_str!("../assets/templates/0.2/engagement/template.json"),
33 ),
34 (
35 "folderbase.project",
36 "0.2.1",
37 include_str!("../assets/templates/0.2/project-0.2.1/template.json"),
38 ),
39 (
40 "folderbase.project",
41 "0.2.2",
42 include_str!("../assets/templates/0.2/project-0.2.2/template.json"),
43 ),
44 (
45 "folderbase.customer",
46 "0.2.0",
47 include_str!("../assets/templates/0.2/customer/template.json"),
48 ),
49 (
50 "folderbase.temporary",
51 "0.2.0",
52 include_str!("../assets/templates/0.2/temporary/template.json"),
53 ),
54 (
55 "folderbase.custom",
56 "0.2.0",
57 include_str!("../assets/templates/0.2/custom/template.json"),
58 ),
59];
60
61const MAX_TEMPLATE_PACKAGE_BYTES: usize = 4 * 1024 * 1024;
62const MAX_TEMPLATE_QUESTIONS: usize = 256;
63const MAX_TEMPLATE_ARTIFACTS: usize = 4096;
64const MAX_TEMPLATE_UPGRADE_EDGES: usize = 256;
65const MAX_TEMPLATE_EXTENSION_FIELDS: usize = 32;
66const MAX_TEMPLATE_TEXT_BYTES: usize = 1024 * 1024;
67const MAX_RENDERED_TEMPLATE_BYTES: usize = 4 * 1024 * 1024;
68
69pub fn load_builtin_template(id: &str, version: &str) -> Result<TemplatePackage> {
74 let path = PathBuf::from(format!("<built-in:{id}@{version}>"));
75 let source = BUILTIN_TEMPLATES
76 .iter()
77 .find_map(|(candidate_id, candidate_version, source)| {
78 (*candidate_id == id && *candidate_version == version).then_some(*source)
79 })
80 .ok_or_else(|| FolderbaseError::InvalidRecord {
81 path: path.clone(),
82 message: format!("unknown built-in template {id}@{version}"),
83 })?;
84 let package: TemplatePackage =
85 serde_json::from_str(source).map_err(|source| FolderbaseError::json(&path, source))?;
86 validate_runtime_package(&path, &package)?;
87 if package.id != id || package.version != version {
88 return Err(FolderbaseError::InvalidRecord {
89 path,
90 message: format!(
91 "built-in template identity mismatch: requested {id}@{version}, embedded {}@{}",
92 package.id, package.version
93 ),
94 });
95 }
96 Ok(package)
97}
98
99pub fn list_templates(registry_root: &Path) -> Result<Vec<TemplateDescriptor>> {
100 if !registry_root.is_dir() {
101 return Err(FolderbaseError::InvalidRoot(registry_root.to_path_buf()));
102 }
103
104 let package_paths = package_paths(registry_root)?;
105
106 let mut templates = package_paths
107 .into_iter()
108 .map(|path| read_descriptor(&path))
109 .collect::<Result<Vec<_>>>()?;
110 templates.sort_by(|left, right| {
111 (&left.id, &left.version, &left.name).cmp(&(&right.id, &right.version, &right.name))
112 });
113 Ok(templates)
114}
115
116pub fn load_template(registry_root: &Path, id: &str, version: &str) -> Result<TemplatePackage> {
117 if !registry_root.is_dir() {
118 return Err(FolderbaseError::InvalidRoot(registry_root.to_path_buf()));
119 }
120
121 let mut matches = package_paths(registry_root)?
122 .into_iter()
123 .map(|path| read_package(&path))
124 .collect::<Result<Vec<_>>>()?
125 .into_iter()
126 .filter(|package| package.id == id && package.version == version)
127 .collect::<Vec<_>>();
128
129 if matches.len() != 1 {
130 return Err(FolderbaseError::InvalidRecord {
131 path: registry_root.to_path_buf(),
132 message: format!(
133 "expected exactly one template {id}@{version}, found {}",
134 matches.len()
135 ),
136 });
137 }
138 Ok(matches.remove(0))
139}
140
141pub fn render_template(
142 package: &TemplatePackage,
143 destination_root: &Path,
144 answers: &BTreeMap<String, TemplateAnswerValue>,
145) -> Result<TemplateRenderPlan> {
146 validate_destination_root(destination_root)?;
147 validate_runtime_package(destination_root, package)?;
148
149 validate_answers(package, answers, destination_root)?;
150
151 let mut additions = Vec::new();
152 let mut existing_paths = Vec::new();
153 let mut rendered_bytes = 0_usize;
154 for artifact in &package.artifacts {
155 if inspect_destination(destination_root, &artifact.target)? == DestinationState::Existing {
156 existing_paths.push(artifact.target.clone());
157 continue;
158 }
159 let content = match artifact.kind {
160 TemplateArtifactKind::Directory => None,
161 TemplateArtifactKind::Text => {
162 let content = render_content(
163 artifact.content.as_deref().unwrap_or_default(),
164 package,
165 answers,
166 destination_root,
167 )?;
168 rendered_bytes = rendered_bytes.saturating_add(content.len());
169 if rendered_bytes > MAX_RENDERED_TEMPLATE_BYTES {
170 return invalid_template(
171 destination_root,
172 "rendered template exceeds 4194304 bytes",
173 );
174 }
175 Some(content)
176 }
177 };
178 additions.push(PlannedTemplateAddition {
179 path: artifact.target.clone(),
180 kind: artifact.kind,
181 content,
182 });
183 }
184 additions.sort_by(|left, right| left.path.cmp(&right.path));
185 existing_paths.sort();
186
187 Ok(TemplateRenderPlan {
188 template_id: package.id.clone(),
189 template_version: package.version.clone(),
190 additions,
191 existing_paths,
192 })
193}
194
195pub(crate) fn render_template_for_capability_destination(
202 package: &TemplatePackage,
203 destination_label: &Path,
204 answers: &BTreeMap<String, TemplateAnswerValue>,
205) -> Result<TemplateRenderPlan> {
206 validate_runtime_package(destination_label, package)?;
207 validate_answers(package, answers, destination_label)?;
208
209 let mut additions = Vec::new();
210 let mut rendered_bytes = 0_usize;
211 for artifact in &package.artifacts {
212 let content = match artifact.kind {
213 TemplateArtifactKind::Directory => None,
214 TemplateArtifactKind::Text => {
215 let content = render_content(
216 artifact.content.as_deref().unwrap_or_default(),
217 package,
218 answers,
219 destination_label,
220 )?;
221 rendered_bytes = rendered_bytes.saturating_add(content.len());
222 if rendered_bytes > MAX_RENDERED_TEMPLATE_BYTES {
223 return invalid_template(
224 destination_label,
225 "rendered template exceeds 4194304 bytes",
226 );
227 }
228 Some(content)
229 }
230 };
231 additions.push(PlannedTemplateAddition {
232 path: artifact.target.clone(),
233 kind: artifact.kind,
234 content,
235 });
236 }
237 additions.sort_by(|left, right| left.path.cmp(&right.path));
238
239 Ok(TemplateRenderPlan {
240 template_id: package.id.clone(),
241 template_version: package.version.clone(),
242 additions,
243 existing_paths: Vec::new(),
244 })
245}
246
247pub fn template_package_sha256(package: &TemplatePackage) -> Result<String> {
248 let source = PathBuf::from("<template-package>");
249 validate_runtime_package(&source, package)?;
250 let value =
251 serde_json::to_value(package).map_err(|error| FolderbaseError::json(&source, error))?;
252 let mut bytes = Vec::new();
253 write_canonical_json(&value, &mut bytes);
254 Ok(format!("{:x}", Sha256::digest(bytes)))
255}
256
257fn write_canonical_json(value: &Value, output: &mut Vec<u8>) {
258 match value {
259 Value::Null => output.extend_from_slice(b"null"),
260 Value::Bool(value) => {
261 output.extend_from_slice(if *value { b"true" } else { b"false" });
262 }
263 Value::Number(value) => output.extend_from_slice(value.to_string().as_bytes()),
264 Value::String(value) => output.extend_from_slice(
265 serde_json::to_string(value)
266 .expect("JSON string serialization is infallible")
267 .as_bytes(),
268 ),
269 Value::Array(values) => {
270 output.push(b'[');
271 for (index, value) in values.iter().enumerate() {
272 if index > 0 {
273 output.push(b',');
274 }
275 write_canonical_json(value, output);
276 }
277 output.push(b']');
278 }
279 Value::Object(values) => {
280 output.push(b'{');
281 let mut entries = values.iter().collect::<Vec<_>>();
282 entries.sort_by(|(left, _), (right, _)| left.as_bytes().cmp(right.as_bytes()));
283 for (index, (key, value)) in entries.into_iter().enumerate() {
284 if index > 0 {
285 output.push(b',');
286 }
287 output.extend_from_slice(
288 serde_json::to_string(key)
289 .expect("JSON object key serialization is infallible")
290 .as_bytes(),
291 );
292 output.push(b':');
293 write_canonical_json(value, output);
294 }
295 output.push(b'}');
296 }
297 }
298}
299
300fn read_descriptor(path: &Path) -> Result<TemplateDescriptor> {
301 let package = read_package(path)?;
302 Ok(TemplateDescriptor {
303 id: package.id,
304 version: package.version,
305 name: package.name,
306 })
307}
308
309fn package_paths(registry_root: &Path) -> Result<Vec<PathBuf>> {
310 let mut paths = Vec::new();
311 for entry in WalkDir::new(registry_root).follow_links(false) {
312 let entry = entry.map_err(|error| {
313 let path = error
314 .path()
315 .map(Path::to_path_buf)
316 .unwrap_or_else(|| registry_root.to_path_buf());
317 if let Some(source) = error.into_io_error() {
318 FolderbaseError::io(path, source)
319 } else {
320 FolderbaseError::InvalidRecord {
321 path,
322 message: "template registry traversal failed".to_owned(),
323 }
324 }
325 })?;
326 if entry.file_type().is_file() && entry.file_name() == "template.json" {
327 paths.push(entry.into_path());
328 }
329 }
330 paths.sort();
331 Ok(paths)
332}
333
334fn validate_answers(
335 package: &TemplatePackage,
336 answers: &BTreeMap<String, TemplateAnswerValue>,
337 error_path: &Path,
338) -> Result<()> {
339 if answers.len() > MAX_TEMPLATE_QUESTIONS {
340 return invalid_template(error_path, "template answers exceed 256 entries");
341 }
342 let questions = package
343 .questions
344 .iter()
345 .map(|question| (question.id.as_str(), question))
346 .collect::<BTreeMap<_, _>>();
347 let unknown = answers
348 .keys()
349 .find(|id| !questions.contains_key(id.as_str()));
350 if let Some(id) = unknown {
351 return invalid_template(error_path, format!("unknown template answer: {id}"));
352 }
353 for question in &package.questions {
354 let Some(answer) = answers.get(&question.id) else {
355 if question.required {
356 return invalid_template(
357 error_path,
358 format!("missing required template answer: {}", question.id),
359 );
360 }
361 continue;
362 };
363 let correct_type = matches!(
364 (question.answer_type, answer),
365 (TemplateAnswerType::Text, TemplateAnswerValue::Text(_))
366 | (TemplateAnswerType::Boolean, TemplateAnswerValue::Boolean(_))
367 );
368 if !correct_type {
369 return invalid_template(
370 error_path,
371 format!("wrong type for template answer: {}", question.id),
372 );
373 }
374 if matches!(answer, TemplateAnswerValue::Text(value) if value.len() > MAX_TEMPLATE_TEXT_BYTES)
375 {
376 return invalid_template(
377 error_path,
378 format!("template answer exceeds 1048576 bytes: {}", question.id),
379 );
380 }
381 if question.required
382 && matches!(answer, TemplateAnswerValue::Text(value) if value.trim().is_empty())
383 {
384 return invalid_template(
385 error_path,
386 format!("blank required template answer: {}", question.id),
387 );
388 }
389 }
390 Ok(())
391}
392
393fn render_content(
394 content: &str,
395 package: &TemplatePackage,
396 answers: &BTreeMap<String, TemplateAnswerValue>,
397 error_path: &Path,
398) -> Result<String> {
399 let question_ids = package
400 .questions
401 .iter()
402 .map(|question| question.id.as_str())
403 .collect::<BTreeSet<_>>();
404 let mut rendered = String::with_capacity(content.len());
405 for segment in parse_content(content, error_path)? {
406 match segment {
407 ContentSegment::Literal(literal) => rendered.push_str(literal),
408 ContentSegment::Placeholder(id) => {
409 if !question_ids.contains(id) {
410 return invalid_template(
411 error_path,
412 format!("unknown template placeholder: {id}"),
413 );
414 }
415 let Some(answer) = answers.get(id) else {
416 return invalid_template(
417 error_path,
418 format!("missing template answer for placeholder: {id}"),
419 );
420 };
421 match answer {
422 TemplateAnswerValue::Text(value) => rendered.push_str(value),
423 TemplateAnswerValue::Boolean(value) => {
424 rendered.push_str(if *value { "true" } else { "false" })
425 }
426 }
427 }
428 }
429 if rendered.len() > MAX_TEMPLATE_TEXT_BYTES {
430 return invalid_template(
431 error_path,
432 "rendered template artifact exceeds 1048576 bytes",
433 );
434 }
435 }
436 Ok(rendered)
437}
438
439fn invalid_template<T>(path: &Path, message: impl Into<String>) -> Result<T> {
440 Err(FolderbaseError::InvalidRecord {
441 path: path.to_path_buf(),
442 message: message.into(),
443 })
444}
445
446fn read_package(path: &Path) -> Result<TemplatePackage> {
447 let bytes = fs::read(path).map_err(|source| FolderbaseError::io(path, source))?;
448 let package: TemplatePackage =
449 serde_json::from_slice(&bytes).map_err(|source| FolderbaseError::json(path, source))?;
450 validate_runtime_package(path, &package)?;
451 Ok(package)
452}
453
454pub(crate) fn validate_runtime_package(path: &Path, package: &TemplatePackage) -> Result<()> {
455 if unicode_normalization::UNICODE_VERSION != (17, 0, 0)
456 || unicode_casefold::UNICODE_VERSION != (9, 0, 0)
457 {
458 return invalid_template(
459 path,
460 "template path policy requires Unicode NFC 17.0.0 and full-default case folding 9.0.0",
461 );
462 }
463 let encoded =
464 serde_json::to_vec(package).map_err(|source| FolderbaseError::json(path, source))?;
465 if encoded.len() > MAX_TEMPLATE_PACKAGE_BYTES {
466 return invalid_template(path, "template package exceeds 4194304 bytes");
467 }
468 if !supported_protocol_version(&package.protocol_version) {
469 return invalid_template(
470 path,
471 format!(
472 "unsupported template protocol {} (supported: valid SemVer 0.2.x)",
473 package.protocol_version
474 ),
475 );
476 }
477 if !valid_package_id(&package.id) {
478 return invalid_template(path, format!("invalid template package id: {}", package.id));
479 }
480 if package.id.len() > 256 {
481 return invalid_template(path, "template package id exceeds 256 bytes");
482 }
483 let package_version =
484 Version::parse(&package.version).map_err(|_| FolderbaseError::InvalidRecord {
485 path: path.to_path_buf(),
486 message: format!("invalid template package version: {}", package.version),
487 })?;
488 if package.name.trim().is_empty() {
489 return invalid_template(path, "template name is empty");
490 }
491 if package.name.len() > 4096 {
492 return invalid_template(path, "template name exceeds 4096 bytes");
493 }
494 if package
495 .description
496 .as_deref()
497 .is_some_and(|description| description.len() > 65_536)
498 {
499 return invalid_template(path, "template description exceeds 65536 bytes");
500 }
501 if package.questions.len() > MAX_TEMPLATE_QUESTIONS {
502 return invalid_template(path, "template exceeds 256 questions");
503 }
504 if package.artifacts.len() > MAX_TEMPLATE_ARTIFACTS {
505 return invalid_template(path, "template exceeds 4096 artifacts");
506 }
507 if package.upgrade_edges.len() > MAX_TEMPLATE_UPGRADE_EDGES {
508 return invalid_template(path, "template exceeds 256 upgrade edges");
509 }
510 validate_extensions(path, "template package", package.extensions.keys())?;
511 let mut question_ids = BTreeSet::new();
512 for question in &package.questions {
513 validate_extensions(path, "template question", question.extensions.keys())?;
514 if !valid_question_id(&question.id) {
515 return invalid_template(
516 path,
517 format!("invalid template question id: {}", question.id),
518 );
519 }
520 if question.id.len() > 128 || question.prompt.len() > 4096 {
521 return invalid_template(
522 path,
523 format!("template question exceeds its text bound: {}", question.id),
524 );
525 }
526 if !question_ids.insert(question.id.as_str()) {
527 return invalid_template(
528 path,
529 format!("duplicate template question id: {}", question.id),
530 );
531 }
532 if question.prompt.trim().is_empty() {
533 return invalid_template(
534 path,
535 format!("template question prompt is empty: {}", question.id),
536 );
537 }
538 }
539 validate_upgrade_graph(path, package, &package_version)?;
540 for edge in &package.upgrade_edges {
541 validate_extensions(path, "template upgrade edge", edge.extensions.keys())?;
542 if edge
543 .notes
544 .as_deref()
545 .is_some_and(|notes| notes.len() > 4096)
546 {
547 return invalid_template(path, "template upgrade notes exceed 4096 bytes");
548 }
549 }
550
551 let mut targets = BTreeSet::new();
552 for artifact in &package.artifacts {
553 validate_extensions(path, "template artifact", artifact.extensions.keys())?;
554 if !safe_artifact_target(&artifact.target) {
555 return invalid_template(
556 path,
557 format!("unsafe artifact target: {}", artifact.target.display()),
558 );
559 }
560 let target_text = artifact
561 .target
562 .to_str()
563 .expect("safe_artifact_target accepted only UTF-8");
564 let folded = target_text
565 .nfc()
566 .collect::<String>()
567 .case_fold()
568 .collect::<String>()
569 .nfc()
570 .collect::<String>();
571 if !targets.insert(folded) {
572 return invalid_template(
573 path,
574 format!("duplicate artifact target: {}", artifact.target.display()),
575 );
576 }
577 if artifact.install != "create_if_missing" {
578 return invalid_template(path, "unsupported artifact installation mode");
579 }
580 match (artifact.kind, artifact.content.as_ref()) {
581 (TemplateArtifactKind::Text, None) => {
582 return invalid_template(path, "text artifact is missing inline content");
583 }
584 (TemplateArtifactKind::Directory, Some(_)) => {
585 return invalid_template(path, "directory artifact cannot contain text");
586 }
587 _ => {}
588 }
589 if let Some(content) = artifact.content.as_deref() {
590 if content.len() > MAX_TEMPLATE_TEXT_BYTES {
591 return invalid_template(path, "template artifact content exceeds 1048576 bytes");
592 }
593 for segment in parse_content(content, path)? {
594 if let ContentSegment::Placeholder(placeholder) = segment
595 && !question_ids.contains(placeholder)
596 {
597 return invalid_template(
598 path,
599 format!("unknown template placeholder: {placeholder}"),
600 );
601 }
602 }
603 }
604 }
605 Ok(())
606}
607
608fn validate_upgrade_graph(
609 path: &Path,
610 package: &TemplatePackage,
611 package_version: &Version,
612) -> Result<()> {
613 let mut graph = BTreeMap::<String, Vec<String>>::new();
614 let mut parsed_edges = Vec::new();
615 for edge in &package.upgrade_edges {
616 let from = Version::parse(&edge.from).map_err(|_| FolderbaseError::InvalidRecord {
617 path: path.to_path_buf(),
618 message: format!("invalid upgrade edge version: {}", edge.from),
619 })?;
620 let to = Version::parse(&edge.to).map_err(|_| FolderbaseError::InvalidRecord {
621 path: path.to_path_buf(),
622 message: format!("invalid upgrade edge version: {}", edge.to),
623 })?;
624 graph
625 .entry(edge.from.clone())
626 .or_default()
627 .push(edge.to.clone());
628 parsed_edges.push((edge, from, to));
629 }
630 if graph_has_cycle(&graph) {
631 return invalid_template(path, "template upgrade graph contains a cycle");
632 }
633 for (edge, from, to) in parsed_edges {
634 if from >= to {
635 return invalid_template(
636 path,
637 format!(
638 "upgrade edge does not advance: {} -> {}",
639 edge.from, edge.to
640 ),
641 );
642 }
643 if to != *package_version {
644 return invalid_template(
645 path,
646 format!(
647 "upgrade edge does not terminate at package version: {} -> {}",
648 edge.from, edge.to
649 ),
650 );
651 }
652 }
653 Ok(())
654}
655
656fn graph_has_cycle(graph: &BTreeMap<String, Vec<String>>) -> bool {
657 fn visit<'a>(
658 node: &'a str,
659 graph: &'a BTreeMap<String, Vec<String>>,
660 visiting: &mut BTreeSet<&'a str>,
661 visited: &mut BTreeSet<&'a str>,
662 ) -> bool {
663 if visited.contains(node) {
664 return false;
665 }
666 if !visiting.insert(node) {
667 return true;
668 }
669 if graph.get(node).is_some_and(|neighbors| {
670 neighbors
671 .iter()
672 .any(|neighbor| visit(neighbor, graph, visiting, visited))
673 }) {
674 return true;
675 }
676 visiting.remove(node);
677 visited.insert(node);
678 false
679 }
680
681 let mut visiting = BTreeSet::new();
682 let mut visited = BTreeSet::new();
683 graph
684 .keys()
685 .any(|node| visit(node, graph, &mut visiting, &mut visited))
686}
687
688fn validate_extensions<'a>(
689 path: &Path,
690 location: &str,
691 keys: impl Iterator<Item = &'a String>,
692) -> Result<()> {
693 let keys = keys.into_iter().collect::<Vec<_>>();
694 if keys.len() > MAX_TEMPLATE_EXTENSION_FIELDS {
695 return invalid_template(path, format!("{location} exceeds 32 extension fields"));
696 }
697 if let Some(key) = keys.into_iter().find(|key| !key.starts_with("x-")) {
698 return invalid_template(path, format!("unknown {location} property: {key}"));
699 }
700 Ok(())
701}
702
703fn valid_question_id(id: &str) -> bool {
704 let mut characters = id.chars();
705 let Some(first) = characters.next() else {
706 return false;
707 };
708 (first.is_ascii_lowercase() || first.is_ascii_digit())
709 && characters.all(|character| {
710 character.is_ascii_lowercase()
711 || character.is_ascii_digit()
712 || matches!(character, '_' | '-')
713 })
714}
715
716#[derive(Debug, PartialEq, Eq)]
717enum ContentSegment<'a> {
718 Literal(&'a str),
719 Placeholder(&'a str),
720}
721
722fn parse_content<'a>(content: &'a str, error_path: &Path) -> Result<Vec<ContentSegment<'a>>> {
723 let mut segments = Vec::new();
724 let mut remaining = content;
725 while let Some(start) = remaining.find("${") {
726 if start > 0 {
727 segments.push(ContentSegment::Literal(&remaining[..start]));
728 }
729 let after_open = &remaining[start + 2..];
730 let Some(end) = after_open.find('}') else {
731 return invalid_template(error_path, "unterminated template placeholder");
732 };
733 let id = &after_open[..end];
734 if !valid_question_id(id) {
735 return invalid_template(error_path, format!("invalid template placeholder: {id}"));
736 }
737 segments.push(ContentSegment::Placeholder(id));
738 remaining = &after_open[end + 1..];
739 }
740 if !remaining.is_empty() {
741 segments.push(ContentSegment::Literal(remaining));
742 }
743 Ok(segments)
744}
745
746fn safe_artifact_target(target: &Path) -> bool {
747 use std::path::Component;
748
749 let Some(text) = target.to_str() else {
750 return false;
751 };
752 if text.is_empty()
753 || text.len() > 4096
754 || target.is_absolute()
755 || text.contains('\\')
756 || text.contains("//")
757 || text.ends_with('/')
758 || (text.as_bytes().get(1) == Some(&b':')
759 && text.as_bytes().first().is_some_and(u8::is_ascii_alphabetic))
760 {
761 return false;
762 }
763 let components = target.components().collect::<Vec<_>>();
764 if components.len() > 128 {
765 return false;
766 }
767 components.into_iter().all(|component| {
768 let Component::Normal(component) = component else {
769 return false;
770 };
771 let Some(component) = component.to_str() else {
772 return false;
773 };
774 if component.is_empty()
775 || component.len() > 255
776 || component.ends_with(['.', ' '])
777 || component
778 .chars()
779 .any(|character| character <= '\u{1f}' || r#"<>:"|?*"#.contains(character))
780 {
781 return false;
782 }
783 let stem = component.split('.').next().unwrap_or(component);
784 !matches!(
785 stem.to_ascii_uppercase().as_str(),
786 "CON"
787 | "PRN"
788 | "AUX"
789 | "NUL"
790 | "COM1"
791 | "COM2"
792 | "COM3"
793 | "COM4"
794 | "COM5"
795 | "COM6"
796 | "COM7"
797 | "COM8"
798 | "COM9"
799 | "LPT1"
800 | "LPT2"
801 | "LPT3"
802 | "LPT4"
803 | "LPT5"
804 | "LPT6"
805 | "LPT7"
806 | "LPT8"
807 | "LPT9"
808 | "COM¹"
809 | "COM²"
810 | "COM³"
811 | "LPT¹"
812 | "LPT²"
813 | "LPT³"
814 )
815 })
816}
817
818fn supported_protocol_version(version: &str) -> bool {
819 Version::parse(version).is_ok_and(|version| version.major == 0 && version.minor == 2)
820}
821
822fn valid_package_id(id: &str) -> bool {
823 let mut characters = id.chars();
824 let Some(first) = characters.next() else {
825 return false;
826 };
827 (first.is_ascii_lowercase() || first.is_ascii_digit())
828 && characters.all(|character| {
829 character.is_ascii_lowercase()
830 || character.is_ascii_digit()
831 || matches!(character, '.' | '_' | '-')
832 })
833}
834
835fn validate_destination_root(destination_root: &Path) -> Result<()> {
836 let metadata = fs::symlink_metadata(destination_root)
837 .map_err(|source| FolderbaseError::io(destination_root, source))?;
838 if metadata.file_type().is_symlink() {
839 return invalid_template(destination_root, "destination root is a symlink");
840 }
841 if !metadata.is_dir() {
842 return Err(FolderbaseError::InvalidRoot(destination_root.to_path_buf()));
843 }
844 Ok(())
845}
846
847#[derive(Debug, Clone, Copy, PartialEq, Eq)]
848enum DestinationState {
849 Absent,
850 Existing,
851}
852
853fn inspect_destination(root: &Path, relative: &Path) -> Result<DestinationState> {
854 let mut current = root.to_path_buf();
855 let component_count = relative.components().count();
856 for (index, component) in relative.components().enumerate() {
857 current.push(component.as_os_str());
858 match fs::symlink_metadata(¤t) {
859 Ok(metadata) => {
860 if metadata.file_type().is_symlink() {
861 return invalid_template(
862 ¤t,
863 format!(
864 "template destination contains a symlink: {}",
865 relative.display()
866 ),
867 );
868 }
869 if index + 1 < component_count && !metadata.is_dir() {
870 return invalid_template(
871 ¤t,
872 format!(
873 "template destination ancestor is not a directory: {}",
874 relative.display()
875 ),
876 );
877 }
878 if index + 1 == component_count {
879 return Ok(DestinationState::Existing);
880 }
881 }
882 Err(source) if source.kind() == ErrorKind::NotFound => {
883 return Ok(DestinationState::Absent);
884 }
885 Err(source) => return Err(FolderbaseError::io(¤t, source)),
886 }
887 }
888 Ok(DestinationState::Absent)
889}