Refuse to save a script we only partly read

The transport fix stops the truncation that caused #76, but the save path
had no answer for a baseline that arrives incomplete. It is neither
unknown nor empty, so every existing guard passes it through: it parses
into a shorter rule list that looks exactly like a script with fewer
rules, and saving writes that back over the real one.

Check the script against the shape the generator emits instead. Every
rule comment parses, every enabled rule has an if and a closed body under
it, every block ends with a blank line. Structural rather than a
re-serialize-and-compare, so a script written by an older version whose
serializer differed is still editable.

The rule editor reports a short script as unreadable rather than showing
the rules that happened to parse, since a list that looks complete over a
script that is not is the most dangerous thing it could offer.

A cut at the end of a complete rule block is still a valid shorter script
and cannot be told apart from one; that residual is the proxy's to cover.
This commit is contained in:
2026-08-30 13:56:12 -07:00
parent 0277b5b6a8
commit 8d475e2b07
6 changed files with 227 additions and 15 deletions
+94
View File
@@ -174,6 +174,100 @@ export function rulesToSieve(rules: SieveRule[]): string {
return lines.join("\n");
}
/**
* Why this script must not be rewritten from the rules parsed out of it, or
* null when rewriting it is safe.
*
* Saving replaces the whole script with a fresh serialization of the rules read
* out of it, so whatever was not read is deleted. `sieveToRules` cannot raise
* the alarm by itself: it skips what it does not recognise, so a script cut off
* partway through parses cleanly into a shorter list and looks exactly like one
* that genuinely has fewer rules. That is the shape of the loss in #76 -- a
* truncated download, a plausible parse, and a save that wrote the short
* version back over the real one. The transport fault behind it is fixed in the
* blob proxy; this is the check that makes the save path refuse regardless of
* how the content came to be short.
*
* The tests are structural rather than an equality check against
* `rulesToSieve(sieveToRules(content))`. A script written by an older version
* whose serializer differed in some detail is intact, and refusing to let
* anyone edit their rules over a changed byte would be the worse bug.
*/
export function scriptDamage(content: string): string | null {
// Not one of ours: genuinely empty, or hand-written. Both mean something
// else and are answered elsewhere.
if (!content.includes("# rule:") && !content.includes(SCRIPT_HEADER)) {
// Unless it is one of ours cut off inside its own first line, which reads
// as a very short hand-written script -- and that reading is the one that
// offers to replace it.
const head = content.replace(/\n+$/, "");
if (head !== "" && SCRIPT_HEADER.startsWith(head)) return "breaks off inside its first line";
return null;
}
// Every generated script ends with a newline, so a body that stops mid-line
// stopped early. The rest of the walk covers the cuts that land on one.
if (!content.endsWith("\n")) return "stops in the middle of a line";
const lines = content.replace(/\r\n/g, "\n").split("\n");
let i = 0;
let hadRequire = false;
if (lines[0] === SCRIPT_HEADER) {
i = 1;
hadRequire = lines[i]?.startsWith("require ") ?? false;
if (hadRequire) i++;
if (lines[i] !== "") return "breaks off in its opening lines";
i++;
} else {
// Header edited away but the rule comments kept. Still ours to walk.
i = lines.findIndex((l) => l.startsWith("# rule:"));
}
// Walk the shape rulesToSieve emits, one rule block at a time. Deliberately
// structural: the condition and action lines are read only for their
// presence, so a serializer that words them differently is still intact.
let seen = 0;
const cut = (r: SieveRule, what: string) => `has a rule in it (“${r.name}”) ${what}`;
while (i < lines.length) {
const line = lines[i]!;
if (!line.startsWith("# rule:")) return "has a stray line where a rule should start";
let rule: SieveRule | null = null;
try {
const parsed = JSON.parse(line.slice(7)) as SieveRule;
if (parsed && typeof parsed === "object" && Array.isArray(parsed.tests) && Array.isArray(parsed.actions)) rule = parsed;
} catch {
/* reported below */
}
if (!rule) return "has a rule in it that breaks off unfinished";
seen++;
i++;
// `!r.enabled` is how rulesToSieve chooses the branch, so match it exactly
// rather than testing for `=== false`.
if (rule.enabled) {
if (!lines[i]?.startsWith("if ")) return cut(rule, "with nothing below it");
i++;
if (lines[i] !== "{") return cut(rule, "whose body never opens");
i++;
while (i < lines.length && lines[i] !== "}") {
if (lines[i] === "") return cut(rule, "whose body breaks off");
i++;
}
if (i >= lines.length) return cut(rule, "whose body never closes");
i++;
} else {
if (!lines[i]?.startsWith("# (disabled) ")) return cut(rule, "with nothing below it");
i++;
}
// Each block is followed by a blank line, the last one included: it is the
// empty final element left by the trailing newline.
if (lines[i] !== "") return cut(rule, "that runs into what follows it");
i++;
}
// A require line is written only for rules that need it, so one standing over
// no rules at all means the rules it was written for are gone.
if (hadRequire && seen === 0) return "breaks off before the first rule";
return null;
}
/** Returns rules if the script was generated by ihasmail, else null (raw script). */
export function sieveToRules(script: string): SieveRule[] | null {
if (!script.includes("# rule:")) return script.trim() === "" || script.includes(SCRIPT_HEADER) ? [] : null;