mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-29 01:34:37 +01:00
Merge pull request #2587 from storytold/formats/penpot-craft-zip-9-8-2
Read Penpot archives through craft-zip
This commit is contained in:
13 files changed
+153
-135
No files matched your search
Generated
+34
-55
@@ -274,15 +274,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
dependencies = [
|
||||
"derive_arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arboard"
|
||||
version = "3.7.0"
|
||||
@@ -1039,6 +1030,15 @@ version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"
|
||||
dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cookie-factory"
|
||||
version = "0.3.3"
|
||||
@@ -1327,7 +1327,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1879,7 +1879,7 @@ dependencies = [
|
||||
"verifysign",
|
||||
"winreg",
|
||||
"winsafe",
|
||||
"zip 9.1.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1962,7 +1962,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259e
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"thiserror 2.0.21",
|
||||
"zip 9.1.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2099,17 +2099,6 @@ version = "0.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
|
||||
|
||||
[[package]]
|
||||
name = "derive_arbitrary"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deunicode"
|
||||
version = "1.6.2"
|
||||
@@ -2780,7 +2769,7 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
"wat",
|
||||
"web-time",
|
||||
"zip 2.6.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2809,7 +2798,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"zip 2.6.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2927,7 +2916,7 @@ dependencies = [
|
||||
"toml",
|
||||
"tungstenite",
|
||||
"wat",
|
||||
"zip 2.6.1",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8704,6 +8693,20 @@ name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
dependencies = [
|
||||
"zeroize_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize_derive"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
@@ -8744,33 +8747,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "2.6.1"
|
||||
version = "9.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"crossbeam-utils",
|
||||
"flate2",
|
||||
"indexmap",
|
||||
"memchr",
|
||||
"zopfli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4"
|
||||
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
|
||||
dependencies = [
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
"indexmap",
|
||||
"libc",
|
||||
"memchr",
|
||||
"nix",
|
||||
"typed-path",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8785,18 +8776,6 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||
|
||||
[[package]]
|
||||
name = "zopfli"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"crc32fast",
|
||||
"log",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zune-core"
|
||||
version = "0.5.3"
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@ icu_segmenter = { version = "2.3", default-features = false, features = ["compil
|
||||
# dependencies, BSD-3-Clause, no_std so the web build keeps it too).
|
||||
deunicode = "1.6"
|
||||
linesweeper = "0.5"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] }
|
||||
# `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe).
|
||||
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
||||
ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
|
||||
|
||||
@@ -47,7 +47,7 @@ pub(crate) fn archive(bomb: usize, padding: usize) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..src.len() {
|
||||
let f = src.by_index_raw(i).unwrap();
|
||||
if bomb > 0 && f.name() == "library/document.json" {
|
||||
if bomb > 0 && f.name().expect("ZIP member name") == "library/document.json" {
|
||||
continue;
|
||||
}
|
||||
out.raw_copy_file(f).unwrap();
|
||||
|
||||
@@ -20,11 +20,11 @@ fn jam_file(tag: &str) -> std::path::PathBuf {
|
||||
let mut member = from.by_index(i).unwrap();
|
||||
let mut bytes = Vec::new();
|
||||
member.read_to_end(&mut bytes).unwrap();
|
||||
if member.name() == "canvas.fig" {
|
||||
if member.name().expect("ZIP member name") == "canvas.fig" {
|
||||
assert!(bytes.starts_with(b"fig-kiwi"));
|
||||
bytes.splice(..8, *b"fig-jam.");
|
||||
}
|
||||
to.start_file(member.name(), zip::write::SimpleFileOptions::default()).unwrap();
|
||||
to.start_file(member.name().expect("ZIP member name"), zip::write::SimpleFileOptions::default()).unwrap();
|
||||
to.write_all(&bytes).unwrap();
|
||||
}
|
||||
let path = std::env::temp_dir().join(format!("figcraft-jam-{tag}-{}.jam", std::process::id()));
|
||||
|
||||
@@ -14,7 +14,6 @@ figcraft-pathops = { workspace = true }
|
||||
figcraft-layout = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
ruzstd = { workspace = true }
|
||||
sha1 = { workspace = true }
|
||||
@@ -32,3 +31,6 @@ craft-raw = { workspace = true }
|
||||
craft-develop = { workspace = true }
|
||||
craft-color-transform = { workspace = true }
|
||||
craft-geom = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
zip = { workspace = true }
|
||||
@@ -1380,7 +1380,8 @@ fn images_are_named_by_the_sha1_of_their_bytes() {
|
||||
assert_eq!(export::sha1_hex(&vec![b'a'; 1_000_000]), "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
|
||||
let (bytes, _) = export(&generate(3), None).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
|
||||
let names: Vec<String> = z.file_names().filter(|n| n.starts_with("images/")).map(str::to_string).collect();
|
||||
let names: Vec<String> =
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).filter(|n| n.starts_with("images/")).map(std::borrow::Cow::into_owned).collect();
|
||||
assert!(!names.is_empty());
|
||||
for name in names {
|
||||
let data = crate::read_member(&mut z, &name, 1 << 26).unwrap();
|
||||
|
||||
@@ -364,7 +364,7 @@ fn mask_types_round_trip() {
|
||||
fn the_archive_lists_its_members_and_describes_the_file() {
|
||||
let (bytes, _) = export(&sample(), Some(&super::tests::png())).unwrap();
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes[..])).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().expect("ZIP member name").into_owned()).collect();
|
||||
assert_eq!(names, ["canvas.fig", "thumbnail.png", "meta.json"]);
|
||||
let meta: serde_json::Value = serde_json::from_slice(&crate::read_member(&mut z, "meta.json", 1 << 20).unwrap()).unwrap();
|
||||
assert_eq!(meta["file_name"], "Interop");
|
||||
|
||||
@@ -31,7 +31,7 @@ fn file_with_images(n: u8) -> (Vec<u8>, Vec<String>, u64) {
|
||||
/// `bytes` with one more member, `name` holding `data`.
|
||||
fn with_member(bytes: &[u8], name: &str, data: &[u8]) -> Vec<u8> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = z.file_names().map(str::to_string).collect();
|
||||
let names: Vec<String> = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect();
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
let mut w = zip::ZipWriter::new(&mut buf);
|
||||
let stored = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
|
||||
@@ -25,7 +25,7 @@ fn doc_with_image() -> (Document, String) {
|
||||
/// The archive of `d` rebuilt with `edit` applied to each member (None drops it).
|
||||
fn rebuild(bytes: &[u8], edit: impl Fn(&str, Vec<u8>) -> Option<Vec<u8>>) -> Vec<u8> {
|
||||
let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = z.file_names().map(str::to_string).collect();
|
||||
let names: Vec<String> = z.file_names().map(|name| name.expect("ZIP member name")).map(std::borrow::Cow::into_owned).collect();
|
||||
let mut buf = std::io::Cursor::new(Vec::new());
|
||||
let mut w = zip::ZipWriter::new(&mut buf);
|
||||
for n in names {
|
||||
@@ -109,7 +109,11 @@ fn image_members_with_path_like_names_are_dropped_and_not_saved_back() {
|
||||
assert!(!loaded.issues.is_empty());
|
||||
let saved = save_bytes_with_history(&loaded.doc, None, &loaded.versions, &loaded.branches).unwrap();
|
||||
let z = zip::ZipArchive::new(std::io::Cursor::new(saved)).unwrap();
|
||||
assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::<Vec<_>>());
|
||||
assert!(
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1),
|
||||
"{:?}",
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).collect::<Vec<_>>()
|
||||
);
|
||||
let _ = hash;
|
||||
}
|
||||
|
||||
@@ -128,11 +132,15 @@ fn a_path_like_rest_image_ref_never_names_an_archive_member() {
|
||||
assert!(doc.images.contains_key("rest-image-missing"), "the shared placeholder stores it instead: {:?}", doc.images.keys().collect::<Vec<_>>());
|
||||
let bytes = save_bytes(&doc, None).unwrap();
|
||||
let z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
assert!(z.file_names().all(|n| !n.contains("..") && n.matches('/').count() <= 1), "{:?}", z.file_names().collect::<Vec<_>>());
|
||||
assert!(
|
||||
z.file_names().any(|n| n == "images/rest-image-missing"),
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).all(|n| !n.contains("..") && n.matches('/').count() <= 1),
|
||||
"{:?}",
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).collect::<Vec<_>>()
|
||||
);
|
||||
assert!(
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).any(|n| n == "images/rest-image-missing"),
|
||||
"the placeholder is saved under its own name: {:?}",
|
||||
z.file_names().collect::<Vec<_>>()
|
||||
z.file_names().map(|name| name.expect("ZIP member name")).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ fn replace_member(zip_bytes: &[u8], name: &str, bytes: Option<&[u8]>) -> Vec<u8>
|
||||
let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
|
||||
for i in 0..src.len() {
|
||||
let mut f = src.by_index(i).unwrap();
|
||||
let n = f.name().to_string();
|
||||
let n = f.name().expect("ZIP member name").to_string();
|
||||
let mut data = Vec::new();
|
||||
f.read_to_end(&mut data).unwrap();
|
||||
let data = if n == name { bytes.map(<[u8]>::to_vec) } else { Some(data) };
|
||||
|
||||
+83
-54
@@ -8,6 +8,8 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::{self, Cursor, Read};
|
||||
|
||||
use crate::{FormatError, add_image};
|
||||
use craft_zip::{SeekableArchive, SeekableLimits};
|
||||
use figcraft_doc::color::{BlendMode, Color, ColorStop, Gradient, GradientKind, ImageScaleMode, Paint, PaintKind};
|
||||
use figcraft_doc::geom::{Affine, BezPath, Shape};
|
||||
use figcraft_doc::{
|
||||
@@ -17,9 +19,8 @@ use figcraft_doc::{
|
||||
Variable, VariableType, VariableValue, VectorNetwork,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use zip::ZipArchive;
|
||||
|
||||
use crate::{FormatError, add_image};
|
||||
type PenpotArchive<'a> = SeekableArchive<Cursor<&'a [u8]>>;
|
||||
|
||||
mod embedded_fonts;
|
||||
mod export;
|
||||
@@ -135,11 +136,12 @@ impl<R: Read> Read for BudgetReader<'_, R> {
|
||||
}
|
||||
|
||||
/// Read a JSON archive member within the per-member decompression limit.
|
||||
fn json(z: &mut ZipArchive<Cursor<&[u8]>>, path: &str, budget: &mut InflateBudget) -> Result<Value, FormatError> {
|
||||
let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?;
|
||||
if entry.size() > MAX_JSON {
|
||||
fn json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget) -> Result<Value, FormatError> {
|
||||
let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
|
||||
if declared > MAX_JSON {
|
||||
return Err(corrupt(format!("JSON member too large: {path}")));
|
||||
}
|
||||
let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
|
||||
let mut data = Vec::new();
|
||||
BudgetReader { inner: entry, budget }.take(MAX_JSON + 1).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?;
|
||||
if data.len() as u64 > MAX_JSON {
|
||||
@@ -149,14 +151,15 @@ fn json(z: &mut ZipArchive<Cursor<&[u8]>>, path: &str, budget: &mut InflateBudge
|
||||
}
|
||||
|
||||
/// Read a shape JSON member within member and per-page decompression limits.
|
||||
fn shape_json(z: &mut ZipArchive<Cursor<&[u8]>>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result<Value, FormatError> {
|
||||
let entry = z.by_name(path).map_err(|e| corrupt(format!("{path}: {e}")))?;
|
||||
if entry.size() > MAX_JSON {
|
||||
fn shape_json(z: &mut PenpotArchive<'_>, path: &str, budget: &mut InflateBudget, page_budget: &mut u64) -> Result<Value, FormatError> {
|
||||
let declared = z.declared_size(path).ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
|
||||
if declared > MAX_JSON {
|
||||
return Err(corrupt(format!("JSON member too large: {path}")));
|
||||
}
|
||||
if entry.size() > *page_budget {
|
||||
if declared > *page_budget {
|
||||
return Err(corrupt("page shapes exceed byte budget"));
|
||||
}
|
||||
let entry = z.open_entry(path, MAX_JSON).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt(format!("{path}: missing ZIP member")))?;
|
||||
let mut data = Vec::new();
|
||||
let max_read = (MAX_JSON + 1).min(*page_budget + 1);
|
||||
BudgetReader { inner: entry, budget }.take(max_read).read_to_end(&mut data).map_err(|e| corrupt(e.to_string()))?;
|
||||
@@ -360,29 +363,35 @@ fn finish_masked_group(doc: &mut Document, group: NodeId, source: &Value, warnin
|
||||
}
|
||||
}
|
||||
|
||||
fn open_archive(bytes: &[u8]) -> Result<PenpotArchive<'_>, FormatError> {
|
||||
let limits = SeekableLimits {
|
||||
max_entries: MAX_ENTRIES as u64,
|
||||
max_metadata_bytes: MAX_ARCHIVE as u64,
|
||||
// The Penpot budget also charges partial reads (embedded font signatures) and
|
||||
// remembers an overflow that an optional-member caller might otherwise swallow.
|
||||
max_total_bytes: u64::MAX,
|
||||
};
|
||||
let z = SeekableArchive::open(Cursor::new(bytes), limits).map_err(|e| match e {
|
||||
craft_zip::Error::TooManyEntries { .. } => corrupt("too many ZIP members"),
|
||||
_ => corrupt(format!("invalid ZIP: {e}")),
|
||||
})?;
|
||||
if let Some(name) = z.duplicate_names().next() {
|
||||
return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::<String>())));
|
||||
}
|
||||
Ok(z)
|
||||
}
|
||||
|
||||
/// Read one exported `.penpot` archive without touching the filesystem or running a converter.
|
||||
/// Returns native, editable FigCraft nodes plus notes about unsupported features.
|
||||
pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
|
||||
if bytes.len() > MAX_ARCHIVE {
|
||||
return Err(corrupt("archive exceeds 512 MiB"));
|
||||
}
|
||||
let mut z = ZipArchive::new(Cursor::new(bytes)).map_err(|e| corrupt(format!("invalid ZIP: {e}")))?;
|
||||
if z.len() > MAX_ENTRIES {
|
||||
return Err(corrupt("too many ZIP members"));
|
||||
}
|
||||
// Reject oversized logical archives before decoding any JSON. This guards against ZIP bombs
|
||||
// whose compressed size is innocuous but whose advertised uncompressed size is enormous.
|
||||
let mut z = open_archive(bytes)?;
|
||||
// Check declared totals and member paths before decoding any JSON.
|
||||
let mut expanded = 0_u64;
|
||||
let mut names = BTreeSet::new();
|
||||
for index in 0..z.len() {
|
||||
let member = z.by_index(index).map_err(|e| corrupt(e.to_string()))?;
|
||||
// An importer never extracts members to disk, but ambiguous ZIP names can
|
||||
// cause one member to be inspected and another member to be read by name.
|
||||
// Reject duplicates and traversal instead of guessing which version is real.
|
||||
let name = member.name();
|
||||
if !names.insert(name.to_owned()) {
|
||||
return Err(corrupt(format!("duplicate ZIP member: {}", name.chars().take(200).collect::<String>())));
|
||||
}
|
||||
let name = z.entry_name(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?;
|
||||
if name.starts_with('/')
|
||||
|| name.contains('\\')
|
||||
|| name.split('/').any(|part| part == "." || part == "..")
|
||||
@@ -390,10 +399,14 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
|
||||
{
|
||||
return Err(corrupt("unsafe ZIP member path"));
|
||||
}
|
||||
expanded = expanded.saturating_add(member.size());
|
||||
let (size, _) = z.entry_sizes(index).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?;
|
||||
expanded = expanded.saturating_add(size);
|
||||
if expanded > MAX_DECOMPRESSED {
|
||||
return Err(corrupt("ZIP contents exceed 1 GiB"));
|
||||
}
|
||||
// The old indexing pass also rejected entries the decoder could not open,
|
||||
// even when mapping the document would never request those members.
|
||||
z.open_entry_index(index, MAX_DECOMPRESSED).map_err(|e| corrupt(e.to_string()))?.ok_or_else(|| corrupt("missing ZIP member"))?;
|
||||
}
|
||||
let mut inflate_budget = InflateBudget::new();
|
||||
let manifest = json(&mut z, "manifest.json", &mut inflate_budget)?;
|
||||
@@ -447,12 +460,12 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
|
||||
// The page index files are peers of the directories containing their layers.
|
||||
let prefix = format!("{base}/pages/");
|
||||
let page_names: Vec<String> = z
|
||||
.file_names()
|
||||
.names()
|
||||
.filter(|name| {
|
||||
name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))
|
||||
})
|
||||
.take(501)
|
||||
.map(str::to_owned)
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.collect();
|
||||
if page_names.len() > 500 {
|
||||
return Err(corrupt("too many pages"));
|
||||
@@ -508,13 +521,13 @@ pub fn import(bytes: &[u8]) -> Result<(Document, Vec<String>), FormatError> {
|
||||
}
|
||||
let page_prefix = format!("{prefix}{page_id}/");
|
||||
let paths: Vec<String> = z
|
||||
.file_names()
|
||||
.names()
|
||||
.filter(|name| {
|
||||
name.strip_prefix(&page_prefix)
|
||||
.is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid))
|
||||
})
|
||||
.take(MAX_LAYERS + 1)
|
||||
.map(str::to_owned)
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.collect();
|
||||
if paths.len() > MAX_LAYERS {
|
||||
return Err(corrupt("too many layers on a page"));
|
||||
@@ -1439,13 +1452,13 @@ fn bind_applied_tokens(doc: &mut Document, active_modes: &BTreeMap<String, Strin
|
||||
|
||||
/// Import Penpot library colors as reusable native styles. Original design-token
|
||||
/// references are handled separately by `bind_applied_tokens` after shape import.
|
||||
fn import_document_colors(z: &mut ZipArchive<Cursor<&[u8]>>, base: &str, doc: &mut Document, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
|
||||
fn import_document_colors(z: &mut PenpotArchive<'_>, base: &str, doc: &mut Document, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
|
||||
let prefix = format!("{base}/colors/");
|
||||
let paths = z
|
||||
.file_names()
|
||||
.names()
|
||||
.filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)))
|
||||
.take(2049)
|
||||
.map(str::to_owned)
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.collect::<Vec<_>>();
|
||||
if paths.len() > 2048 {
|
||||
warn(warnings, "Penpot color library exceeds 2048 swatches; truncated".into());
|
||||
@@ -1483,7 +1496,7 @@ fn import_document_colors(z: &mut ZipArchive<Cursor<&[u8]>>, base: &str, doc: &m
|
||||
/// Keep original values on the text nodes: attaching a shared style automatically
|
||||
/// would override local formatting unless the source explicitly links it.
|
||||
fn import_typography_styles(
|
||||
z: &mut ZipArchive<Cursor<&[u8]>>,
|
||||
z: &mut PenpotArchive<'_>,
|
||||
base: &str,
|
||||
doc: &mut Document,
|
||||
warnings: &mut Vec<String>,
|
||||
@@ -1492,10 +1505,10 @@ fn import_typography_styles(
|
||||
let mut custom_refs = Vec::new();
|
||||
let prefix = format!("{base}/typographies/");
|
||||
let paths: Vec<String> = z
|
||||
.file_names()
|
||||
.names()
|
||||
.filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)))
|
||||
.take(2049)
|
||||
.map(str::to_owned)
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.collect();
|
||||
if paths.len() > 2048 {
|
||||
warn(warnings, "Penpot typography library exceeds 2048 entries; truncated".into());
|
||||
@@ -2359,7 +2372,7 @@ fn import_themed_tokens(
|
||||
|
||||
/// Import supported scalar tokens and retain their original source.
|
||||
fn import_token_variables(
|
||||
z: &mut ZipArchive<Cursor<&[u8]>>,
|
||||
z: &mut PenpotArchive<'_>,
|
||||
base: &str,
|
||||
doc: &mut Document,
|
||||
active_modes: &mut BTreeMap<String, String>,
|
||||
@@ -2367,7 +2380,9 @@ fn import_token_variables(
|
||||
budget: &mut InflateBudget,
|
||||
) -> Option<String> {
|
||||
let path = format!("{base}/tokens.json");
|
||||
z.index_for_name(&path)?;
|
||||
if !z.contains(&path) {
|
||||
return None;
|
||||
}
|
||||
let value = match json(z, &path, budget) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
@@ -2501,16 +2516,16 @@ fn report_design_system_limits(doc: &Document, warnings: &mut Vec<String>) {
|
||||
/// that original into a native FigCraft component. Copies are still independent layers until the
|
||||
/// Penpot override/source graph can be translated safely (see docs).
|
||||
fn component_masters(
|
||||
z: &mut ZipArchive<Cursor<&[u8]>>,
|
||||
z: &mut PenpotArchive<'_>,
|
||||
base: &str,
|
||||
budget: &mut InflateBudget,
|
||||
) -> (BTreeMap<String, String>, BTreeMap<String, String>, BTreeMap<String, String>) {
|
||||
let prefix = format!("{base}/components/");
|
||||
let paths = z
|
||||
.file_names()
|
||||
.names()
|
||||
.filter(|name| name.strip_prefix(&prefix).is_some_and(|part| part.len() == 41 && part.ends_with(".json") && part.get(..36).is_some_and(uuid)))
|
||||
.take(10001)
|
||||
.map(str::to_owned)
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.collect::<Vec<_>>();
|
||||
let mut result = BTreeMap::new();
|
||||
let mut variant_names = BTreeMap::new();
|
||||
@@ -2971,7 +2986,7 @@ fn svg_paint_ref(text: &str) -> Option<&str> {
|
||||
/// What importing a page's layers shares from layer to layer: the archive and the page's shapes,
|
||||
/// and the document, budgets and warnings they add to.
|
||||
struct LayerImport<'a, 'b> {
|
||||
z: &'a mut ZipArchive<Cursor<&'b [u8]>>,
|
||||
z: &'a mut PenpotArchive<'b>,
|
||||
base: &'a str,
|
||||
shapes: &'a BTreeMap<String, Value>,
|
||||
children_by_parent: &'a BTreeMap<String, Vec<String>>,
|
||||
@@ -4137,7 +4152,7 @@ fn effects(v: &Value, warnings: &mut Vec<String>) -> Vec<Effect> {
|
||||
|
||||
/// Resolve a Penpot image fill through `media/<id>.json` -> `objects/<mediaId>.png|jpg`.
|
||||
fn paints(
|
||||
z: &mut ZipArchive<Cursor<&[u8]>>,
|
||||
z: &mut PenpotArchive<'_>,
|
||||
base: &str,
|
||||
shape: &Value,
|
||||
key: &str,
|
||||
@@ -4172,10 +4187,7 @@ fn paints(
|
||||
};
|
||||
if let Some(obj) = object_id {
|
||||
let p = format!("objects/{obj}.{extension}");
|
||||
let data = z.by_name(&p).ok().and_then(|f| {
|
||||
if f.size() > MAX_IMAGE {
|
||||
return None;
|
||||
}
|
||||
let data = z.open_entry(&p, MAX_IMAGE).ok().flatten().and_then(|f| {
|
||||
let mut bytes = Vec::new();
|
||||
BudgetReader { inner: f, budget: &mut *budget }.take(MAX_IMAGE + 1).read_to_end(&mut bytes).ok()?;
|
||||
if bytes.len() as u64 > MAX_IMAGE || bytes.len() > MAX_TOTAL_IMAGES.saturating_sub(*image_bytes) {
|
||||
@@ -4387,7 +4399,7 @@ mod tests {
|
||||
writer.write_all(b"[0,0]").unwrap();
|
||||
}
|
||||
let bytes = writer.finish().unwrap().into_inner();
|
||||
let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
|
||||
let mut archive = open_archive(&bytes).unwrap();
|
||||
let mut budget = InflateBudget { json_values: 6, ..InflateBudget::new() };
|
||||
let mut page_bytes = MAX_PAGE_SHAPES_BYTES;
|
||||
assert_eq!(json(&mut archive, "tokens.json", &mut budget).unwrap(), serde_json::json!([0, 0]));
|
||||
@@ -4436,8 +4448,8 @@ mod tests {
|
||||
assert!(dense.len() < MAX_JSON as usize);
|
||||
for index in 0..source.len() {
|
||||
let mut member = source.by_index(index).unwrap();
|
||||
writer.start_file(member.name(), crate::json_options()).unwrap();
|
||||
if member.name().ends_with(&format!("/{id}.json")) {
|
||||
writer.start_file(member.name().expect("ZIP member name"), crate::json_options()).unwrap();
|
||||
if member.name().expect("ZIP member name").ends_with(&format!("/{id}.json")) {
|
||||
writer.write_all(dense.as_bytes()).unwrap();
|
||||
} else {
|
||||
io::copy(&mut member, &mut writer).unwrap();
|
||||
@@ -4495,14 +4507,14 @@ mod tests {
|
||||
z.start_file("shape.json", SimpleFileOptions::default()).unwrap();
|
||||
z.write_all(br#"{"id":"00000000-0000-0000-0000-000000000001","type":"rect"}"#).unwrap();
|
||||
let bytes = z.finish().unwrap().into_inner();
|
||||
let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
|
||||
let mut archive = open_archive(&bytes).unwrap();
|
||||
|
||||
let mut inflate_budget = InflateBudget::new();
|
||||
let mut page_budget = 10u64; // Too small for the shape JSON (~60 bytes)
|
||||
let res = shape_json(&mut archive, "shape.json", &mut inflate_budget, &mut page_budget);
|
||||
assert!(res.is_err());
|
||||
|
||||
let mut archive2 = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
|
||||
let mut archive2 = open_archive(&bytes).unwrap();
|
||||
let mut inflate_budget2 = InflateBudget::new();
|
||||
let mut page_budget2 = 1000u64;
|
||||
let res2 = shape_json(&mut archive2, "shape.json", &mut inflate_budget2, &mut page_budget2);
|
||||
@@ -4510,7 +4522,7 @@ mod tests {
|
||||
assert!(page_budget2 < 1000);
|
||||
}
|
||||
use std::io::Write;
|
||||
use zip::write::SimpleFileOptions;
|
||||
use zip::{ZipArchive, write::SimpleFileOptions};
|
||||
|
||||
fn archive_with_shapes(shapes: &[(&str, Value)]) -> Vec<u8> {
|
||||
archive_with_components(shapes, &[])
|
||||
@@ -4548,6 +4560,23 @@ mod tests {
|
||||
z.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_allows_a_legacy_encoded_ancillary_zip_member() {
|
||||
let id = "cccccccc-cccc-cccc-cccc-cccccccccccc";
|
||||
let bytes = archive_with_shapes(&[(id, serde_json::json!({"id":id,"type":"rect","name":"Imported rectangle","width":40,"height":25}))]);
|
||||
let mut writer = zip::ZipWriter::new_append(Cursor::new(bytes)).unwrap();
|
||||
// Unflagged CP437, as written by legacy ZIP tools: 0x82 is é.
|
||||
writer.start_file_with_options(SimpleFileOptions::default().name(b"caf\x82.txt")).unwrap();
|
||||
writer.write_all(b"Ancillary archive note").unwrap();
|
||||
let bytes = writer.finish().unwrap().into_inner();
|
||||
|
||||
let mut archive = open_archive(&bytes).unwrap();
|
||||
assert!((0..archive.len()).any(|i| archive.entry_name(i).unwrap().as_deref() == Some("café.txt")));
|
||||
let (doc, warnings) = import(&bytes).unwrap();
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(doc.nodes().any(|node| node.name == "Imported rectangle"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_svg_from_export_is_preserved_for_native_svg_expansion() {
|
||||
let id = "cccccccc-cccc-cccc-cccc-cccccccccccc";
|
||||
@@ -4931,12 +4960,12 @@ mod tests {
|
||||
let mut e = z.by_index(i).unwrap();
|
||||
let mut content = Vec::new();
|
||||
e.read_to_end(&mut content).unwrap();
|
||||
if e.name().ends_with(&format!("/{ROOT_ID}.json")) {
|
||||
if e.name().expect("ZIP member name").ends_with(&format!("/{ROOT_ID}.json")) {
|
||||
let mut v: Value = serde_json::from_slice(&content).unwrap();
|
||||
v["shapes"] = serde_json::json!([one]);
|
||||
content = serde_json::to_vec(&v).unwrap();
|
||||
}
|
||||
members.push((e.name().to_string(), content));
|
||||
members.push((e.name().expect("ZIP member name").to_string(), content));
|
||||
}
|
||||
drop(z);
|
||||
let cursor = Cursor::new(Vec::new());
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
//! Embedded font detection without decoding or retaining unsupported binaries.
|
||||
|
||||
use super::{BudgetReader, InflateBudget, MAX_ENTRIES, warn};
|
||||
use std::io::{Cursor, Read};
|
||||
use zip::ZipArchive;
|
||||
use super::{BudgetReader, InflateBudget, MAX_ENTRIES, PenpotArchive, warn};
|
||||
use std::io::Read;
|
||||
|
||||
/// Identify unsupported fonts from signatures without decoding their payloads.
|
||||
pub(super) fn report(z: &mut ZipArchive<Cursor<&[u8]>>, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
|
||||
pub(super) fn report(z: &mut PenpotArchive<'_>, warnings: &mut Vec<String>, budget: &mut InflateBudget) {
|
||||
let names: Vec<String> = z
|
||||
.file_names()
|
||||
.names()
|
||||
.filter(|n| n.starts_with("objects/") || n.starts_with("fonts/") || n.starts_with("assets/fonts/"))
|
||||
.take(MAX_ENTRIES)
|
||||
.map(str::to_owned)
|
||||
.map(std::borrow::Cow::into_owned)
|
||||
.collect();
|
||||
let mut count = 0;
|
||||
for name in names {
|
||||
let Ok(member) = z.by_name(&name) else { continue };
|
||||
let Ok(Some(member)) = z.open_entry(&name, u64::MAX) else { continue };
|
||||
let mut header = [0; 4];
|
||||
if (BudgetReader { inner: member, budget }).read_exact(&mut header).is_ok()
|
||||
&& (matches!(&header, b"OTTO" | b"true" | b"ttcf" | b"wOFF" | b"wOF2") || header == [0, 1, 0, 0])
|
||||
@@ -35,7 +34,7 @@ pub(super) fn report(z: &mut ZipArchive<Cursor<&[u8]>>, warnings: &mut Vec<Strin
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use std::io::{Cursor, Write};
|
||||
use zip::{ZipWriter, write::SimpleFileOptions};
|
||||
|
||||
#[test]
|
||||
@@ -45,7 +44,7 @@ mod tests {
|
||||
z.write_all(b"wOF2").unwrap();
|
||||
z.write_all(&vec![0; 100_000]).unwrap();
|
||||
let bytes = z.finish().unwrap().into_inner();
|
||||
let mut z = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
|
||||
let mut z = super::super::open_archive(&bytes).unwrap();
|
||||
let mut budget = InflateBudget::new();
|
||||
let before = budget.remaining;
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
@@ -18,7 +18,7 @@ fn entries(bytes: &[u8]) -> BTreeMap<String, Value> {
|
||||
let mut out = BTreeMap::new();
|
||||
for i in 0..z.len() {
|
||||
let mut f = z.by_index(i).unwrap();
|
||||
let name = f.name().to_owned();
|
||||
let name = f.name().expect("ZIP member name").into_owned();
|
||||
if name.ends_with(".json") {
|
||||
let mut text = String::new();
|
||||
f.read_to_string(&mut text).unwrap();
|
||||
@@ -684,7 +684,7 @@ fn imported_penpot_tokens_are_written_back_verbatim() {
|
||||
doc.node_mut(p).unwrap().plugin_data.insert("penpot.fp.tokens".into(), fp);
|
||||
let (bytes, warnings) = export(&doc).unwrap();
|
||||
let mut z = zip::ZipArchive::new(Cursor::new(&bytes[..])).unwrap();
|
||||
let path = z.file_names().find(|n| n.ends_with("tokens.json")).unwrap().to_owned();
|
||||
let path = z.file_names().map(|name| name.expect("ZIP member name")).find(|n| n.ends_with("tokens.json")).unwrap().into_owned();
|
||||
let mut text = String::new();
|
||||
z.by_name(&path).unwrap().read_to_string(&mut text).unwrap();
|
||||
assert_eq!(text, source);
|
||||
@@ -1033,7 +1033,7 @@ fn shared_writer_keeps_manifest_first_and_deflated_members() {
|
||||
let doc = Document::new("Shared container");
|
||||
let (bytes, _) = export(&doc).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap();
|
||||
assert_eq!(zip.by_index(0).unwrap().name(), "manifest.json");
|
||||
assert_eq!(zip.by_index(0).unwrap().name().expect("ZIP member name"), "manifest.json");
|
||||
for index in 0..zip.len() {
|
||||
assert_eq!(zip.by_index(index).unwrap().compression(), zip::CompressionMethod::Deflated);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user