diff --git a/docs/for-developers/template-builder.md b/docs/for-developers/template-builder.md
index c03c005..78a179c 100644
--- a/docs/for-developers/template-builder.md
+++ b/docs/for-developers/template-builder.md
@@ -244,7 +244,7 @@ builds it; its problems carry the JSON pointer. See the known limits for what th
| Code | Severity | Meaning |
|---|---|---|
-| TB9300 | error | The syntax is broken (unclosed loop, …) or the file is not a DOCX/ODT template. |
+| TB9300 | error | The syntax is broken (unclosed loop, …), the file is not a DOCX/ODT template, or it exceeds an upload limit (below). |
| TB9301 | error | The copy reads a path the data does not have (`DataPath` names it as the copy writes it). |
| TB9302 | error | Filling with the data's shape fails, for example a loop over a value. |
| TB9303 | warning | No stamp: edited in an application that dropped it, or not built by the builder. |
@@ -253,6 +253,22 @@ builds it; its problems carry the JSON pointer. See the known limits for what th
| TB9306 | warning | Built from an older version of a component, or from one no longer registered in `Components`. |
| TB92xx, others | error | `CheckDefinition`: the import's and the build's own codes (TB9203: unknown data path). |
+**Upload limits.** An upload comes from outside, so `Check` reads the package once within limits before anything
+parses it, counting what the entries really unpack to (a ZIP can declare false sizes). Exceeding a limit is TB9300 at
+the entry (`word/document.xml`) or paragraph (`content.xml, paragraph 12`), and the check stops there. The defaults fit
+real templates with room to spare; raise them in `TemplateCheckOptions` if yours are larger. Cap the size of the raw
+upload in the host too: `Check` reads the whole stream before it looks inside.
+
+| Option | Default | Limits |
+|---|---|---|
+| `MaximumEntries` | 1,000 | entries in the package |
+| `MaximumUnpackedSize` | 64 MiB | bytes all entries unpack to |
+| `MaximumMarkupSize` | 8 MiB | bytes the XML entries unpack to (recognised by content, not name: what the engine parses; about half a second of checking per MiB) |
+| `MaximumParagraphLength` | 20,000 | characters of text in one paragraph |
+
+The trial fill uses witness data in which a collection answers every index (`lines[999]`) with one shared item and
+loops once, so it is linear in the template, however many indexes and nested loops it has.
+
**Changing the data.** Adding a field is safe. Renaming or removing one is a breaking change: stored templates that read
it break. Check every stored template after such a change (for example on deploy) and show the result to the users
(yellow for warnings, red for broken). The library only checks; storing templates, keeping a changelog of data
@@ -556,8 +572,24 @@ Export the definitions a host stores with `TemplateJsonExportOptions.TextLanguag
the JSON and an agent can read and change them; without, the texts come from the host's catalogue and the agent only
sees the keys.
-A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` into its own child)
-changes nothing and reports TB9207 at the operation (`/1` is the second). The description and the schema are generated
+A patch that cannot be applied (malformed, a missing path, a failed `test` operation, a `move` or `copy` into its own
+child, or a limit below) changes nothing and reports TB9207 at the operation (`/1` is the second).
+
+**Limits.** Everything an agent sends is input from outside. Cap it in the host as well (request size, rate), and keep
+these limits, which hold whatever the host does:
+
+| Limit | Default | Exceeded |
+|---|---|---|
+| `TemplateJsonImportOptions.MaximumLength` | 1,000,000 characters | TB9206 at `""` (import, check, preview); a patch that would make the definition longer: TB9207 at the operation |
+| `TemplateJsonImportOptions.MaximumValues` | 100,000 JSON values (objects, arrays, strings, numbers, …) | TB9206 at `""` |
+| operations in one patch | 1,000 | TB9207 at `/1000` |
+| depth of a patched definition | 64 levels | TB9207 at the operation |
+
+A patch's growth is counted per operation, so a `copy` that doubles the definition is refused before memory runs
+out; a patch longer than `MaximumLength` is refused at `""`, and one that copies or removes more than 16 times
+`MaximumLength` in total at the operation that crosses it. `Patch` writes the result compact (as the length is counted);
+`Read` gives indented parts to read. `Preview` without data fills with the contract's witness, which, like the check's, loops once and answers every
+index with one item; `Preview` with data fills with the host's data as it is. The description and the schema are generated
from one vocabulary that a test compares with the reader, so they always describe what the import accepts.
## Testing your definitions
diff --git a/docs/superpowers/plans/2026-12-02-builder-input-limits.md b/docs/superpowers/plans/2026-12-02-builder-input-limits.md
new file mode 100644
index 0000000..bcf644e
--- /dev/null
+++ b/docs/superpowers/plans/2026-12-02-builder-input-limits.md
@@ -0,0 +1,76 @@
+# Builder input limits Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Check, Preview and Patch stay fast and small on hostile input (#302).
+
+**Architecture:** a shared-item witness list for both witnesses; limit options on check and import options; size,
+depth and count guards in the patch applier.
+
+**Tech Stack:** .NET 11/10, xUnit v3, System.Text.Json, System.IO.Compression, XmlReader.
+
+**Spec:** `docs/superpowers/specs/2026-12-02-builder-input-limits-design.md`
+
+## Global Constraints
+
+- Builder API is experimental (`[TPLB001]` lines in `PublicAPI.Unshipped.txt`); core untouched.
+- Limits give problems (TB9300 / TB9206 / TB9207), never exceptions.
+- Defaults: entries 1,000; unpacked 64 MiB; markup 8 MiB; paragraph 20,000 chars; definition 1,000,000 chars and
+ 100,000 values; patch 1,000 operations, depth 64.
+
+## Review Focus
+
+- A real template (sample, 100+ paragraphs, images) passes Check and Preview unchanged.
+- Indexed paths still resolve in fills (`IndexedPathTests` stay green).
+- Patch: legitimate `copy`/`move` of a section still works.
+- ODT uploads hit the same limits (content.xml / styles.xml, `text:p`/`text:h`).
+- A damaged ZIP is not reported as a limit (the engine's syntax error stays).
+
+---
+
+### Task 1: Shared-item witness
+
+**Files:** Create `src/TriasDev.Templify.Builder/Typed/WitnessList.cs`; modify `DataContract.cs` (WitnessNode.ToData),
+`Typed/DataCatalog.cs` (CreateWitness); test `tests/TriasDev.Templify.Builder.Tests/InputLimitTests.cs`.
+
+- [ ] Tests: `Preview_DeepIndexedPath_IsFastAndSmall` (definition with `{{c0[999].c1[999].c2[999].leaf}}`, Preview
+ without data completes < 1 s, allocations < 100 MB, a document comes back);
+ `Check_IndexedPlaceholderAndNestedLoops_IsFastAndSmall` (DOCX with `{{order.lines[999].description}}` and three
+ nested loops over catalogue collections; Check < 1 s, < 100 MB); `Witness_IndexedItem_Resolves`.
+- [ ] Run, watch the first two fail (timeout/OOM guard via allocation assertion).
+- [ ] `WitnessList(object? item, int count)`: `IList`, read-only, enumerates `[item]`.
+- [ ] Green, plus `IndexedPathTests`, `DataContractTests`, `TemplateCheckTests`.
+
+### Task 2: Definition limits (TB9206)
+
+**Files:** `Json/TemplateJsonImportOptions.cs`, `Json/TemplateJson.cs` (Import), `BuildContext.cs` (code), PublicAPI.
+
+- [ ] Tests: just below / just above for `MaximumLength` and `MaximumValues` (Import throws TemplateBuildException with
+ TB9206 at `""`; CheckDefinition returns it as a problem).
+- [ ] Implement; count values iteratively over the parsed `JsonElement`.
+
+### Task 3: Patch limits (TB9207)
+
+**Files:** `Json/JsonPatch.cs`, `Json/TemplateJson.cs` (Patch passes limits).
+
+- [ ] Tests: `Patch_SelfCopies_AreRefused` (23 × copy `/content` → `/content/-`: not applied, TB9207, < 1 s);
+ `Patch_CopyIntoItsOwnSource_IsRefused`; `Patch_TooManyOperations` (1,000 ok-shaped `test` ops pass, 1,001 → TB9207
+ at `/1000`); `Patch_TooDeep` (TB9207, no exception); size just below/above with a small `MaximumLength`.
+- [ ] Implement `JsonPatch.Apply(document, patch, maximumLength)`.
+
+### Task 4: Check limits (TB9300)
+
+**Files:** `TemplateCheck.cs` (options), `TemplateInspector.cs` (pre-scan), new `PackageLimits.cs`.
+
+- [ ] Tests per limit, DOCX and ODT where it matters: entries, unpacked (zip with a large stored media entry), markup,
+ paragraph length (just below Ok, just above TB9300 with Location naming the entry); a damaged ZIP keeps its old
+ result.
+- [ ] Implement a pre-scan reading every entry through a counting stream; XmlReader (DTD prohibited) for paragraph
+ text in `.xml` entries.
+
+### Task 5: Property test, docs, core issue
+
+- [ ] `Limits_RandomNestingAndIndexes_StayBounded`: seeded random definitions (loop depth 1–6, indexes 0–999) through
+ Preview and CheckDefinition + built upload through Check; each < 2 s and < 100 MB.
+- [ ] Docs: limits table and the agent-input sentence in `docs/for-developers/template-builder.md`.
+- [x] Core issue #321 for the quadratic unterminated-tag scan.
diff --git a/docs/superpowers/specs/2026-12-02-builder-input-limits-design.md b/docs/superpowers/specs/2026-12-02-builder-input-limits-design.md
new file mode 100644
index 0000000..3cce1ba
--- /dev/null
+++ b/docs/superpowers/specs/2026-12-02-builder-input-limits-design.md
@@ -0,0 +1,40 @@
+# Builder: limits for Check, Preview and Patch on untrusted input (#302)
+
+**Status:** approved without a design checkpoint (the maintainer accepts the reviewer's proposal, issue #302).
+
+## Intent
+
+`TemplateInspector.Check`, `TemplateJson.Preview` and `TemplateJson.Patch` are called by an agent host with input it
+does not control. A few hundred bytes must not exhaust memory or keep a core busy for minutes. Every limit gives a
+result with a problem, never an exception.
+
+## Goals
+
+- The three inputs from the issue (indexed placeholder + 3 nested loops in an upload; `c0[999].c1[999].c2[999]` in a
+ definition; 23 self-copies in a patch) return within 1 s and well under 100 MB.
+- Limits on uploads (Check), definitions (Import and everything built on it) and patches, with documented defaults.
+
+Non-goals: limits on the host's own data in `Preview(…, data)` (the host owns it); the core's quadratic scan of
+unterminated tags (a separate core issue; the paragraph limit below bounds it for Check).
+
+## Design
+
+1. **Witness: one shared item per collection.** A collection in witness data is a `WitnessList`: a read-only `IList`
+ whose `Count` is what the highest index needs (`[999]` → 1000), whose indexer returns the one shared item, and which
+ *enumerates one item*. The core indexes through `IList` and loops through `IEnumerable`, so indexed paths resolve
+ and every loop runs once. Witness data is linear in the contract, and a trial fill or a preview without data is
+ linear in the template. Used by `DataContract.CreateWitness` (Preview, test kit) and `DataCatalog.CreateWitness`
+ (Check). Ruling: with one enumerated item there is no product of loop sizes left, so no separate fill budget.
+2. **Check limits** in `TemplateCheckOptions`, counted while reading the package (declared sizes can lie):
+ `MaximumEntries` (1,000), `MaximumUnpackedSize` (64 MiB, all entries), `MaximumMarkupSize` (8 MiB, `.xml`/`.rels`
+ entries: what the engine parses), `MaximumParagraphLength` (20,000 characters of text in one paragraph). Exceeding
+ one is TB9300 at the entry (`word/document.xml`), the paragraph limit also names the paragraph number. The check
+ stops there (no validation, no fill).
+3. **Definition limits** in `TemplateJsonImportOptions`: `MaximumLength` (1,000,000 characters) and `MaximumValues`
+ (100,000 JSON values: objects, arrays, strings, numbers, …). Exceeding one is the new code TB9206 at `""`. All JSON
+ functions that import (Import, CheckDefinition, Patch's check, Preview) inherit them.
+4. **Patch limits**: at most 1,000 operations; the patched document's size, estimated per operation (stored length,
+ plus the value's length for add/replace and the copied node's serialised length for copy/move), stays within the
+ import's `MaximumLength`; its depth stays within 64 (the target pointer's tokens plus the value's depth); `copy`
+ into its own source is refused like `move`. Each is TB9207 at the operation (`/n`).
+5. **Docs**: the developer docs list the limits and defaults, and tell hosts to cap agent input.
diff --git a/src/TriasDev.Templify.Builder/BuildContext.cs b/src/TriasDev.Templify.Builder/BuildContext.cs
index b8e4a81..b9f482f 100644
--- a/src/TriasDev.Templify.Builder/BuildContext.cs
+++ b/src/TriasDev.Templify.Builder/BuildContext.cs
@@ -115,6 +115,9 @@ internal static class DiagnosticCodes
/// A theme value the host sets on import names a token the definition's theme does not have; it is not used.
public const string UnusedThemeValue = "TB9205";
+ /// A JSON definition is longer or has more values than the import options allow.
+ public const string DefinitionTooLarge = "TB9206";
+
/// was called more than once.
public const string PageAlreadySet = "TB6001";
diff --git a/src/TriasDev.Templify.Builder/DataContract.cs b/src/TriasDev.Templify.Builder/DataContract.cs
index d29610d..f61b8a8 100644
--- a/src/TriasDev.Templify.Builder/DataContract.cs
+++ b/src/TriasDev.Templify.Builder/DataContract.cs
@@ -118,8 +118,9 @@ public string ToJson()
}
///
- /// Builds data in which every path of the contract exists: each collection holds one item (or as many as its highest
- /// index needs, items[2] → three), every item with the shape of all its uses; each value is the text "x".
+ /// Builds data in which every path of the contract exists: each collection holds one item, with the shape of all its
+ /// uses, which every index reads (items[2] is that item too); each value is the text "x". A loop over
+ /// it runs once.
///
/// The data, as nested dictionaries and lists.
public IReadOnlyDictionary CreateWitness()
@@ -139,7 +140,7 @@ public string ToJson()
// items[] (every item) or items[2] (one item): the same item shape, at least index + 1 items.
string index = segment[(bracket + 1)..^1];
- node = node.Child(segment[..bracket]).Item(index.Length == 0 ? 1 : int.Parse(index, System.Globalization.CultureInfo.InvariantCulture) + 1);
+ node = node.Child(segment[..bracket]).Item(index.Length == 0 || !int.TryParse(index, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out int at) ? 1 : Math.Min(at, int.MaxValue - 1) + 1);
}
if (entry.Usage == ContractUsage.Collection)
@@ -337,7 +338,8 @@ public WitnessNode Item(int count = 1)
{
if (_item != null)
{
- return Enumerable.Range(0, _count).Select(_ => _item.ToData()).ToList();
+ // One shared item, however high the index (#302): building each anew grows as count^depth.
+ return new WitnessList(_item.ToData(), _count);
}
if (_children.Count > 0)
diff --git a/src/TriasDev.Templify.Builder/Json/JsonPatch.cs b/src/TriasDev.Templify.Builder/Json/JsonPatch.cs
index ae2a8e4..68299c2 100644
--- a/src/TriasDev.Templify.Builder/Json/JsonPatch.cs
+++ b/src/TriasDev.Templify.Builder/Json/JsonPatch.cs
@@ -12,13 +12,39 @@ internal sealed class JsonPatchException(int index, string message) : Exception(
public int Index { get; } = index;
}
-/// JSON Patch (RFC 6902) on : add, remove, replace, move, copy, test.
+///
+/// JSON Patch (RFC 6902) on : add, remove, replace, move, copy, test. A patch comes from outside
+/// (an agent), so it is bounded (#302): at most operations, a document that stays within
+/// a size (estimated per operation, so a copy cannot double it unseen) and within levels, and
+/// no copy or move into its own source.
+///
internal static class JsonPatch
{
+ /// The most operations one patch may have.
+ public const int MaximumOperations = 1000;
+
+ /// The most nested levels a patched document may have (as System.Text.Json reads by default).
+ public const int MaximumDepth = 64;
+
+ /// How a patched definition is written: compact, non-ASCII text unescaped.
+ public static readonly JsonSerializerOptions Compact = new JsonSerializerOptions
+ {
+ Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
+ };
+
/// Applies the operations to a copy of ; all or none.
- /// An operation is malformed or cannot be applied; the input is unchanged.
- public static JsonNode? Apply(JsonNode? document, string patch)
+ /// The document.
+ /// The patch: a JSON array of operations.
+ /// The document's length as stored, in characters.
+ /// The most characters the patched document may have.
+ /// An operation is malformed, cannot be applied or exceeds a limit; the input is unchanged.
+ public static JsonNode? Apply(JsonNode? document, string patch, long length = 0, long maximumLength = long.MaxValue)
{
+ if (patch.Length > maximumLength)
+ {
+ throw new JsonPatchException(-1, $"The patch has {patch.Length} characters; at most {maximumLength} are accepted (TemplateJsonImportOptions.MaximumLength).");
+ }
+
JsonArray operations;
try
{
@@ -29,15 +55,22 @@ internal static class JsonPatch
throw new JsonPatchException(-1, "The patch is not JSON: " + exception.Message);
}
+ if (operations.Count > MaximumOperations)
+ {
+ throw new JsonPatchException(MaximumOperations, $"Operation {MaximumOperations}: a patch has at most {MaximumOperations} operations; send the rest in another patch.");
+ }
+
JsonNode? root = document?.DeepClone();
+ Budget budget = new Budget(length, maximumLength);
for (int i = 0; i < operations.Count; i++)
{
try
{
- root = Operation(root, operations[i] as JsonObject ?? throw new ArgumentException("An operation is an object with \"op\" and \"path\"."));
+ root = Operation(root, operations[i] as JsonObject ?? throw new ArgumentException("An operation is an object with \"op\" and \"path\"."), budget);
}
- catch (ArgumentException exception)
+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException)
{
+ // InvalidOperationException: a string System.Text.Json cannot write (a lone surrogate).
throw new JsonPatchException(i, $"Operation {i}: {exception.Message}");
}
}
@@ -45,44 +78,46 @@ internal static class JsonPatch
return root;
}
- private static JsonNode? Operation(JsonNode? root, JsonObject operation)
+ private static JsonNode? Operation(JsonNode? root, JsonObject operation, Budget budget)
{
string op = Member(operation, "op");
string path = Member(operation, "path");
switch (op)
{
case "add":
- return Add(root, path, Value(operation));
+ return Add(root, path, Value(operation), budget);
case "remove":
+ budget.Remove(JsonPointer.Resolve(root, path));
Remove(root, path);
return root;
case "replace":
- JsonPointer.Resolve(root, path);
+ JsonNode? old = JsonPointer.Resolve(root, path);
if (path.Length == 0)
{
- return Value(operation);
+ budget.Remove(old);
+ return budget.Insert(path, Value(operation));
}
+ budget.Remove(old);
Remove(root, path);
- return Add(root, path, Value(operation));
+ return Add(root, path, Value(operation), budget);
case "move":
string from = Member(operation, "from");
- if (path.StartsWith(from + "/", StringComparison.Ordinal))
- {
- throw new ArgumentException($"'{from}' cannot be moved into itself ('{path}').");
- }
-
+ IntoItself(from, path, "moved");
if (from == path)
{
JsonPointer.Resolve(root, from);
return root;
}
- JsonNode? moved = JsonPointer.Resolve(root, from)?.DeepClone();
+ // Detached, not cloned: a move neither copies nor changes the length.
+ JsonNode? moved = JsonPointer.Resolve(root, from);
Remove(root, from);
- return Add(root, path, moved);
+ return Add(root, path, moved, budget, JsonPointer.Parse(from).Count, charge: false);
case "copy":
- return Add(root, path, JsonPointer.Resolve(root, Member(operation, "from"))?.DeepClone());
+ string source = Member(operation, "from");
+ IntoItself(source, path, "copied");
+ return Add(root, path, JsonPointer.Resolve(root, source)?.DeepClone(), budget, JsonPointer.Parse(source).Count);
case "test":
if (!JsonNode.DeepEquals(JsonPointer.Resolve(root, path), Value(operation)))
{
@@ -95,9 +130,20 @@ internal static class JsonPatch
}
}
- private static JsonNode? Add(JsonNode? root, string path, JsonNode? value)
+ private static void IntoItself(string from, string path, string verb)
+ {
+ if (path.StartsWith(from + "/", StringComparison.Ordinal))
+ {
+ throw new ArgumentException($"'{from}' cannot be {verb} into itself ('{path}').");
+ }
+ }
+
+ // sourceDepth: for a node taken from the document, how many levels down it was; charge: whether the value adds to
+ // the length (not for a move).
+ private static JsonNode? Add(JsonNode? root, string path, JsonNode? value, Budget budget, int? sourceDepth = null, bool charge = true)
{
IReadOnlyList tokens = JsonPointer.Parse(path);
+ value = budget.Insert(path, value, tokens.Count, sourceDepth, charge);
if (tokens.Count == 0)
{
return value;
@@ -159,4 +205,84 @@ private static string Member(JsonObject operation, string name) =>
private static JsonNode? Value(JsonObject operation) =>
operation.TryGetPropertyValue("value", out JsonNode? value) ? value?.DeepClone() : throw new ArgumentException("\"value\" is missing.");
+ ///
+ /// The patched document's length (as writes it), its depth limit, and the work a patch may
+ /// cause: serialising and walking nodes costs at most times the length limit, so a patch
+ /// that copies and removes a large part again and again stops early.
+ ///
+ private sealed class Budget(long length, long maximum)
+ {
+ private const long WorkFactor = 16;
+
+ private readonly long _maximumWork = maximum > long.MaxValue / WorkFactor ? long.MaxValue : maximum * WorkFactor;
+ private long _length = length;
+ private long _work;
+
+ /// Counts a value placed at ( levels down), or refuses it.
+ public JsonNode? Insert(string path, JsonNode? value, int depth = 0, int? sourceDepth = null, bool charge = true)
+ {
+ // The document is never deeper than the limit, so a node taken from it at least as deep fits anywhere higher.
+ if (!(sourceDepth >= depth) && depth + Depth(value) > MaximumDepth)
+ {
+ throw new ArgumentException($"the document would be deeper than {MaximumDepth} levels at '{path}'.");
+ }
+
+ if (charge)
+ {
+ _length += Length(value);
+ if (_length > maximum)
+ {
+ throw new ArgumentException($"the definition would be longer than {maximum} characters (TemplateJsonImportOptions.MaximumLength).");
+ }
+ }
+
+ return value;
+ }
+
+ public void Remove(JsonNode? value) => _length -= Length(value);
+
+ private void Work(long amount)
+ {
+ _work += amount;
+ if (_work > _maximumWork)
+ {
+ throw new ArgumentException("the patch copies or removes too much in total; send smaller patches.");
+ }
+ }
+
+ private long Length(JsonNode? value)
+ {
+ long length = value is null ? 4 : value.ToJsonString(Compact).Length;
+ Work(length);
+ return length;
+ }
+
+ /// The nesting depth of a value: 0 for a scalar, 1 for an empty array or object (iterative).
+ private int Depth(JsonNode? value)
+ {
+ int deepest = 0;
+ Stack<(JsonNode Node, int Depth)> pending = new Stack<(JsonNode, int)>();
+ if (value is JsonObject or JsonArray)
+ {
+ pending.Push((value, 1));
+ }
+
+ while (pending.Count > 0)
+ {
+ (JsonNode node, int depth) = pending.Pop();
+ Work(1);
+ deepest = Math.Max(deepest, depth);
+ IEnumerable children = node is JsonObject o ? o.Select(p => p.Value) : node.AsArray();
+ foreach (JsonNode? child in children)
+ {
+ if (child is JsonObject or JsonArray)
+ {
+ pending.Push((child, depth + 1));
+ }
+ }
+ }
+
+ return deepest;
+ }
+ }
}
diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJson.cs b/src/TriasDev.Templify.Builder/Json/TemplateJson.cs
index ceb6da0..7a6adbb 100644
--- a/src/TriasDev.Templify.Builder/Json/TemplateJson.cs
+++ b/src/TriasDev.Templify.Builder/Json/TemplateJson.cs
@@ -106,7 +106,7 @@ private static void CheckBuildsTheSame(ITemplateDefinition definition, TemplateB
ITemplateDefinition imported;
try
{
- imported = Import(json, new TemplateJsonImportOptions { Assets = assets, Components = export.Components, Shared = shared, AllowRawXml = true, AcceptsAnyValueFormat = true });
+ imported = Import(json, new TemplateJsonImportOptions { Assets = assets, Components = export.Components, Shared = shared, AllowRawXml = true, AcceptsAnyValueFormat = true, MaximumLength = int.MaxValue, MaximumValues = int.MaxValue });
}
catch (TemplateBuildException exception)
{
@@ -230,21 +230,24 @@ public static TemplatePatchResult Patch(string json, string patch, TemplateJsonI
}
JsonNode document = JsonOutline.Parse(json);
- JsonNode? patched;
+ string text;
try
{
- patched = JsonPatch.Apply(document, patch);
+ JsonNode? patched = JsonPatch.Apply(document, patch, document.ToJsonString(JsonPatch.Compact).Length, import.MaximumLength);
+
+ // Compact, as the patch's length was counted: indenting a deeply nested value can multiply its length.
+ text = patched is null ? "null" : patched.ToJsonString(JsonPatch.Compact);
}
- catch (JsonPatchException exception)
+ catch (Exception exception) when (exception is JsonPatchException or InvalidOperationException)
{
+ int index = exception is JsonPatchException failed ? failed.Index : -1;
TemplateCheckProblem problem = new TemplateCheckProblem(CheckCodes.PatchFailed, TemplateCheckSeverity.Error, exception.Message)
{
- Location = exception.Index < 0 ? string.Empty : "/" + exception.Index.ToString(System.Globalization.CultureInfo.InvariantCulture),
+ Location = index < 0 ? string.Empty : "/" + index.ToString(System.Globalization.CultureInfo.InvariantCulture),
};
return new TemplatePatchResult(false, json, new TemplateCheckResult(TriasDev.Templify.Core.TemplateFormat.Unknown, null, [problem]));
}
- string text = patched is null ? "null" : patched.ToJsonString(_indented);
return new TemplatePatchResult(true, text, TemplateInspector.CheckDefinition(text, import, build));
}
@@ -313,12 +316,6 @@ static TemplatePreview Failed(IEnumerable problems) =>
return new TemplatePreview(new TemplateCheckResult(template.Format, null, warnings), filled, PreviewText.Of(filled, template.Format));
}
- private static readonly System.Text.Json.JsonSerializerOptions _indented = new System.Text.Json.JsonSerializerOptions
- {
- WriteIndented = true,
- Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
- };
-
///
/// Imports a JSON definition. The result builds with like a C# definition;
/// problems are reported as build errors with the JSON pointer in .
@@ -331,6 +328,11 @@ public static ITemplateDefinition Import(string json, TemplateJsonImportOptions?
{
ArgumentNullException.ThrowIfNull(json);
options ??= new TemplateJsonImportOptions();
+ if (json.Length > options.MaximumLength)
+ {
+ throw TooLarge($"The definition has {json.Length} characters; at most {options.MaximumLength} are accepted (TemplateJsonImportOptions.MaximumLength).");
+ }
+
System.Text.Json.JsonElement root;
try
{
@@ -342,6 +344,11 @@ public static ITemplateDefinition Import(string json, TemplateJsonImportOptions?
throw Invalid(string.Empty, "The text is not JSON: " + exception.Message);
}
+ if (!WithinValues(root, options.MaximumValues))
+ {
+ throw TooLarge($"The definition has more than {options.MaximumValues} JSON values (TemplateJsonImportOptions.MaximumValues).");
+ }
+
if (root.ValueKind != System.Text.Json.JsonValueKind.Object
|| !root.TryGetProperty("templifyDefinition", out System.Text.Json.JsonElement version)
|| version.ValueKind != System.Text.Json.JsonValueKind.Number
@@ -387,6 +394,42 @@ private static void CheckStructure(JsonDefinition definition)
}
}
+ private static TemplateBuildException TooLarge(string message) =>
+ new TemplateBuildException([new BuildDiagnostic(DiagnosticCodes.DefinitionTooLarge, message) { Location = string.Empty }]);
+
+ /// Whether a JSON value holds at most values, itself included (iterative: no deep recursion).
+ private static bool WithinValues(System.Text.Json.JsonElement root, int maximum)
+ {
+ Stack pending = new Stack();
+ pending.Push(root);
+ long count = 0;
+ while (pending.Count > 0)
+ {
+ if (++count > maximum)
+ {
+ return false;
+ }
+
+ System.Text.Json.JsonElement element = pending.Pop();
+ if (element.ValueKind == System.Text.Json.JsonValueKind.Object)
+ {
+ foreach (System.Text.Json.JsonProperty property in element.EnumerateObject())
+ {
+ pending.Push(property.Value);
+ }
+ }
+ else if (element.ValueKind == System.Text.Json.JsonValueKind.Array)
+ {
+ foreach (System.Text.Json.JsonElement item in element.EnumerateArray())
+ {
+ pending.Push(item);
+ }
+ }
+ }
+
+ return true;
+ }
+
private static TemplateBuildException Invalid(string location, string message) =>
new TemplateBuildException([new BuildDiagnostic(DiagnosticCodes.InvalidJson, message) { Location = location }]);
}
diff --git a/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs b/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs
index f9b3b72..b2fdff2 100644
--- a/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs
+++ b/src/TriasDev.Templify.Builder/Json/TemplateJsonImportOptions.cs
@@ -33,6 +33,18 @@ public sealed class TemplateJsonImportOptions
/// Gets a value indicating whether raw XML blocks are accepted. Default: false (a JSON definition is input from outside).
public bool AllowRawXml { get; init; }
+ ///
+ /// Gets the most characters a definition may have; a longer one is refused (TB9206) before it is read. Default:
+ /// 1,000,000. A definition comes from outside (a customer, an agent): cap what you accept.
+ ///
+ public int MaximumLength { get; init; } = 1_000_000;
+
+ ///
+ /// Gets the most JSON values (objects, arrays, strings, numbers, booleans, nulls) a definition may have; more is
+ /// refused (TB9206). Default: 100,000.
+ ///
+ public int MaximumValues { get; init; } = 100_000;
+
///
/// Whether any value format is accepted: the export's self-check, which reads back what the C# definition wrote
/// (host formats included); the host's own list applies when it imports.
diff --git a/src/TriasDev.Templify.Builder/PackageLimits.cs b/src/TriasDev.Templify.Builder/PackageLimits.cs
new file mode 100644
index 0000000..015b0e4
--- /dev/null
+++ b/src/TriasDev.Templify.Builder/PackageLimits.cs
@@ -0,0 +1,240 @@
+// Copyright (c) 2026 TriasDev GmbH & Co. KG
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Globalization;
+using System.IO.Compression;
+using System.Xml;
+
+namespace TriasDev.Templify.Builder;
+
+///
+/// Reads an uploaded package once within the limits of before anything parses it
+/// (#302): entries, unpacked bytes (counted while reading, since declared sizes can lie), XML bytes and the text of one
+/// paragraph. An entry is XML by its content, not its name (a package may name its main part document.bin). A
+/// package that is not a ZIP is left to the format check; an entry that cannot be read (encrypted, an unknown
+/// compression) is skipped, since the engine cannot read it either.
+///
+internal static class PackageLimits
+{
+ private const string WordNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
+ private const string TextNamespace = "urn:oasis:names:tc:opendocument:xmlns:text:1.0";
+
+ /// The first limit the package exceeds, as a TB9300 problem; null when it is within all of them.
+ public static TemplateCheckProblem? Check(byte[] package, TemplateCheckOptions options)
+ {
+ try
+ {
+ using ZipArchive archive = new ZipArchive(new MemoryStream(package, writable: false), ZipArchiveMode.Read);
+ if (archive.Entries.Count > options.MaximumEntries)
+ {
+ return Problem(
+ archive.Entries[options.MaximumEntries].FullName,
+ $"The package has {archive.Entries.Count} entries; at most {options.MaximumEntries} are read (TemplateCheckOptions.MaximumEntries).");
+ }
+
+ Counter counter = new Counter(options);
+ foreach (ZipArchiveEntry entry in archive.Entries)
+ {
+ try
+ {
+ if (Read(entry, counter, options) is { } problem)
+ {
+ return problem;
+ }
+ }
+ catch (Exception exception) when (exception is InvalidDataException or NotSupportedException or IOException)
+ {
+ // Unreadable here, so unreadable for the engine: what it yielded so far is counted.
+ }
+ }
+ }
+ catch (Exception exception) when (exception is InvalidDataException or NotSupportedException or IOException)
+ {
+ // Not a ZIP, or a damaged directory: the format check reports it.
+ }
+
+ return null;
+ }
+
+ private static TemplateCheckProblem? Read(ZipArchiveEntry entry, Counter counter, TemplateCheckOptions options)
+ {
+ bool markup = LooksLikeXml(entry);
+ using CountingStream stream = new CountingStream(entry.Open(), counter, markup);
+ try
+ {
+ if (markup)
+ {
+ if (Paragraphs(stream, options.MaximumParagraphLength) is { } paragraph)
+ {
+ return Problem(
+ $"{entry.FullName}, paragraph {paragraph.ToString(CultureInfo.InvariantCulture)}",
+ $"A paragraph has more than {options.MaximumParagraphLength} characters of text (TemplateCheckOptions.MaximumParagraphLength).");
+ }
+ }
+
+ stream.CopyTo(Stream.Null);
+ }
+ catch (LimitException exception)
+ {
+ return Problem(entry.FullName, exception.Message);
+ }
+
+ return null;
+ }
+
+ ///
+ /// Whether an entry starts like XML: < after an optional byte order mark and white space (a UTF-16 mark
+ /// counts too). Media, fonts and other binary data do not.
+ ///
+ private static bool LooksLikeXml(ZipArchiveEntry entry)
+ {
+ Span start = stackalloc byte[64];
+ int length = 0;
+ using (Stream stream = entry.Open())
+ {
+ int read;
+ while (length < start.Length && (read = stream.Read(start[length..])) > 0)
+ {
+ length += read;
+ }
+ }
+
+ ReadOnlySpan bytes = start[..length];
+ if (bytes.StartsWith((ReadOnlySpan)[0xFF, 0xFE]) || bytes.StartsWith((ReadOnlySpan)[0xFE, 0xFF]))
+ {
+ return true;
+ }
+
+ if (bytes.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF]))
+ {
+ bytes = bytes[3..];
+ }
+
+ bytes = bytes.TrimStart((ReadOnlySpan)[(byte)' ', (byte)'\t', (byte)'\r', (byte)'\n']);
+ return bytes.Length > 0 && bytes[0] == (byte)'<';
+ }
+
+ /// The 1-based number of the first paragraph (in document order) with too much text; null when none.
+ private static int? Paragraphs(Stream stream, int maximum)
+ {
+ XmlReaderSettings settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, CloseInput = false };
+ Stack<(int Number, long Length)> open = new Stack<(int, long)>();
+ int paragraphs = 0;
+ try
+ {
+ using XmlReader reader = XmlReader.Create(stream, settings);
+ while (reader.Read())
+ {
+ switch (reader.NodeType)
+ {
+ case XmlNodeType.Element when IsParagraph(reader):
+ paragraphs++;
+ if (!reader.IsEmptyElement)
+ {
+ open.Push((paragraphs, 0));
+ }
+
+ break;
+ case XmlNodeType.EndElement when open.Count > 0 && IsParagraph(reader):
+ open.Pop();
+ break;
+ case XmlNodeType.Text or XmlNodeType.CDATA or XmlNodeType.SignificantWhitespace or XmlNodeType.Whitespace when open.Count > 0:
+ (int number, long length) = open.Pop();
+ length += reader.Value.Length;
+ if (length > maximum)
+ {
+ return number;
+ }
+
+ open.Push((number, length));
+ break;
+ }
+ }
+ }
+ catch (XmlException)
+ {
+ // Malformed XML: the engine reports it; the rest of the entry is still counted.
+ }
+
+ return null;
+ }
+
+ private static bool IsParagraph(XmlReader reader) =>
+ (reader.LocalName == "p" && reader.NamespaceURI is WordNamespace or TextNamespace)
+ || (reader.LocalName == "h" && reader.NamespaceURI == TextNamespace);
+
+ private static TemplateCheckProblem Problem(string location, string message) =>
+ new TemplateCheckProblem(CheckCodes.Syntax, TemplateCheckSeverity.Error, message) { Location = location };
+
+ private sealed class LimitException(string message) : Exception(message);
+
+ /// The bytes read so far, all entries and XML entries.
+ private sealed class Counter(TemplateCheckOptions options)
+ {
+ private long _total;
+ private long _markup;
+
+ public void Add(int count, bool markup)
+ {
+ _total += count;
+ if (_total > options.MaximumUnpackedSize)
+ {
+ throw new LimitException($"The package unpacks to more than {options.MaximumUnpackedSize} bytes (TemplateCheckOptions.MaximumUnpackedSize).");
+ }
+
+ if (markup)
+ {
+ _markup += count;
+ if (_markup > options.MaximumMarkupSize)
+ {
+ throw new LimitException($"The package's XML unpacks to more than {options.MaximumMarkupSize} bytes (TemplateCheckOptions.MaximumMarkupSize).");
+ }
+ }
+ }
+ }
+
+ /// A read-only stream that counts what it yields.
+ private sealed class CountingStream(Stream inner, Counter counter, bool markup) : Stream
+ {
+ public override bool CanRead => true;
+
+ public override bool CanSeek => false;
+
+ public override bool CanWrite => false;
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => throw new NotSupportedException();
+ set => throw new NotSupportedException();
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ int read = inner.Read(buffer, offset, count);
+ counter.Add(read, markup);
+ return read;
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ inner.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+ }
+}
diff --git a/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt b/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt
index aa2736c..a36bc9d 100644
--- a/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt
+++ b/src/TriasDev.Templify.Builder/PublicAPI.Unshipped.txt
@@ -811,3 +811,15 @@
[TPLB001]TriasDev.Templify.Builder.LoopInfo.Number.get -> TriasDev.Templify.Builder.TemplatePath
[TPLB001]TriasDev.Templify.Builder.LoopItem.Loop.get -> TriasDev.Templify.Builder.LoopInfo!
[TPLB001]TriasDev.Templify.Builder.LoopItem.Loop.get -> TriasDev.Templify.Builder.LoopInfo!
+[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumLength.get -> int
+[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumLength.init -> void
+[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumValues.get -> int
+[TPLB001]TriasDev.Templify.Builder.Json.TemplateJsonImportOptions.MaximumValues.init -> void
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumEntries.get -> int
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumEntries.init -> void
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumUnpackedSize.get -> long
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumUnpackedSize.init -> void
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumMarkupSize.get -> long
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumMarkupSize.init -> void
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumParagraphLength.get -> int
+[TPLB001]TriasDev.Templify.Builder.TemplateCheckOptions.MaximumParagraphLength.init -> void
diff --git a/src/TriasDev.Templify.Builder/TemplateCheck.cs b/src/TriasDev.Templify.Builder/TemplateCheck.cs
index 0946aa4..0042a72 100644
--- a/src/TriasDev.Templify.Builder/TemplateCheck.cs
+++ b/src/TriasDev.Templify.Builder/TemplateCheck.cs
@@ -58,6 +58,24 @@ public sealed record TemplateCheckOptions
/// versioned component the host uses should be registered.
///
public ComponentCatalog? Components { get; init; }
+
+ ///
+ /// Gets the most entries the package may have; more is TB9300 and the check stops. Default: 1,000. Upload limits
+ /// are counted while reading, since a package can declare false sizes.
+ ///
+ public int MaximumEntries { get; init; } = 1000;
+
+ /// Gets the most bytes all entries may unpack to; more is TB9300 at the entry that crosses it. Default: 64 MiB.
+ public long MaximumUnpackedSize { get; init; } = 64L * 1024 * 1024;
+
+ ///
+ /// Gets the most bytes the XML entries (by their content, whatever their name: what the engine parses) may unpack
+ /// to; more is TB9300 at the entry that crosses it. Default: 8 MiB.
+ ///
+ public long MaximumMarkupSize { get; init; } = 8L * 1024 * 1024;
+
+ /// Gets the most characters of text one paragraph may have; more is TB9300 at the paragraph. Default: 20,000.
+ public int MaximumParagraphLength { get; init; } = 20_000;
}
/// The result of or .
diff --git a/src/TriasDev.Templify.Builder/TemplateInspector.cs b/src/TriasDev.Templify.Builder/TemplateInspector.cs
index a9db156..c735d43 100644
--- a/src/TriasDev.Templify.Builder/TemplateInspector.cs
+++ b/src/TriasDev.Templify.Builder/TemplateInspector.cs
@@ -44,6 +44,11 @@ public static TemplateCheckResult Check(Stream template, TemplateCheckOptions op
ArgumentNullException.ThrowIfNull(template);
ArgumentNullException.ThrowIfNull(options);
byte[] bytes = ReadAll(template);
+ if (PackageLimits.Check(bytes, options) is { } tooLarge)
+ {
+ return new TemplateCheckResult(TemplateFormat.Unknown, null, [tooLarge]);
+ }
+
TemplateFormat format = DetectFormat(bytes);
TemplateStamp? stamp = ReadStamp(bytes, format);
List problems = new List();
diff --git a/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs b/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs
index b9b0c9f..bd4106f 100644
--- a/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs
+++ b/src/TriasDev.Templify.Builder/Typed/DataCatalog.cs
@@ -109,11 +109,11 @@ public string ToJson()
}
///
- /// Builds data in which every path of the catalogue exists: values are the text "x", collections hold
- /// items, and an open shape is an with the given names.
+ /// Builds data in which every path of the catalogue exists: values are the text "x", a collection answers
+ /// every index below with one shared item and enumerates it once, and an open shape is an with the given names.
///
/// The names an open shape has (at any depth below it); null for none.
- /// How many items every collection holds (an index [n] needs n + 1).
+ /// How many items every collection answers by index (an index [n] needs n + 1).
internal IReadOnlyDictionary CreateWitness(IEnumerable? openNames = null, int items = 1)
{
OpenWitness open = new OpenWitness(openNames ?? []);
@@ -139,7 +139,7 @@ public string ToJson()
return open;
case DataKind.Collection:
object? item = byPath.TryGetValue(entry.Path + "[]", out DataCatalogEntry? itemEntry) ? Witness(itemEntry) : "x";
- return Enumerable.Repeat(item, items).ToList();
+ return new WitnessList(item, items);
default:
return ObjectWitness(entry.Path);
}
diff --git a/src/TriasDev.Templify.Builder/Typed/WitnessList.cs b/src/TriasDev.Templify.Builder/Typed/WitnessList.cs
new file mode 100644
index 0000000..b9c6f40
--- /dev/null
+++ b/src/TriasDev.Templify.Builder/Typed/WitnessList.cs
@@ -0,0 +1,62 @@
+// Copyright (c) 2026 TriasDev GmbH & Co. KG
+// Licensed under the MIT License. See LICENSE file in the project root for full license information.
+
+using System.Collections;
+
+namespace TriasDev.Templify.Builder;
+
+///
+/// A collection of witness data: every index below reads the one shared item, and enumerating it
+/// gives that item once. The engine indexes through and loops through ,
+/// so lines[999].name resolves while every loop runs once: witness data stays linear in the contract, and a fill
+/// with it linear in the template, whatever indexes and nested loops it has (#302).
+///
+internal sealed class WitnessList : IList
+{
+ private readonly object? _item;
+
+ public WitnessList(object? item, int count)
+ {
+ _item = item;
+ Count = Math.Max(1, count);
+ }
+
+ // Count is public, as on List: a template may read it. The other members are explicit, so a path cannot read a
+ // name (SyncRoot, IsReadOnly) that real data's lists do not offer.
+ public int Count { get; }
+
+ bool IList.IsFixedSize => true;
+
+ bool IList.IsReadOnly => true;
+
+ bool ICollection.IsSynchronized => false;
+
+ object ICollection.SyncRoot => this;
+
+ public object? this[int index]
+ {
+ get => index >= 0 && index < Count ? _item : throw new ArgumentOutOfRangeException(nameof(index));
+ set => throw new NotSupportedException();
+ }
+
+ public IEnumerator GetEnumerator()
+ {
+ yield return _item;
+ }
+
+ public int Add(object? value) => throw new NotSupportedException();
+
+ public void Clear() => throw new NotSupportedException();
+
+ public bool Contains(object? value) => Equals(value, _item);
+
+ public int IndexOf(object? value) => Contains(value) ? 0 : -1;
+
+ public void Insert(int index, object? value) => throw new NotSupportedException();
+
+ public void Remove(object? value) => throw new NotSupportedException();
+
+ public void RemoveAt(int index) => throw new NotSupportedException();
+
+ public void CopyTo(Array array, int index) => array.SetValue(_item, index);
+}
diff --git a/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs b/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs
index 3aef90c..dc780c3 100644
--- a/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs
+++ b/tests/TriasDev.Templify.Builder.Tests/DataContractTests.cs
@@ -108,9 +108,9 @@ public void Witness_HasEveryPathWithOneItemPerCollection()
Dictionary order = Assert.IsType>(witness["order"]);
Assert.Equal("x", order["number"]);
- Dictionary line = Assert.IsType>(Assert.Single(Assert.IsType>(order["lines"])));
+ Dictionary line = Assert.IsType>(Assert.Single(Assert.IsAssignableFrom(order["lines"]).Cast