Skip to main content

thunderstore_engine/profile/
portability.rs

1//! r2modman-compatible profile portability: `.r2z` export/import and shareable
2//! Thunderstore profile codes.
3//!
4//! A `.r2z` is a zip holding an `export.r2x` manifest (the mod list) plus the
5//! target's config files. Note the manifest names the version field `version`,
6//! while `mods.yml` names it `versionNumber` — same shape, different key.
7//!
8//! Every operation is target-directory generic (`*_in`), with an r2modman-layout
9//! wrapper, so a game server can export its tracked mod set just as a desktop
10//! client exports a named profile.
11//!
12//! **Import installs each mod at its exported version.** An exported version
13//! Thunderstore no longer serves fails that mod.
14
15#![deny(missing_docs)]
16
17#[cfg(feature = "io")]
18use crate::client::ThunderstoreClient;
19use crate::error::{Error, Result};
20use crate::profile::modlist::{ProfileMod, SemVer};
21#[cfg(feature = "io")]
22use crate::util::{canonicalize_missing, same_file};
23#[cfg(feature = "io")]
24use base64::Engine as _;
25#[cfg(feature = "io")]
26use base64::engine::general_purpose::STANDARD;
27use serde::{Deserialize, Serialize};
28#[cfg(feature = "io")]
29use std::fs;
30#[cfg(feature = "io")]
31use std::io::{Cursor, Read, Write};
32use std::path::PathBuf;
33#[cfg(feature = "io")]
34use std::path::{Component, Path};
35#[cfg(feature = "io")]
36use zip::write::{FileOptions, ZipWriter};
37
38/// One entry of an `export.r2x` mod list.
39///
40/// `#[non_exhaustive]`: fields may be added as the format grows.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[non_exhaustive]
43pub struct ExportMod {
44  /// The `Owner-Name` identifier.
45  pub name: String,
46  /// The version. Note: `version`, not `versionNumber` as in `mods.yml`.
47  pub version: SemVer,
48  /// Whether the mod was enabled. Absent upstream means enabled.
49  #[serde(default = "default_true")]
50  pub enabled: bool,
51}
52
53/// serde default for [`ExportMod::enabled`]: r2modman treats an absent `enabled`
54/// as `true`.
55fn default_true() -> bool {
56  true
57}
58
59/// The `export.r2x` manifest inside a `.r2z`.
60///
61/// `#[non_exhaustive]`: fields may be added as the format grows.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64#[non_exhaustive]
65pub struct ExportFormat {
66  /// The exported profile's display name.
67  pub profile_name: String,
68  /// The exported mod list.
69  pub mods: Vec<ExportMod>,
70}
71
72/// Builds an [`ExportFormat`] from a target's `mods.yml` entries.
73pub fn export_format_from_mods(profile_name: &str, mods: &[ProfileMod]) -> ExportFormat {
74  let mods = mods
75    .iter()
76    .map(|entry| ExportMod {
77      name: entry.name.clone(),
78      version: entry.version_number,
79      enabled: entry.enabled,
80    })
81    .collect();
82
83  ExportFormat {
84    profile_name: profile_name.to_string(),
85    mods,
86  }
87}
88
89/// Serializes an [`ExportFormat`] to `export.r2x` YAML.
90pub fn export_r2x_to_string(export: &ExportFormat) -> Result<String> {
91  serde_yaml_ng::to_string(export)
92    .map_err(|e| Error::Profile(format!("serializing export.r2x: {e}")))
93}
94
95/// Parses `export.r2x` YAML.
96pub fn parse_export_r2x(yaml: &str) -> Result<ExportFormat> {
97  serde_yaml_ng::from_str(yaml).map_err(|e| Error::Profile(format!("parsing export.r2x: {e}")))
98}
99
100/// Filename suffixes r2modman treats as config files worth exporting.
101#[cfg(feature = "io")]
102const CONFIG_EXTENSIONS: [&str; 6] = [".cfg", ".txt", ".json", ".yml", ".yaml", ".ini"];
103
104/// Whether a target-relative path is excluded from an export.
105///
106/// Mirrors r2modman's export prune list: manager state (`_state/`, `mods.yml`),
107/// the runtime it never ships (`dotnet/`, `MelonLoader/`, `GDWeave/core|mods`),
108/// per-mod package metadata, and `BepInEx/config/` (added separately under the
109/// zip's `config/` folder). Pure — no filesystem access.
110#[cfg(feature = "io")]
111fn is_pruned(rel: &Path) -> bool {
112  let normalized = rel.to_string_lossy().replace('\\', "/");
113
114  let prefixes = [
115    "dotnet/",
116    "_state/",
117    "MelonLoader/",
118    "BepInEx/config/",
119    "GDWeave/core/",
120    "GDWeave/mods/",
121  ];
122
123  if prefixes.iter().any(|p| normalized.starts_with(p)) {
124    return true;
125  }
126
127  if normalized == "mods.yml" || normalized == "GDWeave/GDWeave.log" {
128    return true;
129  }
130
131  is_plugin_manifest(&normalized)
132}
133
134/// Whether a path is a per-mod `BepInEx/plugins/<Owner-Name>/manifest.json`,
135/// which r2modman strips from an export.
136#[cfg(feature = "io")]
137fn is_plugin_manifest(normalized: &str) -> bool {
138  let parts: Vec<&str> = normalized.split('/').collect();
139
140  parts.len() == 4
141    && parts[0] == "BepInEx"
142    && parts[1] == "plugins"
143    && parts[3].eq_ignore_ascii_case("manifest.json")
144}
145
146/// Whether a filename ends with one of [`CONFIG_EXTENSIONS`] (case-insensitive).
147/// Pure — no filesystem access.
148#[cfg(feature = "io")]
149fn is_config_file(rel: &Path) -> bool {
150  let name = match rel.file_name().and_then(|n| n.to_str()) {
151    Some(name) => name.to_ascii_lowercase(),
152    None => return false,
153  };
154
155  CONFIG_EXTENSIONS.iter().any(|ext| name.ends_with(ext))
156}
157
158/// Collects the target-relative paths an export should carry: config files that
159/// survive the prune list, sorted for a deterministic archive.
160#[cfg(feature = "io")]
161fn collect_export_paths(target_dir: &Path) -> Result<Vec<PathBuf>> {
162  let mut found = Vec::new();
163
164  collect_files(target_dir, target_dir, &mut found)?;
165
166  let mut kept: Vec<PathBuf> = found
167    .into_iter()
168    .filter(|rel| is_config_file(rel) && !is_pruned(rel))
169    .collect();
170
171  kept.sort();
172
173  Ok(kept)
174}
175
176/// Recursively collects file paths under `dir`, relative to `root`, skipping
177/// symlinks so an export cannot escape the target (mirrors `install::walk_files`).
178#[cfg(feature = "io")]
179fn collect_files(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
180  if !dir.is_dir() {
181    return Ok(());
182  }
183
184  for entry in
185    fs::read_dir(dir).map_err(|e| Error::Profile(format!("reading {}: {}", dir.display(), e)))?
186  {
187    let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
188    let path = entry.path();
189    let metadata = fs::symlink_metadata(&path)
190      .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
191
192    if metadata.file_type().is_symlink() {
193      continue;
194    }
195
196    if metadata.is_dir() {
197      collect_files(root, &path, out)?;
198    } else if let Ok(rel) = path.strip_prefix(root) {
199      out.push(rel.to_path_buf());
200    }
201  }
202
203  Ok(())
204}
205
206/// The manifest filename inside a `.r2z`.
207#[cfg(feature = "io")]
208const EXPORT_MANIFEST: &str = "export.r2x";
209
210/// The archive folder that a target's `BepInEx/config/` tree is re-rooted into.
211#[cfg(feature = "io")]
212const ARCHIVE_CONFIG_DIR: &str = "config";
213
214/// The target-relative path of the shared BepInEx config tree.
215#[cfg(feature = "io")]
216const BEPINEX_CONFIG_DIR: &str = "BepInEx/config";
217
218/// Builds the `.r2z` bytes for `target_dir`.
219///
220/// The archive carries `EXPORT_MANIFEST` (the mod list from `mods.yml`), the
221/// target's `BepInEx/config/` tree re-rooted under `config/`, and every other
222/// surviving config file at its target-relative path. Binaries and manager state
223/// are never exported (see `is_pruned`).
224///
225/// `profile_name` is recorded in the manifest as the exported profile's name and
226/// need not match any directory on disk.
227///
228/// # Errors
229///
230/// - [`Error::Profile`] if `target_dir` has no readable
231///   `mods.yml`, or the mod list cannot be serialized.
232/// - [`Error::Io`] if a config file cannot be read.
233/// - [`Error::Zip`] if the archive cannot be written.
234///
235/// # Examples
236///
237/// ```no_run
238/// use std::path::Path;
239/// use thunderstore_engine::profile::portability::build_r2z_in;
240///
241/// let bytes = build_r2z_in(Path::new("/srv/valheim"), "my-profile")?;
242///
243/// std::fs::write("my-profile.r2z", &bytes)?;
244/// # Ok::<(), thunderstore_engine::Error>(())
245/// ```
246#[cfg(feature = "io")]
247pub fn build_r2z_in(target_dir: &Path, profile_name: &str) -> Result<Vec<u8>> {
248  let mods = crate::profile::modlist::read(target_dir)?;
249  let manifest = export_r2x_to_string(&export_format_from_mods(profile_name, &mods))?;
250
251  let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
252  let options: FileOptions<'_, ()> =
253    FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
254
255  zip
256    .start_file(EXPORT_MANIFEST, options)
257    .map_err(|e| Error::Profile(format!("writing {EXPORT_MANIFEST}: {e}")))?;
258  zip
259    .write_all(manifest.as_bytes())
260    .map_err(|e| Error::Profile(format!("writing {EXPORT_MANIFEST}: {e}")))?;
261
262  let config_root = target_dir.join(BEPINEX_CONFIG_DIR);
263  let mut shared = Vec::new();
264
265  collect_files(&config_root, &config_root, &mut shared)?;
266  shared.sort();
267
268  for rel in shared {
269    let archive_path = format!(
270      "{ARCHIVE_CONFIG_DIR}/{}",
271      rel.to_string_lossy().replace('\\', "/")
272    );
273
274    add_zip_file(&mut zip, options, &archive_path, &config_root.join(&rel))?;
275  }
276
277  for rel in collect_export_paths(target_dir)? {
278    let archive_path = rel.to_string_lossy().replace('\\', "/");
279
280    add_zip_file(&mut zip, options, &archive_path, &target_dir.join(&rel))?;
281  }
282
283  let cursor = zip
284    .finish()
285    .map_err(|e| Error::Profile(format!("finishing export archive: {e}")))?;
286
287  Ok(cursor.into_inner())
288}
289
290/// Adds one file to the archive under `archive_path`.
291#[cfg(feature = "io")]
292fn add_zip_file(
293  zip: &mut ZipWriter<Cursor<Vec<u8>>>,
294  options: FileOptions<'_, ()>,
295  archive_path: &str,
296  source: &Path,
297) -> Result<()> {
298  let bytes =
299    fs::read(source).map_err(|e| Error::Profile(format!("reading {}: {}", source.display(), e)))?;
300
301  zip
302    .start_file(archive_path, options)
303    .map_err(|e| Error::Profile(format!("writing {archive_path}: {e}")))?;
304  zip
305    .write_all(&bytes)
306    .map_err(|e| Error::Profile(format!("writing {archive_path}: {e}")))?;
307
308  Ok(())
309}
310
311/// Writes `target_dir`'s export to `<out_dir>/<profile_name>_<timestamp_millis>.r2z`
312/// and returns the path. `timestamp_millis` is supplied by the caller so the
313/// filename is deterministic and testable. `profile_name` is refused as
314/// [`BadProfile::InvalidName`](crate::profile::layout::BadProfile::InvalidName)
315/// if it could escape `out_dir`, since it becomes part of the output filename.
316/// It is not held to the stricter
317/// [`crate::profile::layout::validate_name`] rules, so a profile named under
318/// older rules can still be exported.
319#[cfg(feature = "io")]
320pub fn export_to_file_in(
321  target_dir: &Path,
322  profile_name: &str,
323  out_dir: &Path,
324  timestamp_millis: u64,
325) -> Result<PathBuf> {
326  crate::profile::layout::validate_existing_name(profile_name)?;
327
328  let bytes = build_r2z_in(target_dir, profile_name)?;
329
330  fs::create_dir_all(out_dir)
331    .map_err(|e| Error::Profile(format!("creating {}: {}", out_dir.display(), e)))?;
332
333  let path = out_dir.join(format!("{profile_name}_{timestamp_millis}.r2z"));
334
335  fs::write(&path, bytes)
336    .map_err(|e| Error::Profile(format!("writing {}: {}", path.display(), e)))?;
337
338  Ok(path)
339}
340
341/// Exports an r2modman-layout profile into `<base>/<game>/exports/`.
342/// See [`export_to_file_in`].
343#[cfg(feature = "io")]
344pub fn export_to_file(
345  base: &Path,
346  game: &str,
347  profile_name: &str,
348  timestamp_millis: u64,
349) -> Result<PathBuf> {
350  export_to_file_in(
351    &crate::profile::layout::profile_dir(base, game, profile_name),
352    profile_name,
353    &base.join(game).join("exports"),
354    timestamp_millis,
355  )
356}
357
358/// Upstream ceiling on a shared profile's zip, before base64.
359#[cfg(feature = "io")]
360const MAX_EXPORT_CODE_BYTES: usize = 20_000_000;
361
362/// The literal prefix Thunderstore's profile-code payload carries.
363#[cfg(feature = "io")]
364const PROFILE_DATA_PREFIX: &str = "#r2modman";
365
366/// Wraps `.r2z` bytes in the profile-code payload: the `#r2modman` prefix, a
367/// newline, then base64 of the zip. Rejects a zip above the upstream 20 MB cap
368/// before any upload is attempted.
369#[cfg(feature = "io")]
370fn encode_profile_payload(zip_bytes: &[u8]) -> Result<Vec<u8>> {
371  if zip_bytes.len() > MAX_EXPORT_CODE_BYTES {
372    return Err(Error::SizeLimitExceeded {
373      context: "profile export".to_string(),
374      limit: MAX_EXPORT_CODE_BYTES as u64,
375      actual: Some(zip_bytes.len() as u64),
376    });
377  }
378
379  let mut payload = format!("{PROFILE_DATA_PREFIX}\n").into_bytes();
380
381  payload.extend_from_slice(STANDARD.encode(zip_bytes).as_bytes());
382
383  Ok(payload)
384}
385
386/// Exports `target_dir` as a shareable Thunderstore profile code.
387///
388/// `profile_name` is not validated here: unlike [`export_to_file_in`], it never
389/// becomes part of a filesystem path — it only rides inside the `export.r2x`
390/// manifest carried by the uploaded payload.
391#[cfg(feature = "io")]
392pub async fn export_code_in(
393  target_dir: &Path,
394  profile_name: &str,
395  client: &ThunderstoreClient,
396) -> Result<String> {
397  let payload = encode_profile_payload(&build_r2z_in(target_dir, profile_name)?)?;
398
399  client.create_profile_code(&payload).await
400}
401
402/// Exports an r2modman-layout profile as a shareable code. See [`export_code_in`].
403#[cfg(feature = "io")]
404pub async fn export_code(
405  base: &Path,
406  game: &str,
407  profile_name: &str,
408  client: &ThunderstoreClient,
409) -> Result<String> {
410  export_code_in(
411    &crate::profile::layout::profile_dir(base, game, profile_name),
412    profile_name,
413    client,
414  )
415  .await
416}
417
418/// Extensions never written by an import: a shared profile carries config, not
419/// executable code, so a hostile `.r2z` cannot plant a binary.
420#[cfg(feature = "io")]
421const BLOCKED_IMPORT_EXTENSIONS: [&str; 12] = [
422  ".dll", ".exe", ".bat", ".cmd", ".com", ".ps1", ".sh", ".js", ".vbs", ".msi", ".scr", ".jar",
423];
424
425/// Unwraps a profile-code response body into `.r2z` bytes: validates the
426/// `#r2modman` prefix, then base64-decodes the remainder.
427#[cfg(feature = "io")]
428fn decode_profile_payload(body: &[u8]) -> Result<Vec<u8>> {
429  let text = std::str::from_utf8(body)
430    .map_err(|e| Error::Profile(format!("profile code is not valid UTF-8: {e}")))?;
431
432  let encoded = text
433    .strip_prefix(PROFILE_DATA_PREFIX)
434    .ok_or_else(|| Error::Profile("profile code is missing its #r2modman prefix".to_string()))?;
435
436  STANDARD
437    .decode(encoded.trim())
438    .map_err(|e| Error::Profile(format!("decoding profile code: {e}")))
439}
440
441/// Ceiling on a single inflated archive entry, and on the cumulative inflated
442/// size of an import. A shared profile carries text config, so this sits far
443/// above any legitimate export while rejecting a decompression bomb (DEFLATE
444/// can reach ~1032:1, so a tiny `.r2z` can otherwise inflate to gigabytes).
445#[cfg(feature = "io")]
446const MAX_IMPORT_ENTRY_BYTES: u64 = 16 * 1024 * 1024;
447
448/// See `MAX_IMPORT_ENTRY_BYTES`.
449#[cfg(feature = "io")]
450const MAX_IMPORT_TOTAL_BYTES: u64 = 64 * 1024 * 1024;
451
452/// Reads one archive entry fully into memory, capped at `MAX_IMPORT_ENTRY_BYTES`.
453///
454/// The cap is checked against the bytes actually streamed out of the
455/// decompressor, not any size the archive declares, so a crafted high-ratio
456/// entry cannot forge its way past it. Returns [`Error::ExtractLimitExceeded`]
457/// on breach — the same variant [`crate::extract`] uses for this class of guard.
458#[cfg(feature = "io")]
459fn read_capped_entry(entry: &mut impl Read, label: &str) -> Result<Vec<u8>> {
460  let mut bytes = Vec::new();
461
462  entry
463    .take(MAX_IMPORT_ENTRY_BYTES + 1)
464    .read_to_end(&mut bytes)
465    .map_err(|e| Error::Profile(format!("reading {label}: {e}")))?;
466
467  if bytes.len() as u64 > MAX_IMPORT_ENTRY_BYTES {
468    return Err(Error::ExtractLimitExceeded(format!(
469      "{label} exceeds the {MAX_IMPORT_ENTRY_BYTES}-byte per-entry import cap"
470    )));
471  }
472
473  Ok(bytes)
474}
475
476/// Reads an export manifest from either a `.r2z` archive or bare `.r2x` YAML.
477#[cfg(feature = "io")]
478pub fn read_export(bytes: &[u8]) -> Result<ExportFormat> {
479  match zip::ZipArchive::new(Cursor::new(bytes.to_vec())) {
480    Ok(mut archive) => {
481      let mut entry = archive
482        .by_name(EXPORT_MANIFEST)
483        .map_err(|e| Error::Profile(format!("archive has no {EXPORT_MANIFEST}: {e}")))?;
484
485      let manifest_bytes = read_capped_entry(&mut entry, EXPORT_MANIFEST)?;
486      let manifest = std::str::from_utf8(&manifest_bytes)
487        .map_err(|e| Error::Profile(format!("{EXPORT_MANIFEST} is not valid UTF-8: {e}")))?;
488
489      parse_export_r2x(manifest)
490    }
491    Err(_) => {
492      let text = std::str::from_utf8(bytes)
493        .map_err(|e| Error::Profile(format!("export is neither a zip nor UTF-8 YAML: {e}")))?;
494
495      parse_export_r2x(text)
496    }
497  }
498}
499
500/// Maps an archive entry name to its target-relative destination, or `None` when
501/// the entry must not be written.
502///
503/// The manifest, `mods.yml`, and `_state/` are skipped (the mod list and its
504/// state records come from installing, not copying; an export never holds
505/// them), a `config/…` entry is re-rooted back under `BepInEx/`, and any
506/// executable extension or unsafe path is refused. Pure — no filesystem access.
507///
508/// The blocklist check is matched against the name with trailing dots and
509/// spaces stripped: Windows silently drops those from the final path component
510/// on create, so an entry named e.g. `Evil.dll.` would otherwise land on disk as
511/// `Evil.dll` and bypass the filter on the platform that matters most here.
512#[cfg(feature = "io")]
513fn import_config_key(name: &str) -> Option<PathBuf> {
514  let normalized = name.replace('\\', "/");
515
516  if normalized.is_empty() || normalized.ends_with('/') {
517    return None;
518  }
519
520  if normalized == EXPORT_MANIFEST || normalized == "mods.yml" {
521    return None;
522  }
523
524  let lower = normalized.to_ascii_lowercase();
525  let probe = lower.trim_end_matches(['.', ' ']);
526
527  if BLOCKED_IMPORT_EXTENSIONS
528    .iter()
529    .any(|ext| probe.ends_with(ext))
530  {
531    return None;
532  }
533
534  let remapped = match normalized.strip_prefix("config/") {
535    Some(rest) => format!("{BEPINEX_CONFIG_DIR}/{rest}"),
536    None => normalized,
537  };
538
539  let path = PathBuf::from(remapped);
540
541  for component in path.components() {
542    match component {
543      Component::Normal(_) | Component::CurDir => {}
544      Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
545    }
546  }
547
548  let first = path.components().find_map(|component| match component {
549    Component::Normal(name) => Some(name.to_string_lossy().to_ascii_lowercase()),
550    _ => None,
551  });
552
553  if first.is_some_and(|first| first.trim_end_matches(['.', ' ']) == "_state") {
554    return None;
555  }
556
557  Some(path)
558}
559
560/// Whether `bytes` open with a zip archive's `PK` magic number, rather than
561/// being a bare `.r2x` YAML manifest (see [`read_export`]).
562///
563/// A zip's first local-file header, or the end-of-central-directory record of
564/// an empty zip, always starts with the two bytes `PK`; a YAML manifest never
565/// does. This distinguishes "not a zip at all" from "a zip that failed to
566/// parse" — the latter is a real corruption and must still surface as an
567/// error rather than be swallowed as "no configs".
568#[cfg(feature = "io")]
569fn looks_like_zip(bytes: &[u8]) -> bool {
570  bytes.len() >= 2 && &bytes[0..2] == b"PK"
571}
572
573/// Refuses to write through a pre-existing symlink at `dest`.
574///
575/// Mirrors [`crate::install::apply_install`]'s `RefuseSymlink` handling: a
576/// symlink already sitting at the destination is refused rather than
577/// followed, so a pre-planted leaf link cannot redirect the write outside the
578/// target. This is best-effort: it inspects the final path component only
579/// (not symlinked parent directories) and is not race-free against a
580/// concurrent attacker mutating the target mid-import.
581#[cfg(feature = "io")]
582fn refuse_symlink_dest(dest: &Path) -> Result<()> {
583  let is_symlink = fs::symlink_metadata(dest)
584    .map(|metadata| metadata.file_type().is_symlink())
585    .unwrap_or(false);
586
587  if is_symlink {
588    return Err(Error::Profile(format!(
589      "refusing to write through a symlink at {}",
590      dest.display()
591    )));
592  }
593
594  Ok(())
595}
596
597/// Extracts an export's config files into `target_dir`, returning the
598/// target-relative paths written. Entries `import_config_key` rejects are
599/// skipped.
600///
601/// A bare `.r2x` manifest (see [`read_export`]) carries no config files, so
602/// `zip_bytes` that don't even look like a zip (see `looks_like_zip`) are
603/// treated as "nothing to extract" rather than an error; a payload that does
604/// look like a zip but fails to parse is a genuine corruption and still
605/// surfaces as an error.
606///
607/// A pre-existing symlink at an entry's destination is refused rather than
608/// followed (see `refuse_symlink_dest`), so a planted leaf link cannot
609/// redirect a write outside `target_dir`.
610///
611/// Each entry is bounded by `MAX_IMPORT_ENTRY_BYTES`, and the running total
612/// across the whole import by `MAX_IMPORT_TOTAL_BYTES`, so a decompression
613/// bomb hiding in an otherwise-valid config entry cannot exhaust memory.
614#[cfg(feature = "io")]
615pub fn extract_configs_in(target_dir: &Path, zip_bytes: &[u8]) -> Result<Vec<PathBuf>> {
616  if !looks_like_zip(zip_bytes) {
617    return Ok(Vec::new());
618  }
619
620  let mut archive = zip::ZipArchive::new(Cursor::new(zip_bytes.to_vec()))
621    .map_err(|e| Error::Profile(format!("reading export archive: {e}")))?;
622
623  let mut written = Vec::new();
624  let mut total_written: u64 = 0;
625
626  for index in 0..archive.len() {
627    let mut entry = archive
628      .by_index(index)
629      .map_err(|e| Error::Profile(format!("reading archive entry {index}: {e}")))?;
630
631    let rel = match import_config_key(entry.name()) {
632      Some(rel) => rel,
633      None => continue,
634    };
635
636    let bytes = read_capped_entry(&mut entry, &rel.display().to_string())?;
637
638    total_written += bytes.len() as u64;
639
640    if total_written > MAX_IMPORT_TOTAL_BYTES {
641      return Err(Error::ExtractLimitExceeded(format!(
642        "import exceeds the {MAX_IMPORT_TOTAL_BYTES}-byte cumulative import cap"
643      )));
644    }
645
646    let dest = target_dir.join(&rel);
647
648    if let Some(parent) = dest.parent() {
649      fs::create_dir_all(parent)
650        .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
651    }
652
653    refuse_symlink_dest(&dest)?;
654    fs::write(&dest, &bytes)
655      .map_err(|e| Error::Profile(format!("writing {}: {}", dest.display(), e)))?;
656
657    written.push(rel);
658  }
659
660  Ok(written)
661}
662
663/// Imports a `.r2z` (or a bare `.r2x` manifest, which carries no configs) into
664/// `target_dir`: installs every mod the manifest lists (each with its
665/// dependency closure) and restores the recorded `enabled` state, then
666/// extracts the archive's config files.
667///
668/// These three steps run in this order deliberately:
669///
670/// 1. **Install first, extract configs second.** Most configs live in the
671///    shared `BepInEx/config/`, which an install never removes. A few mods
672///    keep settings inside their own `BepInEx/plugins/<Owner-Name>/` folder
673///    instead, and installing (or updating) a mod deletes that folder and
674///    writes the package's files fresh, as r2modman does. Extracting configs
675///    before installing would lose those exported files the moment their
676///    owning mod is installed; extracting after ensures the exported config
677///    is what's left on disk. A mod skipped as already current is not
678///    touched.
679/// 2. **Disable pass runs after every install, inside the batch.** It still
680///    runs only once every mod in the batch is installed, which is what
681///    makes it immune to a dependency installed later re-enabling an entry
682///    the export marked disabled. It now happens inside `install_batch`
683///    rather than as a loop here, and running before config extraction is
684///    harmless because disabling renames a mod's files rather than
685///    rewriting its config.
686///
687/// **Installs the exported version, not the latest.** A mod or version the
688/// index no longer has fails the import.
689///
690/// `cache_base` is the package cache root and must not be `target_dir` — see
691/// [`crate::profile::install_mod_in`]. Returns the identifiers the import
692/// covers, dependencies included, split into those it installed and those it
693/// skipped as already current, so importing a profile the target already
694/// matches reports every mod as unchanged.
695#[allow(clippy::too_many_arguments)]
696#[cfg(feature = "io")]
697pub async fn import_r2z_in(
698  target_dir: &Path,
699  cache_base: &Path,
700  eco: &crate::ecosystem::Ecosystem,
701  index: &crate::models::PackageIndex,
702  client: &ThunderstoreClient,
703  game: &str,
704  zip_bytes: &[u8],
705  installed_at_time: u64,
706) -> Result<ImportedMods> {
707  let export = read_export(zip_bytes)?;
708
709  let desired: Vec<String> = export
710    .mods
711    .iter()
712    .map(|entry| format!("{}-{}", entry.name, entry.version))
713    .collect();
714  let protect: Vec<String> = export
715    .mods
716    .iter()
717    .filter(|entry| !entry.enabled)
718    .map(|entry| entry.name.clone())
719    .collect();
720  let mut batch = crate::profile::InstallBatch::new(desired, protect);
721
722  // A mod already recorded at its exported version is skipped rather than
723  // reinstalled, so one the export has enabled but the target has disabled
724  // would otherwise stay disabled.
725  batch.enable_requested = export
726    .mods
727    .iter()
728    .filter(|entry| entry.enabled)
729    .map(|entry| entry.name.clone())
730    .collect();
731
732  let outcome = crate::profile::install_batch(
733    target_dir,
734    cache_base,
735    eco,
736    index,
737    client,
738    game,
739    &batch,
740    installed_at_time,
741  )
742  .await?;
743
744  // Configs are not extracted after a failure, so the import is unfinished.
745  // Importing again once the cause is fixed skips the mods already installed
746  // and completes it. A missing exported version is never fixed by a retry
747  // alone, so the message does not promise one will.
748  if !outcome.failed.is_empty() {
749    return Err(Error::ImportUnfinished {
750      failures: outcome.failed,
751    });
752  }
753
754  // Configs are extracted after every install, so an exported per-mod config
755  // wins over the package default the install just wrote.
756  let config_dir = target_dir.to_path_buf();
757  let config_zip = zip_bytes.to_vec();
758
759  tokio::task::spawn_blocking(move || extract_configs_in(&config_dir, &config_zip))
760    .await
761    .map_err(|e| Error::Install(format!("config extraction task failed: {e}")))??;
762
763  // `install_batch` already sorts, dedups, and keeps the two lists disjoint.
764  Ok(ImportedMods {
765    installed: outcome.succeeded,
766    unchanged: outcome.unchanged,
767  })
768}
769
770/// What [`import_r2z_in`] and [`import_code_in`] did with each mod the import
771/// covers.
772///
773/// Both lists include the dependency closure, are sorted and deduplicated, and
774/// never name the same identifier.
775#[derive(Debug, Clone, Default, PartialEq, Eq)]
776#[non_exhaustive]
777pub struct ImportedMods {
778  /// Identifiers this import installed or reinstalled.
779  pub installed: Vec<String>,
780  /// Identifiers skipped because the target already recorded the version that
781  /// would be installed, with its files in place.
782  ///
783  /// Skipped means not reinstalled, not untouched: the import still applies the
784  /// export's enabled state, so a mod listed here may have been enabled or
785  /// disabled to match it.
786  pub unchanged: Vec<String>,
787}
788
789/// Imports a shared profile by its Thunderstore code. See [`import_r2z_in`].
790#[allow(clippy::too_many_arguments)]
791#[cfg(feature = "io")]
792pub async fn import_code_in(
793  target_dir: &Path,
794  cache_base: &Path,
795  eco: &crate::ecosystem::Ecosystem,
796  index: &crate::models::PackageIndex,
797  client: &ThunderstoreClient,
798  game: &str,
799  code: &str,
800  installed_at_time: u64,
801) -> Result<ImportedMods> {
802  let body = client.fetch_profile_code(code).await?;
803  let zip_bytes = decode_profile_payload(&body)?;
804
805  import_r2z_in(
806    target_dir,
807    cache_base,
808    eco,
809    index,
810    client,
811    game,
812    &zip_bytes,
813    installed_at_time,
814  )
815  .await
816}
817
818/// Copies an existing r2modman profile directory into `target_dir`, adopting its
819/// `mods.yml`, installed files, and config as-is.
820///
821/// This is a raw directory adoption, not an install: nothing is downloaded and no
822/// package cache is populated, so re-enabling a `State`-tracked mod afterwards
823/// requires that mod to be reinstalled first.
824///
825/// **The result may not be uninstallable.** r2modman never wrote this engine's
826/// `_state` tracker, so an adopted mod loader ends up with a `mods.yml` entry and
827/// no install record, which is exactly what
828/// [`ensure_removable`](crate::profile::ensure_removable) refuses and therefore
829/// what [`uninstall_mod_in`](crate::profile::uninstall_mod_in) refuses. Use
830/// [`adopt_r2modman_dir_in`] instead unless the offline raw copy is what you
831/// actually want.
832///
833/// # Errors
834///
835/// - [`Error::Profile`] if `source_profile_dir` is not a
836///   directory, or if it and `target_dir` are nested in one another (a copy
837///   would otherwise recurse into its own output; see
838///   [`ensure_disjoint_trees`]).
839/// - [`Error::Io`] if a file cannot be read or written.
840///
841/// Failure can leave `target_dir` partially populated: the copy is not
842/// transactional, so a caller that must not keep a half-imported profile should
843/// import into a scratch directory and move it into place on success.
844#[cfg(feature = "io")]
845pub fn import_r2modman_dir(source_profile_dir: &Path, target_dir: &Path) -> Result<()> {
846  if !source_profile_dir.is_dir() {
847    return Err(Error::Profile(format!(
848      "{} is not a profile directory",
849      source_profile_dir.display()
850    )));
851  }
852
853  ensure_disjoint_trees(source_profile_dir, target_dir)?;
854
855  copy_tree(source_profile_dir, target_dir)
856}
857
858/// What [`adopt_r2modman_dir_in`] adopted, and what it had to reinstall to leave
859/// the profile coherent.
860#[derive(Debug, Clone, Default)]
861#[non_exhaustive]
862pub struct AdoptedProfile {
863  /// Every identifier the adopted `mods.yml` names, in the order it named them.
864  pub adopted: Vec<String>,
865  /// The subset reinstalled from Thunderstore so it would have an install
866  /// record, in the order they were reinstalled.
867  ///
868  /// Each came from the package's **latest** version, so a version the source
869  /// profile had pinned is not preserved. A caller that shows this to a user
870  /// should say so.
871  pub reinstalled: Vec<String>,
872}
873
874/// Copies an existing r2modman profile directory into `target_dir` and then
875/// reinstalls whatever the copy alone would have left un-uninstallable, so the
876/// result is a profile this engine can manage.
877///
878/// [`import_r2modman_dir`] on its own cannot produce one: r2modman never wrote
879/// this engine's `_state` tracker, so an adopted mod loader gets a `mods.yml`
880/// entry and no install record, and
881/// [`ensure_removable`](crate::profile::ensure_removable) then refuses to remove
882/// it. This reinstalls each such loader from its package, which is the *only* way
883/// to get an exact file list for one.
884///
885/// Reconstructing the tracker from the copied files instead is deliberately not
886/// attempted. A loader installs into `BepInEx/core`, which is itself a declared
887/// route, so a loader file sitting there is shape-indistinguishable from one a
888/// user dropped in by hand; attributing files by shape would let a later sweep
889/// delete a file the loader never placed.
890///
891/// **Reinstalls the latest version, not the adopted one.** Resolution goes
892/// through [`crate::models::DependencyGraph`] with a bare `Owner-Name`, so a
893/// version the source profile had pinned is not preserved. The returned
894/// [`AdoptedProfile::reinstalled`] names exactly which packages this happened to,
895/// so a caller can disclose it.
896///
897/// Takes a `client` rather than a prefetched
898/// [`PackageIndex`](crate::models::PackageIndex), unlike [`import_r2z_in`]: the
899/// index is fetched only once something actually needs reinstalling, so adopting
900/// a profile that names no unrecorded loader stays fully offline. Requiring the
901/// caller to pass an index would cost them a network round trip to find out they
902/// did not need one.
903///
904/// `cache_base` is the package cache root and must not be `target_dir`; see
905/// [`crate::profile::install_mod_in`].
906#[allow(clippy::too_many_arguments)]
907#[cfg(feature = "io")]
908pub async fn adopt_r2modman_dir_in(
909  source_profile_dir: &Path,
910  target_dir: &Path,
911  cache_base: &Path,
912  eco: &crate::ecosystem::Ecosystem,
913  client: &ThunderstoreClient,
914  game: &str,
915  installed_at_time: u64,
916) -> Result<AdoptedProfile> {
917  import_r2modman_dir(source_profile_dir, target_dir)?;
918
919  let adopted: Vec<String> = crate::profile::modlist::read(target_dir)?
920    .iter()
921    .map(|entry| entry.name.clone())
922    .collect();
923
924  // Every recognised loader, not merely the first: the registry is keyed on
925  // package identity rather than on a game, so nothing rules out an adopted
926  // profile naming two.
927  //
928  // Presence is tested rather than parsing the record, so a target that already
929  // holds an *unreadable* one is left exactly as it was. Overwriting it would be
930  // a destructive guess, and `ensure_removable` reports it plainly later.
931  let unrecorded: Vec<String> = adopted
932    .iter()
933    .filter(|name| eco.modloader_package(name).is_some())
934    .filter(|name| !crate::install::state_file_path(target_dir, name).exists())
935    .cloned()
936    .collect();
937
938  if unrecorded.is_empty() {
939    return Ok(AdoptedProfile {
940      adopted,
941      reinstalled: unrecorded,
942    });
943  }
944
945  let index = client.get_manifest().await?;
946
947  // Forced: the copied mods.yml already records each loader, usually at the
948  // version that would be installed, which an ordinary install skips. The
949  // reinstall is the point, since it is what writes the record.
950  for full_name in &unrecorded {
951    crate::profile::install_named_in(
952      target_dir,
953      cache_base,
954      eco,
955      &index,
956      client,
957      game,
958      full_name,
959      true,
960      installed_at_time,
961    )
962    .await?;
963  }
964
965  Ok(AdoptedProfile {
966    adopted,
967    reinstalled: unrecorded,
968  })
969}
970
971/// What an adoption installed, what it could not, and what it swept.
972///
973/// Does not derive `Clone`: `failed` carries an [`Error`] per item, and `Error`
974/// itself does not implement `Clone` (it wraps `io::Error` and `reqwest::Error`,
975/// neither of which do either).
976#[derive(Debug, Default)]
977#[non_exhaustive]
978pub struct AdoptOutcome {
979  /// Desired identifiers this adoption installed, sorted.
980  pub adopted: Vec<String>,
981  /// Desired identifiers already recorded and left alone, sorted: either at the
982  /// version that would be installed, or absent from the index so there was
983  /// nothing to install.
984  pub unchanged: Vec<String>,
985  /// Identifiers still missing from the record, sorted. Their files may be on
986  /// disk from an older installer, unrecorded, where a reconcile would sweep
987  /// them as delisted.
988  ///
989  /// `adopted`, `unchanged`, and `remaining` never name the same identifier. A
990  /// desired name that is recorded but whose install failed, such as a failed
991  /// upgrade, is in none of them, only in `failed`.
992  pub remaining: Vec<String>,
993  /// Root-relative folders the completing sweep removed. Empty unless every
994  /// desired name is recorded, that is unless `remaining` is empty.
995  pub swept: Vec<PathBuf>,
996  /// Each desired name that errored while installing, with the reason
997  /// (unresolvable dependency, network error, checksum mismatch, and so on).
998  ///
999  /// This answers a different question than `remaining`: a name lands here only
1000  /// when its own install attempt failed, whereas `remaining` is derived from the
1001  /// record afterwards and also holds a name that resolved to nothing without
1002  /// erroring. A name can therefore be in `remaining` without being in `failed`.
1003  pub failed: Vec<(String, Error)>,
1004}
1005
1006/// Whether `desired` names anything the record does not yet hold.
1007///
1008/// Keyed on missing entries rather than a missing record: the record is written
1009/// after each package installs, so an adoption that failed partway leaves the
1010/// file present but incomplete. Keying on the file's existence would both hide
1011/// that and refuse the retry, stranding the remaining mods on disk where a later
1012/// reconcile would sweep them.
1013#[cfg(feature = "io")]
1014pub fn needs_adoption(target_dir: &Path, desired: &[String]) -> Result<bool> {
1015  if desired.is_empty() {
1016    return Ok(false);
1017  }
1018
1019  let recorded = crate::profile::modlist::read(target_dir).unwrap_or_default();
1020
1021  Ok(
1022    desired
1023      .iter()
1024      .any(|name| crate::profile::modlist::find(&recorded, name).is_none()),
1025  )
1026}
1027
1028/// Adopts `desired` into `target_dir`'s record, then reconciles once complete.
1029///
1030/// Installing clears and rewrites whatever an older folder-based installer
1031/// placed, so this is safe over an existing install and safe to retry after a
1032/// partial failure: an entry already recorded at its latest version is skipped.
1033///
1034/// The delisted sweep runs **only** when every desired name is recorded, whether
1035/// this run installed it or found it already current. Running it against a
1036/// partial record would delete mods that have not been reached yet.
1037///
1038/// A name counts as adopted when its record carries this run's
1039/// `installed_at_time`, since every install stamps it and a skipped mod keeps its
1040/// old one. A caller must therefore pass a fresh time
1041/// ([`now_millis`](crate::profile::modlist::now_millis)); reusing one from an
1042/// earlier install reports the mods that install placed as adopted again.
1043#[allow(clippy::too_many_arguments)]
1044#[cfg(feature = "io")]
1045pub async fn adopt_names_in(
1046  target_dir: &Path,
1047  cache_base: &Path,
1048  eco: &crate::ecosystem::Ecosystem,
1049  index: &crate::models::PackageIndex,
1050  client: &ThunderstoreClient,
1051  game: &str,
1052  desired: &[String],
1053  installed_at_time: u64,
1054) -> Result<AdoptOutcome> {
1055  let batch = crate::profile::plan_install_batch(target_dir, desired, &[])?;
1056
1057  let batch_outcome = crate::profile::install_batch(
1058    target_dir,
1059    cache_base,
1060    eco,
1061    index,
1062    client,
1063    game,
1064    &batch,
1065    installed_at_time,
1066  )
1067  .await?;
1068
1069  let failed = batch_outcome.failed;
1070  let failed_names: std::collections::BTreeSet<&str> =
1071    failed.iter().map(|(name, _)| name.as_str()).collect();
1072
1073  // Everything is read back from the record rather than from the batch outcome.
1074  // A name can be missing because its own install failed or because it resolved
1075  // to nothing. And a name another desired mod installed as a dependency before
1076  // that mod's install errored is absent from `succeeded`, then found current by
1077  // its own attempt and listed as unchanged, so only the record's install time
1078  // tells this run's installs apart from mods it left alone.
1079  let recorded = crate::profile::modlist::read(target_dir).unwrap_or_default();
1080
1081  let mut adopted: Vec<String> = Vec::new();
1082  let mut unchanged: Vec<String> = Vec::new();
1083  let mut remaining: Vec<String> = Vec::new();
1084
1085  for name in desired {
1086    let Some(entry) = crate::profile::modlist::find(&recorded, name) else {
1087      remaining.push(name.clone());
1088
1089      continue;
1090    };
1091
1092    if failed_names.contains(name.as_str()) {
1093      // Recorded, but its own install failed (a failed upgrade, say), so it is
1094      // reported in `failed` alone.
1095      continue;
1096    }
1097
1098    if entry.installed_at_time == installed_at_time {
1099      adopted.push(name.clone());
1100    } else {
1101      unchanged.push(name.clone());
1102    }
1103  }
1104
1105  adopted.sort();
1106  adopted.dedup();
1107  unchanged.sort();
1108  unchanged.dedup();
1109  remaining.sort();
1110  remaining.dedup();
1111
1112  if !remaining.is_empty() {
1113    return Ok(AdoptOutcome {
1114      adopted,
1115      unchanged,
1116      remaining,
1117      swept: Vec::new(),
1118      failed,
1119    });
1120  }
1121
1122  let game_profile = eco.require_profile(game)?;
1123  let keep: std::collections::BTreeSet<String> =
1124    recorded.iter().map(|entry| entry.name.clone()).collect();
1125  let swept = crate::install::remove_delisted(game_profile, target_dir, &keep)?;
1126
1127  Ok(AdoptOutcome {
1128    adopted,
1129    unchanged,
1130    remaining,
1131    swept,
1132    failed,
1133  })
1134}
1135
1136/// Refuses a copy whose source is, contains, or sits inside `target`.
1137///
1138/// `fs::copy` opens the destination with `O_TRUNC` before reading the source, so
1139/// copying a file onto itself zeroes it and returns success. Importing a profile
1140/// into itself would therefore empty the game executable, the loader proxy, every
1141/// plugin assembly, and every hand-edited config, and only then fail parsing the
1142/// record it had just zeroed.
1143///
1144/// The two nesting cases are refused for the same reason rather than for being
1145/// merely odd: a source inside the target has its own tree as the copy
1146/// destination, so a repeated directory name copies into the directory being
1147/// read; a source containing the target has the copy walking into its own
1148/// destination, growing a nested tree until the filesystem gives out.
1149///
1150/// Paths are canonicalized before comparison, so a relative spelling or one
1151/// reached through a symlinked directory still compares equal to what it names. A
1152/// path that cannot be resolved is compared as written rather than assumed
1153/// disjoint.
1154#[cfg(feature = "io")]
1155pub fn ensure_disjoint_trees(source: &Path, target: &Path) -> Result<()> {
1156  let source_at = resolve_as_far_as_it_exists(source);
1157  let target_at = resolve_as_far_as_it_exists(target);
1158
1159  if source_at == target_at {
1160    return Err(Error::Profile(format!(
1161      "refusing to copy {} onto itself: every file would be truncated to zero \
1162       bytes",
1163      source.display()
1164    )));
1165  }
1166
1167  if source_at.starts_with(&target_at) {
1168    return Err(Error::Profile(format!(
1169      "refusing to copy {} into {}: the source lives inside the destination, so \
1170       the copy would overwrite the tree it is reading",
1171      source.display(),
1172      target.display()
1173    )));
1174  }
1175
1176  if target_at.starts_with(&source_at) {
1177    return Err(Error::Profile(format!(
1178      "refusing to copy {} into {}: the destination lives inside the source, so \
1179       the copy would recurse into itself",
1180      source.display(),
1181      target.display()
1182    )));
1183  }
1184
1185  Ok(())
1186}
1187
1188/// Canonicalizes as much of `path` as exists, for [`ensure_disjoint_trees`].
1189///
1190/// Tries `path.canonicalize()` first, then [`canonicalize_missing`] for a leaf
1191/// that does not exist yet. Neither is enough on its own for every caller of
1192/// `ensure_disjoint_trees`: `target_dir` is commonly not yet created at all
1193/// when `import_r2modman_dir` calls this, before `copy_tree` has made anything
1194/// under it, so more than one trailing path component can be missing, and
1195/// `canonicalize_missing` only resolves the immediate parent. So when both of
1196/// those fail, this walks up past every missing level in turn, using the
1197/// first ancestor that does canonicalize and rejoining the missing remainder
1198/// onto it. That resolves a symlink anywhere in the existing prefix, not only
1199/// in the immediate parent, which matters here: a symlinked ancestor two or
1200/// more levels above a not-yet-created leaf would otherwise compare as its
1201/// own unresolved spelling and could wrongly look disjoint from a source it
1202/// really nests inside or contains.
1203///
1204/// Falls back to `path` itself, unresolved, if no ancestor down to the path's
1205/// root can be canonicalized (for example a relative path with no existing
1206/// prefix, or a permissions error). That fallback is intentional and matches
1207/// `ensure_disjoint_trees`'s documented behavior: compare something rather
1208/// than assume disjoint.
1209#[cfg(feature = "io")]
1210fn resolve_as_far_as_it_exists(path: &Path) -> PathBuf {
1211  if let Ok(canonical) = path.canonicalize() {
1212    return canonical;
1213  }
1214
1215  if let Ok(canonical) = canonicalize_missing(path) {
1216    return canonical;
1217  }
1218
1219  for ancestor in path.ancestors().skip(1) {
1220    let Ok(canonical_ancestor) = ancestor.canonicalize() else {
1221      continue;
1222    };
1223    let Ok(remainder) = path.strip_prefix(ancestor) else {
1224      continue;
1225    };
1226
1227    return canonical_ancestor.join(remainder);
1228  }
1229
1230  path.to_path_buf()
1231}
1232
1233/// Recursively copies a directory tree, skipping symlinks in `src`.
1234///
1235/// A pre-existing symlink at a file's destination in `dst` is refused rather
1236/// than followed (see `refuse_symlink_dest`), so a planted leaf link cannot
1237/// redirect a copy outside `dst`.
1238#[cfg(feature = "io")]
1239fn copy_tree(src: &Path, dst: &Path) -> Result<()> {
1240  fs::create_dir_all(dst)
1241    .map_err(|e| Error::Profile(format!("creating {}: {}", dst.display(), e)))?;
1242
1243  for entry in
1244    fs::read_dir(src).map_err(|e| Error::Profile(format!("reading {}: {}", src.display(), e)))?
1245  {
1246    let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
1247    let path = entry.path();
1248    let metadata = fs::symlink_metadata(&path)
1249      .map_err(|e| Error::Profile(format!("inspecting {}: {}", path.display(), e)))?;
1250
1251    if metadata.file_type().is_symlink() {
1252      continue;
1253    }
1254
1255    let target = dst.join(entry.file_name());
1256
1257    if metadata.is_dir() {
1258      copy_tree(&path, &target)?;
1259    } else {
1260      refuse_symlink_dest(&target)?;
1261
1262      // A belt-and-braces second line of defence behind `ensure_disjoint_trees`:
1263      // a same-file copy truncates, so it is skipped rather than attempted even
1264      // if a caller reached here another way. Mirrors `stage_one_file`, including
1265      // running after the symlink refusal above, so a symlink planted at the
1266      // destination is still reported as a symlink even in the edge case where it
1267      // happens to resolve back to the source path.
1268      if same_file(&path, &target) {
1269        continue;
1270      }
1271
1272      fs::copy(&path, &target)
1273        .map_err(|e| Error::Profile(format!("copying to {}: {}", target.display(), e)))?;
1274    }
1275  }
1276
1277  Ok(())
1278}
1279
1280/// What an import source string names.
1281///
1282/// A user or a UI hands over one string for "import this", and which of the
1283/// three import routes it means is decided by looking at the filesystem. That
1284/// decision is made here, once, so no caller re-derives it: a caller that wants
1285/// to word the routes differently, or preview what a pasted string would do,
1286/// matches on this instead of stating its own `is_dir`/`is_file` rules.
1287///
1288/// Deliberately **not** `#[non_exhaustive]`, matching
1289/// [`BadProfile`](crate::profile::layout::BadProfile) and
1290/// [`NotRemovable`](crate::profile::NotRemovable): a caller that words each route
1291/// should stop compiling when a fourth appears.
1292#[derive(Debug, Clone, PartialEq, Eq)]
1293pub enum ImportSource {
1294  /// An existing directory, treated as an r2modman profile to adopt in place.
1295  R2modmanDir(PathBuf),
1296  /// An existing file, treated as a `.r2z` export.
1297  Archive(PathBuf),
1298  /// Anything else, treated as a shareable Thunderstore profile code.
1299  Code(String),
1300}
1301
1302#[cfg(feature = "io")]
1303impl ImportSource {
1304  /// Classifies one import source string.
1305  ///
1306  /// A path that exists but is neither a directory nor a regular file (a
1307  /// dangling symlink, a socket) falls through to [`Self::Code`], where the
1308  /// attempt fails naming the code endpoint. `is_dir`/`is_file` follow symlinks,
1309  /// so a link to either is classified as its destination.
1310  pub fn classify(source: &str) -> Self {
1311    let path = Path::new(source);
1312
1313    if path.is_dir() {
1314      return Self::R2modmanDir(path.to_path_buf());
1315    }
1316
1317    if path.is_file() {
1318      return Self::Archive(path.to_path_buf());
1319    }
1320
1321    Self::Code(source.to_string())
1322  }
1323}
1324
1325/// What an import installed, by which route.
1326///
1327/// Carries `source` so a caller can word the outcome per route without
1328/// classifying the source string a second time. Every route keeps the versions
1329/// the source recorded, except a loader an adoption reinstalls at latest; see
1330/// [`Self::reinstalled`].
1331#[derive(Debug)]
1332#[non_exhaustive]
1333pub struct ImportOutcome {
1334  /// How `source` was classified, and therefore which route ran.
1335  pub source: ImportSource,
1336  /// Identifiers this import installed, sorted. Dependencies are included for
1337  /// [`ImportSource::Archive`] and [`ImportSource::Code`]; for
1338  /// [`ImportSource::R2modmanDir`] it is every identifier the copied `mods.yml`
1339  /// names.
1340  pub installed: Vec<String>,
1341  /// Identifiers skipped because the target already recorded the version that
1342  /// would be installed, sorted and never also in `installed`. See
1343  /// [`ImportedMods::unchanged`]. Always empty for
1344  /// [`ImportSource::R2modmanDir`], which copies every file regardless.
1345  pub unchanged: Vec<String>,
1346  /// Identifiers reinstalled at their latest version so they would have an
1347  /// install record. Only ever non-empty for [`ImportSource::R2modmanDir`]; see
1348  /// [`AdoptedProfile::reinstalled`].
1349  pub reinstalled: Vec<String>,
1350}
1351
1352/// Imports whatever `source` names into `target_dir`: an r2modman profile
1353/// directory, a `.r2z` file, or a Thunderstore profile code.
1354///
1355/// The single entry point for "import this string". [`ImportSource::classify`]
1356/// picks the route and the returned [`ImportOutcome`] says which one ran, so a
1357/// caller neither inspects the filesystem itself nor reads the archive to hand
1358/// over its bytes.
1359///
1360/// The package index is fetched only on the routes that need it, so adopting a
1361/// directory that names no unrecorded loader stays fully offline. That is why
1362/// this takes a `client` rather than a prefetched
1363/// [`PackageIndex`](crate::models::PackageIndex), matching
1364/// [`adopt_r2modman_dir_in`].
1365///
1366/// `cache_base` is the package cache root and must not be `target_dir`; see
1367/// [`crate::profile::install_mod_in`].
1368#[cfg(feature = "io")]
1369pub async fn import_in(
1370  target_dir: &Path,
1371  cache_base: &Path,
1372  eco: &crate::ecosystem::Ecosystem,
1373  client: &ThunderstoreClient,
1374  game: &str,
1375  source: &str,
1376  installed_at_time: u64,
1377) -> Result<ImportOutcome> {
1378  let source = ImportSource::classify(source);
1379
1380  if let ImportSource::R2modmanDir(dir) = &source {
1381    let adopted = adopt_r2modman_dir_in(
1382      dir,
1383      target_dir,
1384      cache_base,
1385      eco,
1386      client,
1387      game,
1388      installed_at_time,
1389    )
1390    .await?;
1391    let mut installed = adopted.adopted;
1392
1393    installed.sort();
1394    installed.dedup();
1395
1396    return Ok(ImportOutcome {
1397      source,
1398      installed,
1399      unchanged: Vec::new(),
1400      reinstalled: adopted.reinstalled,
1401    });
1402  }
1403
1404  let index = client.get_manifest().await?;
1405
1406  let imported = match &source {
1407    ImportSource::Archive(path) => {
1408      let bytes =
1409        fs::read(path).map_err(|e| Error::Profile(format!("reading {}: {}", path.display(), e)))?;
1410
1411      import_r2z_in(
1412        target_dir,
1413        cache_base,
1414        eco,
1415        &index,
1416        client,
1417        game,
1418        &bytes,
1419        installed_at_time,
1420      )
1421      .await?
1422    }
1423    ImportSource::Code(code) => {
1424      import_code_in(
1425        target_dir,
1426        cache_base,
1427        eco,
1428        &index,
1429        client,
1430        game,
1431        code,
1432        installed_at_time,
1433      )
1434      .await?
1435    }
1436    // Unreachable: the `if let ImportSource::R2modmanDir(dir)` above returns
1437    // before this match, so the only way here is a variant added to
1438    // `ImportSource` without a corresponding arm, which the compiler catches
1439    // first. Not reachable by any caller input, so it is not a documented panic.
1440    ImportSource::R2modmanDir(_) => {
1441      unreachable!("R2modmanDir returns from the early branch above this match")
1442    }
1443  };
1444
1445  Ok(ImportOutcome {
1446    source,
1447    installed: imported.installed,
1448    unchanged: imported.unchanged,
1449    reinstalled: Vec::new(),
1450  })
1451}
1452
1453/// Imports a `.r2z` into an r2modman-layout profile. See [`import_r2z_in`].
1454#[allow(clippy::too_many_arguments)]
1455#[cfg(feature = "io")]
1456pub async fn import_r2z(
1457  base: &Path,
1458  game: &str,
1459  profile_name: &str,
1460  eco: &crate::ecosystem::Ecosystem,
1461  index: &crate::models::PackageIndex,
1462  client: &ThunderstoreClient,
1463  zip_bytes: &[u8],
1464  installed_at_time: u64,
1465) -> Result<ImportedMods> {
1466  import_r2z_in(
1467    &crate::profile::layout::profile_dir(base, game, profile_name),
1468    base,
1469    eco,
1470    index,
1471    client,
1472    game,
1473    zip_bytes,
1474    installed_at_time,
1475  )
1476  .await
1477}
1478
1479/// Imports a shared profile code into an r2modman-layout profile.
1480/// See [`import_code_in`].
1481#[allow(clippy::too_many_arguments)]
1482#[cfg(feature = "io")]
1483pub async fn import_code(
1484  base: &Path,
1485  game: &str,
1486  profile_name: &str,
1487  eco: &crate::ecosystem::Ecosystem,
1488  index: &crate::models::PackageIndex,
1489  client: &ThunderstoreClient,
1490  code: &str,
1491  installed_at_time: u64,
1492) -> Result<ImportedMods> {
1493  import_code_in(
1494    &crate::profile::layout::profile_dir(base, game, profile_name),
1495    base,
1496    eco,
1497    index,
1498    client,
1499    game,
1500    code,
1501    installed_at_time,
1502  )
1503  .await
1504}
1505
1506#[cfg(all(test, feature = "io"))]
1507mod tests {
1508  use super::*;
1509
1510  fn profile_mod(name: &str, enabled: bool) -> ProfileMod {
1511    let mut entry = crate::profile::mod_entry_from_version(name, "Author", &sample_version(), 1);
1512    entry.enabled = enabled;
1513
1514    entry
1515  }
1516
1517  fn sample_version() -> crate::models::Version {
1518    // Built through the index so no `#[non_exhaustive]` literal is needed here.
1519    let json = r#"{"name":"Mod","full_name":"Author-Mod","description":"d","icon":"i",
1520      "version_number":"1.2.3","dependencies":[],"download_url":"u","downloads":1,
1521      "date_created":"2024-01-01T12:00:00Z","website_url":"w","is_active":true,
1522      "uuid4":"u","file_size":1}"#;
1523
1524    serde_json::from_str(json).unwrap()
1525  }
1526
1527  #[test]
1528  fn import_source_classifies_a_directory_a_file_and_a_code() {
1529    let dir = tempfile::tempdir().unwrap();
1530    let profile = dir.path().join("SomeProfile");
1531    let archive = dir.path().join("export.r2z");
1532
1533    std::fs::create_dir_all(&profile).unwrap();
1534    write_test_file(&archive, b"not really a zip");
1535
1536    assert!(matches!(
1537      ImportSource::classify(profile.to_str().unwrap()),
1538      ImportSource::R2modmanDir(path) if path == profile
1539    ));
1540    assert!(matches!(
1541      ImportSource::classify(archive.to_str().unwrap()),
1542      ImportSource::Archive(path) if path == archive
1543    ));
1544
1545    // Anything that is not on disk is a Thunderstore profile code. A
1546    // path-shaped string that does not exist counts too: there is nothing to
1547    // read, and the code endpoint is the only remaining thing it could name.
1548    assert!(matches!(
1549      ImportSource::classify("abc123-def456"),
1550      ImportSource::Code(code) if code == "abc123-def456"
1551    ));
1552    assert!(matches!(
1553      ImportSource::classify("/no/such/path.r2z"),
1554      ImportSource::Code(_)
1555    ));
1556  }
1557
1558  #[test]
1559  fn export_format_maps_mods_and_preserves_enabled() {
1560    let mods = vec![
1561      profile_mod("Author-A", true),
1562      profile_mod("Author-B", false),
1563    ];
1564
1565    let export = export_format_from_mods("MyProfile", &mods);
1566
1567    assert_eq!(export.profile_name, "MyProfile");
1568    assert_eq!(export.mods.len(), 2);
1569    assert_eq!(export.mods[0].name, "Author-A");
1570    assert_eq!(
1571      export.mods[0].version,
1572      SemVer {
1573        major: 1,
1574        minor: 2,
1575        patch: 3
1576      }
1577    );
1578    assert!(export.mods[0].enabled);
1579    assert!(!export.mods[1].enabled);
1580  }
1581
1582  #[test]
1583  fn serialized_r2x_uses_version_not_version_number() {
1584    let mods = vec![profile_mod("Author-A", true)];
1585    let yaml = export_r2x_to_string(&export_format_from_mods("MyProfile", &mods)).unwrap();
1586
1587    assert!(yaml.contains("profileName: MyProfile"));
1588    assert!(yaml.contains("name: Author-A"));
1589    assert!(yaml.contains("version:"));
1590    assert!(yaml.contains("major: 1"));
1591    // `mods.yml` uses `versionNumber`; `export.r2x` must NOT.
1592    assert!(!yaml.contains("versionNumber"));
1593  }
1594
1595  #[test]
1596  fn parses_real_r2x_and_defaults_missing_enabled_to_true() {
1597    let yaml = r#"profileName: Shared
1598mods:
1599  - name: Author-A
1600    version:
1601      major: 2
1602      minor: 0
1603      patch: 1
1604    enabled: false
1605  - name: Author-B
1606    version:
1607      major: 1
1608      minor: 0
1609      patch: 0
1610"#;
1611
1612    let export = parse_export_r2x(yaml).unwrap();
1613
1614    assert_eq!(export.profile_name, "Shared");
1615    assert_eq!(export.mods.len(), 2);
1616    assert!(!export.mods[0].enabled);
1617    // r2modman treats an absent `enabled` as true.
1618    assert!(export.mods[1].enabled);
1619  }
1620
1621  #[test]
1622  fn parse_export_r2x_rejects_malformed() {
1623    assert!(parse_export_r2x("not: a valid export").is_err());
1624  }
1625
1626  fn write_test_file(path: &Path, bytes: &[u8]) {
1627    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1628    std::fs::write(path, bytes).unwrap();
1629  }
1630
1631  #[test]
1632  fn is_pruned_matches_r2modman_rules() {
1633    // Dropped.
1634    assert!(is_pruned(Path::new("dotnet/x.json")));
1635    assert!(is_pruned(Path::new("_state/Author-Mod-state.yml")));
1636    assert!(is_pruned(Path::new("BepInEx/config/BepInEx.cfg")));
1637    assert!(is_pruned(Path::new(
1638      "BepInEx/plugins/Author-Mod/manifest.json"
1639    )));
1640    assert!(is_pruned(Path::new("MelonLoader/x.cfg")));
1641    assert!(is_pruned(Path::new("GDWeave/core/a.json")));
1642    assert!(is_pruned(Path::new("GDWeave/mods/b.json")));
1643    assert!(is_pruned(Path::new("GDWeave/GDWeave.log")));
1644    assert!(is_pruned(Path::new("mods.yml")));
1645
1646    // Kept.
1647    assert!(!is_pruned(Path::new(
1648      "BepInEx/plugins/Author-Mod/settings.cfg"
1649    )));
1650    assert!(!is_pruned(Path::new("GDWeave/other.json")));
1651    assert!(!is_pruned(Path::new("notes.txt")));
1652  }
1653
1654  #[test]
1655  fn is_config_file_matches_supported_extensions() {
1656    assert!(is_config_file(Path::new("a/b.cfg")));
1657    assert!(is_config_file(Path::new("a/b.YAML")));
1658    assert!(is_config_file(Path::new("b.ini")));
1659    assert!(!is_config_file(Path::new("a/b.dll")));
1660    assert!(!is_config_file(Path::new("a/b")));
1661  }
1662
1663  #[test]
1664  fn collect_export_paths_selects_configs_and_skips_pruned() {
1665    let dir = tempfile::tempdir().unwrap();
1666    let root = dir.path();
1667
1668    write_test_file(&root.join("mods.yml"), b"[]");
1669    write_test_file(&root.join("BepInEx/config/BepInEx.cfg"), b"cfg");
1670    write_test_file(&root.join("BepInEx/plugins/Author-Mod/settings.cfg"), b"s");
1671    write_test_file(
1672      &root.join("BepInEx/plugins/Author-Mod/manifest.json"),
1673      b"{}",
1674    );
1675    write_test_file(&root.join("BepInEx/plugins/Author-Mod/Mod.dll"), b"dll");
1676    write_test_file(&root.join("_state/Author-Mod-state.yml"), b"x");
1677
1678    let paths = collect_export_paths(root).unwrap();
1679    let as_str: Vec<String> = paths
1680      .iter()
1681      .map(|p| p.to_string_lossy().replace('\\', "/"))
1682      .collect();
1683
1684    assert_eq!(
1685      as_str,
1686      vec!["BepInEx/plugins/Author-Mod/settings.cfg".to_string()]
1687    );
1688  }
1689
1690  #[test]
1691  fn build_r2z_contains_manifest_and_configs() {
1692    let dir = tempfile::tempdir().unwrap();
1693    let root = dir.path();
1694
1695    crate::profile::modlist::write(root, &[profile_mod("Author-A", true)]).unwrap();
1696    write_test_file(&root.join("BepInEx/config/BepInEx.cfg"), b"shared");
1697    write_test_file(&root.join("BepInEx/plugins/Author-A/settings.cfg"), b"mine");
1698    write_test_file(&root.join("BepInEx/plugins/Author-A/Mod.dll"), b"dll");
1699
1700    let bytes = build_r2z_in(root, "MyProfile").unwrap();
1701
1702    let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
1703    let names: Vec<String> = (0..zip.len())
1704      .map(|i| zip.by_index(i).unwrap().name().replace('\\', "/"))
1705      .collect();
1706
1707    assert!(names.contains(&"export.r2x".to_string()));
1708    // BepInEx/config/ is re-rooted under config/ in the archive.
1709    assert!(names.contains(&"config/BepInEx.cfg".to_string()));
1710    // Other config files keep their target-relative path.
1711    assert!(names.contains(&"BepInEx/plugins/Author-A/settings.cfg".to_string()));
1712    // Binaries and mods.yml are never exported.
1713    assert!(!names.iter().any(|n| n.ends_with("Mod.dll")));
1714    assert!(!names.contains(&"mods.yml".to_string()));
1715
1716    let mut manifest = String::new();
1717    std::io::Read::read_to_string(&mut zip.by_name("export.r2x").unwrap(), &mut manifest).unwrap();
1718
1719    let export = parse_export_r2x(&manifest).unwrap();
1720
1721    assert_eq!(export.profile_name, "MyProfile");
1722    assert_eq!(export.mods[0].name, "Author-A");
1723  }
1724
1725  #[test]
1726  fn export_to_file_uses_name_and_timestamp() {
1727    let dir = tempfile::tempdir().unwrap();
1728    let root = dir.path().join("profile");
1729    let out = dir.path().join("exports");
1730
1731    crate::profile::modlist::write(&root, &[profile_mod("Author-A", true)]).unwrap();
1732
1733    let path = export_to_file_in(&root, "MyProfile", &out, 1_700_000_000_000).unwrap();
1734
1735    assert_eq!(
1736      path.file_name().unwrap().to_string_lossy(),
1737      "MyProfile_1700000000000.r2z"
1738    );
1739    assert!(path.exists());
1740  }
1741
1742  #[test]
1743  fn export_to_file_rejects_unsafe_profile_name() {
1744    let dir = tempfile::tempdir().unwrap();
1745    let root = dir.path().join("profile");
1746    let out = dir.path().join("exports");
1747
1748    crate::profile::modlist::write(&root, &[profile_mod("Author-A", true)]).unwrap();
1749
1750    assert!(export_to_file_in(&root, "../evil", &out, 1).is_err());
1751    assert!(!dir.path().join("evil_1.r2z").exists());
1752  }
1753
1754  #[test]
1755  #[cfg(unix)]
1756  fn export_to_file_accepts_a_profile_named_under_the_old_rules() {
1757    let dir = tempfile::tempdir().unwrap();
1758    let root = dir.path().join("profile");
1759    let out = dir.path().join("exports");
1760
1761    crate::profile::modlist::write(&root, &[profile_mod("Author-A", true)]).unwrap();
1762
1763    let path = export_to_file_in(&root, "v2: test", &out, 1).unwrap();
1764
1765    assert_eq!(path, out.join("v2: test_1.r2z"));
1766  }
1767
1768  #[test]
1769  fn encode_profile_payload_prefixes_and_base64s() {
1770    let payload = encode_profile_payload(b"ABC").unwrap();
1771
1772    assert_eq!(payload, b"#r2modman\nQUJD");
1773  }
1774
1775  #[test]
1776  fn encode_profile_payload_rejects_oversize() {
1777    let big = vec![0u8; MAX_EXPORT_CODE_BYTES + 1];
1778
1779    assert!(matches!(
1780      encode_profile_payload(&big),
1781      Err(Error::SizeLimitExceeded { .. })
1782    ));
1783  }
1784
1785  #[test]
1786  fn decode_profile_payload_round_trips_and_rejects_bad_prefix() {
1787    let payload = encode_profile_payload(b"ABC").unwrap();
1788
1789    assert_eq!(decode_profile_payload(&payload).unwrap(), b"ABC");
1790    assert!(decode_profile_payload(b"nope\nQUJD").is_err());
1791  }
1792
1793  #[test]
1794  fn import_config_key_remaps_config_and_blocks_unsafe() {
1795    // `config/` is re-rooted back under BepInEx/.
1796    assert_eq!(
1797      import_config_key("config/BepInEx.cfg"),
1798      Some(PathBuf::from("BepInEx/config/BepInEx.cfg"))
1799    );
1800    // Other entries keep their path.
1801    assert_eq!(
1802      import_config_key("BepInEx/plugins/Author-A/settings.cfg"),
1803      Some(PathBuf::from("BepInEx/plugins/Author-A/settings.cfg"))
1804    );
1805    // Manifest and manager state are skipped.
1806    assert_eq!(import_config_key("export.r2x"), None);
1807    assert_eq!(import_config_key("mods.yml"), None);
1808    assert_eq!(import_config_key("_state/Author-Mod-state.yml"), None);
1809    assert_eq!(import_config_key("./_STATE /Author-Mod-state.yml"), None);
1810    // Executables are refused even inside an otherwise valid path.
1811    assert_eq!(import_config_key("BepInEx/plugins/evil.dll"), None);
1812    // Traversal is refused.
1813    assert_eq!(import_config_key("../escape.cfg"), None);
1814  }
1815
1816  #[test]
1817  fn import_config_key_blocks_trailing_dot_and_space_bypass() {
1818    // Windows strips trailing dots/spaces from the final path component on
1819    // create, so these must be blocked even though they don't literally end
1820    // with a blocked extension.
1821    let blocked = [
1822      "evil.dll.",
1823      "evil.dll ",
1824      "evil.dll. . ",
1825      "evil.DLL",
1826      "evil.cfg.dll",
1827    ];
1828
1829    for name in blocked {
1830      assert_eq!(
1831        import_config_key(name),
1832        None,
1833        "{name} should have been blocked"
1834      );
1835    }
1836
1837    // An ordinary config entry is unaffected.
1838    assert_eq!(import_config_key("a.cfg"), Some(PathBuf::from("a.cfg")));
1839  }
1840
1841  /// A drive prefix only parses as one on Windows, so that is the only host
1842  /// where the guard can be seen to catch it.
1843  #[test]
1844  #[cfg(windows)]
1845  fn import_config_key_refuses_a_drive_prefix() {
1846    assert_eq!(import_config_key(r"C:\Windows\evil.cfg"), None);
1847    assert_eq!(import_config_key("C:evil.cfg"), None);
1848    assert_eq!(import_config_key(r"\\server\share\evil.cfg"), None);
1849  }
1850
1851  #[test]
1852  fn read_export_accepts_r2z_and_bare_r2x() {
1853    let dir = tempfile::tempdir().unwrap();
1854    let root = dir.path();
1855
1856    crate::profile::modlist::write(root, &[profile_mod("Author-A", true)]).unwrap();
1857
1858    let zip_bytes = build_r2z_in(root, "MyProfile").unwrap();
1859
1860    assert_eq!(read_export(&zip_bytes).unwrap().profile_name, "MyProfile");
1861
1862    let yaml = export_r2x_to_string(&export_format_from_mods("Bare", &[])).unwrap();
1863
1864    assert_eq!(read_export(yaml.as_bytes()).unwrap().profile_name, "Bare");
1865  }
1866
1867  #[test]
1868  fn extract_configs_writes_remapped_files_only() {
1869    let dir = tempfile::tempdir().unwrap();
1870    let source = dir.path().join("source");
1871    let target = dir.path().join("target");
1872
1873    crate::profile::modlist::write(&source, &[profile_mod("Author-A", true)]).unwrap();
1874    write_test_file(&source.join("BepInEx/config/BepInEx.cfg"), b"shared");
1875    write_test_file(
1876      &source.join("BepInEx/plugins/Author-A/settings.cfg"),
1877      b"mine",
1878    );
1879
1880    let zip_bytes = build_r2z_in(&source, "MyProfile").unwrap();
1881    let written = extract_configs_in(&target, &zip_bytes).unwrap();
1882
1883    assert!(target.join("BepInEx/config/BepInEx.cfg").exists());
1884    assert!(
1885      target
1886        .join("BepInEx/plugins/Author-A/settings.cfg")
1887        .exists()
1888    );
1889    // The manifest itself is never written into the target.
1890    assert!(!target.join("export.r2x").exists());
1891    assert_eq!(written.len(), 2);
1892  }
1893
1894  #[test]
1895  fn extract_configs_treats_non_zip_input_as_no_configs() {
1896    let dir = tempfile::tempdir().unwrap();
1897    let target = dir.path().join("target");
1898
1899    // A bare `.r2x` manifest — no zip container at all.
1900    let yaml = export_r2x_to_string(&export_format_from_mods("Bare", &[])).unwrap();
1901
1902    let written = extract_configs_in(&target, yaml.as_bytes()).unwrap();
1903
1904    assert!(written.is_empty());
1905  }
1906
1907  #[test]
1908  fn extract_configs_still_rejects_a_genuinely_corrupt_zip() {
1909    let dir = tempfile::tempdir().unwrap();
1910    let target = dir.path().join("target");
1911
1912    // Looks like a zip (starts with the `PK` magic) but is truncated garbage.
1913    let corrupt = b"PK\x03\x04not a real zip".to_vec();
1914
1915    assert!(extract_configs_in(&target, &corrupt).is_err());
1916  }
1917
1918  #[test]
1919  #[cfg(unix)]
1920  fn extract_configs_refuses_to_write_through_a_symlink() {
1921    use std::os::unix::fs::symlink;
1922
1923    let outside = tempfile::tempdir().unwrap();
1924    let secret = outside.path().join("secret.cfg");
1925    std::fs::write(&secret, b"original").unwrap();
1926
1927    let source = tempfile::tempdir().unwrap();
1928
1929    crate::profile::modlist::write(source.path(), &[profile_mod("Author-A", true)]).unwrap();
1930    write_test_file(
1931      &source.path().join("BepInEx/config/BepInEx.cfg"),
1932      b"new-content",
1933    );
1934
1935    let zip_bytes = build_r2z_in(source.path(), "MyProfile").unwrap();
1936
1937    // Plant a symlink at the destination the archive's `config/BepInEx.cfg`
1938    // entry remaps to, pointing outside the target.
1939    let target = tempfile::tempdir().unwrap();
1940    let dest = target.path().join("BepInEx/config/BepInEx.cfg");
1941
1942    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
1943    symlink(&secret, &dest).unwrap();
1944
1945    let err = extract_configs_in(target.path(), &zip_bytes).unwrap_err();
1946
1947    assert!(matches!(err, Error::Profile(_)));
1948    // The write is refused and the symlink target outside the target dir is untouched.
1949    assert_eq!(std::fs::read_to_string(&secret).unwrap(), "original");
1950  }
1951
1952  /// Builds an in-memory zip with a single highly-compressible entry, so the
1953  /// archive itself stays tiny while its inflated content can dwarf the caps.
1954  fn zip_with_one_zero_filled_entry(name: &str, inflated_len: usize) -> Vec<u8> {
1955    let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
1956    let options: FileOptions<'_, ()> =
1957      FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
1958
1959    zip.start_file(name, options).unwrap();
1960    zip.write_all(&vec![0u8; inflated_len]).unwrap();
1961
1962    zip.finish().unwrap().into_inner()
1963  }
1964
1965  #[test]
1966  fn extract_configs_rejects_entry_exceeding_the_per_entry_cap() {
1967    let bytes = zip_with_one_zero_filled_entry(
1968      "BepInEx/config/Big.cfg",
1969      (MAX_IMPORT_ENTRY_BYTES + 1) as usize,
1970    );
1971
1972    let dir = tempfile::tempdir().unwrap();
1973    let err = extract_configs_in(dir.path(), &bytes).unwrap_err();
1974
1975    assert!(matches!(err, Error::ExtractLimitExceeded(_)));
1976  }
1977
1978  #[test]
1979  fn extract_configs_rejects_import_exceeding_the_cumulative_cap() {
1980    // Each entry sits just under the per-entry cap individually, but enough of
1981    // them together must exceed the cumulative cap.
1982    let per_entry_len = (MAX_IMPORT_ENTRY_BYTES - 1024) as usize;
1983    let entries_needed = (MAX_IMPORT_TOTAL_BYTES / per_entry_len as u64) + 1;
1984
1985    let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
1986    let options: FileOptions<'_, ()> =
1987      FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
1988    let chunk = vec![0u8; per_entry_len];
1989
1990    for i in 0..entries_needed {
1991      zip
1992        .start_file(format!("BepInEx/config/{i}.cfg"), options)
1993        .unwrap();
1994      zip.write_all(&chunk).unwrap();
1995    }
1996
1997    let bytes = zip.finish().unwrap().into_inner();
1998
1999    let dir = tempfile::tempdir().unwrap();
2000    let err = extract_configs_in(dir.path(), &bytes).unwrap_err();
2001
2002    assert!(matches!(err, Error::ExtractLimitExceeded(_)));
2003  }
2004
2005  #[test]
2006  fn import_r2modman_dir_adopts_an_existing_profile() {
2007    let dir = tempfile::tempdir().unwrap();
2008    let source = dir.path().join("source");
2009    let target = dir.path().join("target");
2010
2011    crate::profile::modlist::write(&source, &[profile_mod("Author-A", true)]).unwrap();
2012    write_test_file(&source.join("BepInEx/plugins/Author-A/Mod.dll"), b"dll");
2013
2014    import_r2modman_dir(&source, &target).unwrap();
2015
2016    assert!(target.join("BepInEx/plugins/Author-A/Mod.dll").exists());
2017    assert_eq!(crate::profile::modlist::read(&target).unwrap().len(), 1);
2018    assert!(import_r2modman_dir(&dir.path().join("missing"), &target).is_err());
2019  }
2020
2021  #[test]
2022  #[cfg(unix)]
2023  fn import_r2modman_dir_refuses_to_copy_through_a_symlink() {
2024    use std::os::unix::fs::symlink;
2025
2026    let outside = tempfile::tempdir().unwrap();
2027    let secret = outside.path().join("secret.cfg");
2028    std::fs::write(&secret, b"original").unwrap();
2029
2030    let dir = tempfile::tempdir().unwrap();
2031    let source = dir.path().join("source");
2032    let target = dir.path().join("target");
2033
2034    crate::profile::modlist::write(&source, &[profile_mod("Author-A", true)]).unwrap();
2035    write_test_file(
2036      &source.join("BepInEx/plugins/Author-A/settings.cfg"),
2037      b"new-content",
2038    );
2039
2040    // Plant a symlink at the destination the source's config file would copy to.
2041    let dest = target.join("BepInEx/plugins/Author-A/settings.cfg");
2042
2043    std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
2044    symlink(&secret, &dest).unwrap();
2045
2046    let err = import_r2modman_dir(&source, &target).unwrap_err();
2047
2048    assert!(matches!(err, Error::Profile(_)));
2049    // The copy is refused and the symlink target outside the target dir is untouched.
2050    assert_eq!(std::fs::read_to_string(&secret).unwrap(), "original");
2051  }
2052
2053  #[test]
2054  fn copy_tree_skips_a_same_file_copy_instead_of_truncating_it() {
2055    let dir = tempfile::tempdir().unwrap();
2056    let root = dir.path();
2057
2058    write_test_file(&root.join("sub/file.txt"), b"original bytes");
2059
2060    // `ensure_disjoint_trees` refuses an overlapping source and target on
2061    // every public path (see `importing_a_directory_into_itself_is_refused_before_anything_is_truncated`
2062    // in the integration suite), so `copy_tree`'s own `same_file` skip is
2063    // otherwise never reached there. Calling it directly, the way a future
2064    // caller reaching `copy_tree` another way might, is the only way to
2065    // exercise this second line of defence.
2066    copy_tree(root, root).unwrap();
2067
2068    let bytes = std::fs::read(root.join("sub/file.txt")).unwrap();
2069
2070    assert_eq!(
2071      bytes, b"original bytes",
2072      "a same-file copy must be skipped, not truncate the file to zero bytes"
2073    );
2074  }
2075}