Plug-ins: check every number in the type styles a filter writes

Type a filter returned went to layout with its character and paragraph
styles only parsed, and a style equal to one of the type's runs was not
checked at all, so a filter could set leading of 1e9, 100,000 tab stops,
a scale of 0 or a Kinsoku set the document does not have.

- The ranges the character and paragraph style commands keep each
  attribute to move to CharStyle::check_ranges and
  ParaStyle::check_ranges in vectorcraft-doc (text/attr_ranges.rs).
  charStyle.new, charStyle.edit, charStyle.setAttrs and the paragraph
  style commands call them, and so does the filter write path, for every
  run and paragraph style, including one the type already has.
- A paragraph style's custom Kinsoku set must name one of the
  document's sets, and takes that set's characters.
- The character style commands now also refuse tracking and kerning
  outside -1000 to 10000, rotation outside -360 to 360, a miter limit
  outside 1 to 500, Small Caps outside 1 to 200, negative dash lengths
  and a variable font axis setting that is not a number.

Each refusal names the object and the field, and the document does not
change. Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-22 06:24:25 -08:00
1 parent ed50dd06f4
commit 945d0a42b0
12 files changed
+422 -158

No files matched your search

+81 -1
View File
@@ -1275,7 +1275,7 @@ fn bad_writes_are_refused_naming_the_object_and_the_field() {
text,
json!({"text": {"runs": styled(&|s| s["size"] = json!(5000))}}),
&InputKind::ALL,
"text.runs[0].style.size: must be 0.1 to 1296 pt".into(),
"text.runs[0].style.size: `size` must be from 0.1 to 1296".into(),
),
(text, json!({"text": {"runs": styled(&|s| s["size"] = json!("big"))}}), &InputKind::ALL, "text.runs[0].style:".into()),
(
@@ -1444,6 +1444,86 @@ fn written_runs_without_paragraphs_keep_each_paragraph_s_style() {
assert_eq!(justified("A\nB\nC\nD"), [Justify::Left, Justify::Center, Justify::Right, Justify::Right]);
}
/// Every number in the character and paragraph styles a filter writes is checked against the range
/// the style commands keep it to, in a style of the filter's own and in one the type already has,
/// and a custom Kinsoku set must be one of the document's. Each bad value is refused naming the
/// object and the field, and the document stays as it was. A set of the document's, given by
/// name, takes the document's characters.
#[test]
fn written_style_numbers_are_checked_even_in_a_style_the_type_has() {
use vectorcraft_doc::{CharStyle, KinsokuSet, ParaStyle, TabAlign, TabStop, TextObject};
let (mut d, _, layer, _) = mixed();
d.kinsoku_sets.push(KinsokuSet { name: "Mine".into(), cannot_start: vec!['、'], ..KinsokuSet::default() });
let stop = TabStop { position: 10.0, align: TabAlign::Left, leader: String::new(), align_on: '.' };
let outside = KinsokuSet { name: "Elsewhere".into(), ..KinsokuSet::default() };
let bad_chars: [(&str, CharStyle, &str); 5] = [
("leading 1e9", CharStyle { leading: Some(1e9), ..CharStyle::default() }, "style.leading: `leading` must be from 0.1 to 5000"),
("scale 0", CharStyle { h_scale: 0.0, ..CharStyle::default() }, "style.h_scale: `h_scale` must be from 1 to 10000"),
("baseline shift", CharStyle { baseline_shift: 1e9, ..CharStyle::default() }, "style.baseline_shift: `baseline_shift` must be from"),
("tracking", CharStyle { tracking: -5000.0, ..CharStyle::default() }, "style.tracking: `tracking` must be from -1000 to 10000"),
("aki", CharStyle { aki_left: 2000.0, ..CharStyle::default() }, "style.akiLeft: `akiLeft` must be from 0 to 1000"),
];
let hard = |set: KinsokuSet| ParaStyle { kinsoku: vectorcraft_doc::Kinsoku::Hard, kinsoku_set: Some(Arc::new(set)), ..ParaStyle::default() };
let bad_paras: [(&str, ParaStyle, &str); 4] = [
("100000 tabs", ParaStyle { tabs: vec![stop.clone(); 100_000], ..ParaStyle::default() }, "paragraphs[0].tabs: at most 256 tab stops"),
("indent", ParaStyle { left_indent: 1e9, ..ParaStyle::default() }, "paragraphs[0].left_indent: `left_indent` must be from -1296 to 1296"),
(
"hyphenation",
ParaStyle { hyphenation: vectorcraft_doc::HyphenationOptions { after_first: 0, ..Default::default() }, ..ParaStyle::default() },
"paragraphs[0].hyphenation.after_first",
),
("unknown kinsoku set", hard(outside.clone()), "paragraphs[0].kinsoku_set: the document has no Kinsoku set named 'Elsewhere'"),
];
// `own`: the type already has the bad style, and the filter changes only its other run or
// paragraph; otherwise the bad style is the filter's own.
let run = |id: NodeId, own: bool, bad: &CharStyle| {
let mut t = TextObject::point(Point::new(0.0, 0.0), "A\nB", CharStyle::default());
if own {
t.runs = vec![vectorcraft_doc::TextRun::new("A\n", bad.clone()), vectorcraft_doc::TextRun::new("B", CharStyle::default())];
}
let mut doc = d.clone();
let n = Node::new(id, NodeKind::Text(Box::new(t)));
let id = doc.insert(Some(layer), usize::MAX, n).unwrap();
(doc, id)
};
let check = |doc: &Document, id: NodeId, entry: Value, says: &str, what: &str| {
let (bytes, read_only) = encode_input_with(doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
let mut entry = entry;
entry["id"] = json!(id.0);
let mut changed = doc.clone();
let e = write_out(&mut changed, &[id], &bytes, &read_only, &[InputKind::Type], &json!({"objects": [entry]})).unwrap_err().to_string();
assert!(e.contains(&format!("(id {}).text.", id.0)) && e.contains(says), "{what}: {says}: {e}");
assert_eq!(&changed, doc, "{what}: nothing changed");
};
let fresh = d.clone().alloc_id();
for (what, bad, says) in &bad_chars {
let (doc, id) = run(fresh, false, bad);
let runs = json!([{"text": "A\n", "style": bad}, {"text": "B", "style": CharStyle::default()}]);
check(&doc, id, json!({"text": {"runs": runs}}), says, what);
let (doc, id) = run(fresh, true, bad);
let runs = json!([{"text": "A\n", "style": bad}, {"text": "Be", "style": CharStyle::default()}]);
check(&doc, id, json!({"text": {"runs": runs}}), says, &format!("{what}, a style the type has"));
}
let centered = ParaStyle { justify: vectorcraft_doc::Justify::Center, ..ParaStyle::default() };
for (what, bad, says) in &bad_paras {
let (doc, id) = run(fresh, false, &CharStyle::default());
check(&doc, id, json!({"text": {"paragraphs": [bad, ParaStyle::default()]}}), says, what);
let mut doc = doc;
if let Some(Node { kind: NodeKind::Text(t), .. }) = doc.node_mut(id) {
t.set_paragraph_styles(vec![bad.clone(), ParaStyle::default()]);
}
check(&doc, id, json!({"text": {"paragraphs": [bad, centered]}}), says, &format!("{what}, a style the type has"));
}
// A set the document has, by name, takes the document's characters.
let (mut doc, id) = run(fresh, false, &CharStyle::default());
let (bytes, read_only) = encode_input_with(&doc, &[id], &[InputKind::Type], usize::MAX).unwrap();
let named = hard(KinsokuSet { name: "Mine".into(), cannot_start: vec!['x'; 3], ..KinsokuSet::default() });
let out = json!({"objects": [{"id": id.0, "text": {"paragraphs": [named, ParaStyle::default()]}}]});
write_out(&mut doc, &[id], &bytes, &read_only, &[InputKind::Type], &out).unwrap();
let NodeKind::Text(t) = &doc.node(id).unwrap().kind else { panic!("type") };
assert_eq!(t.para_at(0).kinsoku_set.as_deref().map(|s| s.cannot_start.clone()), Some(vec!['、']));
}
/// A filter's `documentData`: absent keeps what the plug-in keeps, `null` forgets it, any other JSON
/// of at most [`MAX_DOCUMENT_DATA`] bytes is kept, and more refuses the whole output.
#[test]
+38 -15
View File
@@ -5,18 +5,16 @@
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use vectorcraft_doc::text::INLINE_CHAR;
use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, ParaStyle, TextObject, TextRun};
use vectorcraft_doc::text::{AttrRangeError, INLINE_CHAR};
use vectorcraft_doc::{CharStyle, Document, JustificationOptions, KinsokuSet, Node, NodeKind, ParaStyle, TextObject, TextRun};
use vectorcraft_geom::Affine;
use super::{
MAX_COORD, MAX_INPUT_RUNS, MAX_INPUT_TEXT, MAX_INPUT_TEXT_TOTAL, admit_paint, decode_name, decode_paint, first_difference, out_err,
read_only_changed,
};
use crate::{InputKind, Result};
use crate::{Error, InputKind, Result};
/// The smallest and largest font size a filter may set, in points (as the Character panel's).
const FONT_SIZE: std::ops::RangeInclusive<f64> = 0.1..=1296.0;
/// The longest font family name a filter may set, in characters.
const MAX_FAMILY: usize = 256;
/// The smallest determinant a transform a filter sets may have: a smaller one flattens the object.
@@ -224,9 +222,10 @@ pub(super) fn apply(doc: &Document, n: &mut Node, changes: &Map<String, Value>,
/// it is a frame of a story that flows through others). Each run has `text`, `style` and, for an
/// inline graphic, `inline`; each attribute is one the type reads. Inline graphics stay as they
/// were, in the same order, and the characters of threaded type or type with ruby stay as they
/// were. A run whose style isn't one of the type's own has a font family and a size in
/// [`FONT_SIZE`], and its paints are checked as an object's are. Paragraph styles are one per
/// paragraph. With runs alone, each paragraph keeps its style when the number of paragraphs stays
/// were. Every number of every run's style is in the range the character style commands keep it
/// to ([`CharStyle::check_ranges`]), and a run whose style isn't one of the type's own has a font
/// family, and its paints are checked as an object's are. Paragraph styles are one per paragraph
/// ([`para_style`]). With runs alone, each paragraph keeps its style when the number of paragraphs stays
/// the same, and otherwise the styles move with the text as typing the change moves them.
fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Value>, paragraphs: Option<&Value>, at: &str) -> Result<()> {
if let Some(runs) = runs {
@@ -252,6 +251,8 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va
if text.contains(INLINE_CHAR) {
return Err(out_err(&at, "`text` holds the character of an inline graphic"));
}
// Every number goes to the layout, so it is checked even in a style the type has.
style.check_ranges(|_| true).map_err(|e| range_err(&format!("{at}.style"), &e))?;
if !own.contains(style_v) {
check_style(doc, &mut style, t.runs.get(i).map(|r| &r.style), &format!("{at}.style"))?;
}
@@ -298,8 +299,7 @@ fn set_text(doc: &Document, t: &mut TextObject, threaded: bool, runs: Option<&Va
if list.len() != count {
return Err(out_err(&at, format!("expected {count} paragraph styles, one per paragraph")));
}
let styles =
list.iter().enumerate().map(|(i, p)| strict::<ParaStyle>(p, &format!("{at}[{i}]"), "a paragraph style")).collect::<Result<_>>()?;
let styles = list.iter().enumerate().map(|(i, p)| para_style(doc, p, &format!("{at}[{i}]"))).collect::<Result<_>>()?;
t.set_paragraph_styles(styles);
}
None => t.normalize_paras(),
@@ -320,17 +320,40 @@ fn changed_range(old: &str, new: &str) -> (usize, usize, usize) {
(start, old.len() - same, new.len() - same)
}
/// An attribute of the style at `at` out of its range, naming the attribute.
fn range_err(at: &str, e: &AttrRangeError) -> Error {
out_err(&format!("{at}.{}", e.key), &e.message)
}
/// Paragraph style `v` from a filter's output, at `at`: each attribute one a paragraph reads, each
/// number in the range the paragraph style commands keep it to ([`ParaStyle::check_ranges`], the
/// Justification options as given), and a custom Kinsoku set one of `doc`'s, by name, whose
/// characters it takes.
fn para_style(doc: &Document, v: &Value, at: &str) -> Result<ParaStyle> {
let mut st: ParaStyle = strict(v, at, "a paragraph style")?;
let justification = match v.get("justification") {
None | Some(Value::Null) => None,
Some(j) => Some(serde_json::from_value::<JustificationOptions>(j.clone()).map_err(|e| out_err(&format!("{at}.justification"), e))?),
};
st.check_ranges(justification.as_ref(), &[], |_, _| true).map_err(|e| range_err(at, &e))?;
if let Some(set) = &st.kinsoku_set {
let found = KinsokuSet::named(&doc.kinsoku_sets, &set.name).ok_or_else(|| {
let shown = crate::permissions::display_text(&set.name, crate::permissions::MAX_SHOWN_FIELD);
out_err(&format!("{at}.kinsoku_set"), format!("the document has no Kinsoku set named '{shown}'"))
})?;
st.kinsoku_set = Some(std::sync::Arc::new(found.clone()));
}
Ok(st)
}
/// Checks character style `s`, a filter's own (`was`: the style of the run in its place before):
/// its font family is 1 to [`MAX_FAMILY`] printable characters, its size is in [`FONT_SIZE`], and
/// its fill and stroke are admitted as an object's paints are.
/// its font family is 1 to [`MAX_FAMILY`] printable characters, and its fill and stroke are
/// admitted as an object's paints are. Its numbers are checked for every run ([`set_text`]).
fn check_style(doc: &Document, s: &mut CharStyle, was: Option<&CharStyle>, at: &str) -> Result<()> {
let family = s.font_family.trim();
if family.is_empty() || family.chars().count() > MAX_FAMILY || s.font_family.chars().any(char::is_control) {
return Err(out_err(&format!("{at}.font_family"), format!("must be 1-{MAX_FAMILY} printable characters")));
}
if !FONT_SIZE.contains(&s.size) {
return Err(out_err(&format!("{at}.size"), format!("must be {} to {} pt", FONT_SIZE.start(), FONT_SIZE.end())));
}
let paint = |p: &vectorcraft_color::Paint, was: Option<&vectorcraft_color::Paint>, key: &str| {
let at = format!("{at}.{key}");
let v = serde_json::to_value(p).map_err(|e| out_err(&at, e))?;