diff --git a/server/implementations/Catcrafts.Server-Http.cpp b/server/implementations/Catcrafts.Server-Http.cpp index ccae6d0..88e8969 100644 --- a/server/implementations/Catcrafts.Server-Http.cpp +++ b/server/implementations/Catcrafts.Server-Http.cpp @@ -845,6 +845,12 @@ HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) { parsed.value, "422"); } parsed.value.color = variant->slug; + } else { + // A product without variants has no colour. Whatever was posted + // in the field is dropped here, not stored: validation only + // bounds its length, and the stored colour is printed on the + // order page and into the invoice's amounts table. + parsed.value.color.clear(); } unitMinor = variant ? variant->priceInclMinor : product->priceInclMinor; diff --git a/server/implementations/Catcrafts.Server-Invoice.cpp b/server/implementations/Catcrafts.Server-Invoice.cpp index c85d0b5..473d87f 100644 --- a/server/implementations/Catcrafts.Server-Invoice.cpp +++ b/server/implementations/Catcrafts.Server-Invoice.cpp @@ -48,9 +48,15 @@ std::string BuildInvoiceMarkdown(const OrderRecord& o, std::string md; md.reserve(2048); - const std::string item = colorLabel.empty() - ? std::string(productName) - : std::format("{} — {}", productName, colorLabel); + // The item goes into a cell of the amounts table. Its two halves come from + // the catalogue, except that a colour the catalogue no longer lists is + // passed through as the ledger has it, and that was once whatever was + // posted. So it is kept to one line and cannot close its cell: a '|' here + // would otherwise add columns to a row of a signed document. + std::string item = Form::SingleLine( + colorLabel.empty() ? std::string(productName) + : std::format("{} — {}", productName, colorLabel)); + std::ranges::replace(item, '|', '/'); // The number scheme continues the pre-shop administration: the customer // number is a UUID series, the invoice number counts within it. @@ -75,9 +81,29 @@ std::string BuildInvoiceMarkdown(const OrderRecord& o, md += std::format("* Paid via: {}\n", o.paidVia); } md += "\n## Billed and shipped to\n\n"; - md += std::format("{} \n{} \n{} {} \n{}\n\n", - o.buyer.name, o.buyer.street, o.buyer.postal, - o.buyer.city, o.buyer.country); + // The one block of this document the buyer wrote, and it is about to be + // signed, so it is printed as what it is: text, not markup. Two things + // make that so, and each needs the other. + // + // Every field is held to ONE LINE (Form::SingleLine). Checkout refuses a + // field that is not, but what is signed is decided here, by what is in + // the record, and a record can be older than that check or written by + // hand. + // + // And every line is indented four spaces, which is Markdown's literal + // block: nothing in it is read as a heading, a table, a link or HTML. + // One line alone was not enough. These fields sit at the start of + // consecutive lines, so a name of "# CREDIT NOTE" was a heading, and a + // name, a street and a city of "| a | b |", "|---|---|" and "| c | d |" + // were a table, with not a line break among them (found in review, + // 2026-11-26). Indented, they are the characters the buyer typed. It + // also reads right as plain text, which is how this file is mostly read, + // and a line that starts with spaces is never dash-escaped by the + // clearsigning. + md += std::format(" {}\n {}\n {} {}\n {}\n\n", + Form::SingleLine(o.buyer.name), Form::SingleLine(o.buyer.street), + Form::SingleLine(o.buyer.postal), Form::SingleLine(o.buyer.city), + Form::SingleLine(o.buyer.country)); md += "## Amounts\n\n"; md += "| Description | Qty | Amount |\n|---|---|---|\n"; diff --git a/shared/interfaces/Catcrafts.Shared-Form.cppm b/shared/interfaces/Catcrafts.Shared-Form.cppm index 49e150e..228b054 100644 --- a/shared/interfaces/Catcrafts.Shared-Form.cppm +++ b/shared/interfaces/Catcrafts.Shared-Form.cppm @@ -135,6 +135,55 @@ export std::string_view Trim(std::string_view s) { return s; } +// `s` as one line of text, read in the order it is written: every character +// that starts a new line, is not text at all, or changes the direction text +// is drawn in, becomes a space. That is +// +// * the C0 controls and DEL; +// * the C1 controls, U+0080 to U+009F, which include NEL (a line break) +// and CSI (the start of a terminal escape sequence); +// * LS U+2028 and PS U+2029, line breaks to an editor that are not control +// characters to anything that only looks at bytes below 0x20; +// * the bidirectional embedding, override and isolate controls, U+202A to +// U+202E and U+2066 to U+2069, which make a line DISPLAY in another +// order than it is stored. An address in Arabic or Hebrew needs none of +// them; a line that reads one thing and holds another does. +// +// It exists for the address fields. They are free text and stay free text, +// but they are printed into an invoice the shop then SIGNS, one field to a +// line, and a name carrying a line break would write lines of its own into +// that document under the shop's signature. So one definition is shared: +// validation refuses a field this function would change (a tab aside, which +// it makes the same space), and the invoice builder applies it to whatever a +// ledger already holds. +// +// This is about LINES, not about Markdown. A field that stays on its line can +// still begin with '#' or '|', which is why the invoice prints the address as +// a literal block instead of trusting this to keep it inert. +export std::string SingleLine(std::string_view s) { + auto at = [&](std::size_t i) { return static_cast(s[i]); }; + std::string out; + out.reserve(s.size()); + for (std::size_t i = 0; i < s.size(); ++i) { + const unsigned char c = at(i); + if (c < 0x20 || c == 0x7F) { + out += ' '; + } else if (c == 0xC2 && i + 1 < s.size() + && at(i + 1) >= 0x80 && at(i + 1) <= 0x9F) { + out += ' '; // U+0080..U+009F + i += 1; + } else if (c == 0xE2 && i + 2 < s.size() + && ((at(i + 1) == 0x80 && at(i + 2) >= 0xA8 && at(i + 2) <= 0xAE) + || (at(i + 1) == 0x81 && at(i + 2) >= 0xA6 && at(i + 2) <= 0xA9))) { + out += ' '; // U+2028..U+202E, U+2066..U+2069 + i += 2; + } else { + out += s[i]; + } + } + return out; +} + // Deliberately permissive email check. // // Not a regex from a blog post and not an RFC 5322 parser. Fully validating an @@ -370,17 +419,36 @@ export CheckoutResult ValidateCheckout(const Fields& f) { r.errors.push_back({ "email", "That doesn't look like an email address." }); } - // A required free-text field: reject empty and oversize, accept everything - // else. Names, streets and cities worldwide defeat any stricter shape check - // — validating them harder only rejects real addresses. + // A required free-text field: reject empty, oversize and anything that is + // not one line, accept everything else. Names, streets and cities + // worldwide defeat any stricter shape check — validating them harder only + // rejects real addresses. + // + // One line is not a shape check on the address, it is what keeps the field + // a field: these four are printed one to a line on the label and on the + // signed invoice, and a line break inside one would start lines of the + // buyer's own writing in a document the shop signs (see SingleLine). + // + // A TAB is the one such character a real buyer sends. A browser's + // single-line input drops the line breaks from a paste and keeps its + // tabs, and an address copied out of two spreadsheet cells arrives as + // "Hoofdstraat12". That is whitespace somebody meant as a space, so + // it becomes one, the way Trim already treats it at either end. Anything + // else SingleLine would change is refused rather than flattened, for the + // reason quantity is: quietly changing what someone typed is worse than + // asking again, and only a hand-made post can send it. auto requiredText = [&](std::string_view fieldName, std::string& into, std::size_t maxLen, std::string_view emptyMsg) { - const std::string_view v = Trim(f.Get(fieldName)); - into = std::string(v); + into = std::string(Trim(f.Get(fieldName))); + std::ranges::replace(into, '\t', ' '); + const std::string_view v = into; if (v.empty()) { r.errors.push_back({ std::string(fieldName), std::string(emptyMsg) }); } else if (v.size() > maxLen) { r.errors.push_back({ std::string(fieldName), "Too long." }); + } else if (SingleLine(v) != v) { + r.errors.push_back({ std::string(fieldName), + "Line breaks and control characters can't be used here." }); } }; requiredText("name", r.value.name, 120, "A recipient name is required — it goes on the label."); diff --git a/tests/ShouldBuildInvoices/main.cpp b/tests/ShouldBuildInvoices/main.cpp index 9c051ed..916fcc0 100644 --- a/tests/ShouldBuildInvoices/main.cpp +++ b/tests/ShouldBuildInvoices/main.cpp @@ -48,6 +48,33 @@ std::int64_t RowMinor(const std::string& md, std::string_view prefix) { return euros * 100 + cents; } +// Whether the address block is a Markdown literal block and nothing else: +// every line between its heading and the next one is blank or starts with +// four spaces. That is the property that makes a buyer's text inert there, +// whatever it holds, and it is checked on the document, not on particular +// forged strings: a line that slipped out of the block would fail this +// whatever it said. +bool AddressBlockIsLiteral(const std::string& md) { + const std::string_view open = "\n## Billed and shipped to\n"; + const std::size_t from = md.find(open); + if (from == std::string::npos) return false; + const std::size_t start = from + open.size(); + const std::size_t stop = md.find("\n## Amounts\n", start); + if (stop == std::string::npos) return false; + bool any = false; + for (std::size_t at = start; at < stop;) { + const std::size_t nl = md.find('\n', at); + const std::size_t end = std::min(nl, stop); + const std::string_view line = std::string_view(md).substr(at, end - at); + if (!line.empty()) { + if (!line.starts_with(" ")) return false; + any = true; + } + at = end + 1; + } + return any; +} + } // namespace int main() { @@ -86,6 +113,92 @@ int main() { Check(eu.find("€1135.23") != std::string::npos, "invoice: EU total"); Check(eu.find("zero-rated") == std::string::npos, "invoice: EU is not an export"); + // The address block is the buyer's own text inside a document the shop + // signs, and it must stay text: nothing in it may be read as a heading, a + // table or markup of the invoice. Two properties, checked separately + // because the first alone was once taken for the whole. + // + // ONE: a field stays on its line. A record holding line breaks (written + // before checkout refused them, or by hand) cannot start lines of its own. + { + Server::OrderRecord forged = o; + forged.buyer.name = "Ada\n\n## Amounts\n\n| Refund due | 1 | €5000 |"; + forged.buyer.city = "Delft\r\n# Invoice 999"; + const std::string md = + Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green"); + const std::size_t heading = md.find("\n## Amounts\n"); + Check(heading != std::string::npos + && md.find("\n## Amounts\n", heading + 1) == std::string::npos, + "invoice: a line break in a name cannot open a second amounts section"); + Check(md.find("\n Ada ## Amounts | Refund due | 1 | €5000 |\n") + != std::string::npos, + "invoice: the field stays whole, on its one line of the address block"); + Check(AddressBlockIsLiteral(md), + "invoice: with line breaks in the record, the block is still literal"); + } + // TWO: the line it stays on is not read as Markdown. No line break is + // needed to forge structure: name, street and city each begin a line, so + // single-line values were enough for a heading, and three of them in a + // row for a table. Every line of the block is therefore indented four + // spaces, which makes it a literal block. These are the values that got + // through a check for line breaks alone. + { + Server::OrderRecord forged = o; + forged.buyer.name = "# CREDIT NOTE: refund of €5000 owed to the bearer"; + const std::string md = + Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green"); + Check(md.find("\n# CREDIT NOTE") == std::string::npos, + "invoice: a name that begins with '#' does not begin a line with it"); + Check(md.find("\n # CREDIT NOTE: refund of €5000 owed to the bearer\n") + != std::string::npos, + "invoice: it is printed as the characters it is, indented"); + Check(AddressBlockIsLiteral(md), "invoice: a heading-shaped name stays literal"); + } + { + Server::OrderRecord forged = o; + forged.buyer.name = "| Refund due | Qty | Amount |"; + forged.buyer.street = "|---|---|---|"; + forged.buyer.postal = "|"; + forged.buyer.city = "**Refund owed** | 1 | **€5000.00** |"; + const std::string md = + Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green"); + Check(md.find("\n| Refund due") == std::string::npos + && md.find("\n| **Refund owed**") == std::string::npos, + "invoice: three fields shaped like table rows do not begin lines"); + // The one real delimiter row is the amounts table's own. + const std::size_t rule = md.find("\n|---|---|---|"); + Check(rule != std::string::npos + && md.find("\n|---|---|---|", rule + 1) == std::string::npos, + "invoice: the only table in the document is the amounts table"); + Check(AddressBlockIsLiteral(md), "invoice: table-shaped fields stay literal"); + } + { + Server::OrderRecord forged = o; + forged.buyer.name = "Ada

Amounts

"; + forged.buyer.street = "[pay the balance here](https://evil.example)"; + const std::string md = + Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green"); + Check(AddressBlockIsLiteral(md), + "invoice: HTML and a link in the address are inside the literal block"); + } + // The other place text from a record is printed: the item, in a cell of + // the amounts table. A colour the catalogue no longer lists is passed + // through as stored, so it is held to its cell. + { + const std::string md = Server::BuildInvoiceMarkdown( + o, "Fairphone 6", "green | 1 | €0.01 |\n| **Total** | | **€0.01**"); + const std::size_t row = md.find("\n| Fairphone 6"); + Check(row != std::string::npos, "invoice: the item row is there"); + if (row != std::string::npos) { + const std::size_t end = md.find('\n', row + 1); + const std::string_view line = + std::string_view(md).substr(row + 1, end - row - 1); + Check(std::ranges::count(line, '|') == 4, + "invoice: a colour cannot add cells or rows to the amounts table", + line); + } + } + // Every cent of the amounts table, pinned. This is the document a Dutch // buyer, an accountant and the Belastingdienst read, so a rounding change // in Money::NetFromGross must break a test rather than ship a wrong VAT diff --git a/tests/ShouldValidateForms/main.cpp b/tests/ShouldValidateForms/main.cpp index bea6dff..dad3e22 100644 --- a/tests/ShouldValidateForms/main.cpp +++ b/tests/ShouldValidateForms/main.cpp @@ -169,6 +169,101 @@ int main() { + "&street=x&postal=1&city=y&country=NL").Ok(), "checkout: overlong name rejected"); + // One line each. The address fields are printed one to a line on the + // invoice the shop signs, so a line break inside one is a way to write + // lines of one's own into that document: a heading, a row of the amounts + // table, a sentence about a refund. A browser's single-line input cannot + // send one; %0A in a hand-made post can. + { + auto broken = validate("email=a%40b.example" + "&name=Ada%0A%0A%23%23%20Amounts%0A%0ARefund%20due" + "&street=x&postal=1&city=y&country=NL"); + Check(!broken.Ok(), "checkout: a line break inside the name is rejected"); + Check(broken.errors.size() == 1 && broken.errors[0].field == "name", + "checkout: and the refusal hangs off the name field"); + } + Check(!validate("email=a%40b.example&name=Ada&street=Main%20St%201%0D%0AMore" + "&postal=1&city=y&country=NL").Ok(), + "checkout: CRLF inside the street is rejected"); + // A tab is the one of these a real buyer sends: a single-line input drops + // the line breaks from a paste and keeps the tabs, and an address copied + // out of two spreadsheet cells arrives with one in the middle. It is + // whitespace someone meant as a space, so it is stored as one. Refusing + // it told a buyer who pasted their own address that it "must be a single + // line", which it was. + { + auto pasted = validate("email=a%40b.example&name=Ada&street=Hoofdstraat%0912" + "&postal=1234%09AB&city=y&country=NL"); + Check(pasted.Ok(), "checkout: a pasted tab does not refuse the address"); + Check(pasted.value.street == "Hoofdstraat 12", + "checkout: a tab inside a field is stored as the space it stood for", + pasted.value.street); + Check(pasted.value.postal == "1234 AB", + "checkout: in every address field", pasted.value.postal); + } + // What a refusal says. It names the cause, because the buyer who meets it + // pasted something they cannot see. + { + auto broken = validate("email=a%40b.example&name=Ada%0AMore&street=x&postal=1" + "&city=y&country=NL"); + Check(broken.errors.size() == 1 + && broken.errors[0].message.find("Line breaks") != std::string::npos, + "checkout: the refusal says line breaks are the problem", + broken.errors.empty() ? "no error" : broken.errors[0].message); + } + // Two more kinds of character that are not text on a line. U+009B is CSI, + // which starts an escape sequence in a terminal showing the ledger or the + // invoice. U+202E turns the rest of the line around on screen, so that a + // line reads one thing and holds another. + Check(!validate("email=a%40b.example&name=Ada%C2%9B31mRed&street=x&postal=1" + "&city=y&country=NL").Ok(), + "checkout: a C1 control character inside the name is rejected"); + Check(!validate("email=a%40b.example&name=Ada&street=x&postal=1" + "&city=y%E2%80%AEdiap&country=NL").Ok(), + "checkout: a direction override inside the city is rejected"); + // U+2028 and U+0085: line breaks to an editor, and not control characters + // to a check that only looks below 0x20. + Check(!validate("email=a%40b.example&name=Ada&street=x&postal=1" + "&city=Delft%E2%80%A8More&country=NL").Ok(), + "checkout: a Unicode line separator inside the city is rejected"); + Check(!validate("email=a%40b.example&name=Ada%C2%85More&street=x&postal=1" + "&city=y&country=NL").Ok(), + "checkout: a Unicode next-line inside the name is rejected"); + // What must NOT be caught: a line break at the very end is trimmed like + // any other stray whitespace, and a name outside ASCII is a name. Zoë and + // Łukasz are here for their bytes — C3 AB and C5 81 sit right next to the + // C2 85 the rule looks for. + Check(validate("email=a%40b.example&name=Ada%0D%0A&street=x&postal=1" + "&city=y&country=NL").Ok(), + "checkout: a trailing line break is trimmed, not refused"); + Check(validate("email=a%40b.example&name=Zo%C3%AB%20%C5%81ukasz&street=x" + "&postal=1&city=%C2%A3%E2%80%99s-Hertogenbosch&country=NL").Ok(), + "checkout: names and cities outside ASCII are still accepted"); + Check(SingleLine("a\nb\r\nc\td") == "a b c d", + "single line: each control character becomes one space"); + Check(SingleLine("x\xC2\x85y\xE2\x80\xA8z\xE2\x80\xA9!") == "x y z !", + "single line: NEL, LS and PS each become one space"); + Check(SingleLine("Zo\xC3\xAB \xC2\xA3 \xE2\x80\x99s") == "Zo\xC3\xAB \xC2\xA3 \xE2\x80\x99s", + "single line: other multi-byte characters pass through untouched"); + // The edges of each range, so a neighbour is not swept up with it: + // U+007F..U+00A0 around the C1 block, U+2027..U+202F around the line + // breaks and overrides, U+2065..U+206A around the isolates. + Check(SingleLine("a\xC2\x80" "b\xC2\x9F" "c") == "a b c", + "single line: the first and last C1 controls become spaces"); + Check(SingleLine("a\xC2\xA0" "b") == "a\xC2\xA0" "b", + "single line: a no-break space, one past the C1 block, is text"); + Check(SingleLine("a\xE2\x80\xAA" "b\xE2\x80\xAE" "c\xE2\x81\xA6" "d\xE2\x81\xA9" "e") + == "a b c d e", + "single line: the direction controls become spaces"); + Check(SingleLine("a\xE2\x80\xA7" "b\xE2\x80\xAF" "c\xE2\x81\xA5" "d\xE2\x81\xAA" "e") + == "a\xE2\x80\xA7" "b\xE2\x80\xAF" "c\xE2\x81\xA5" "d\xE2\x81\xAA" "e", + "single line: their neighbours on either side are left alone"); + // Arabic and Hebrew text needs none of the explicit controls: its + // direction comes from the letters. A name in either must pass whole. + Check(SingleLine("\xD7\xA9\xD7\x9C\xD7\x95\xD7\x9D \xD9\x85\xD8\xB1\xD8\xAD\xD8\xA8\xD8\xA7") + == "\xD7\xA9\xD7\x9C\xD7\x95\xD7\x9D \xD9\x85\xD8\xB1\xD8\xAD\xD8\xA8\xD8\xA7", + "single line: right-to-left text itself is untouched"); + // Colour and quantity: shape checks here, catalogue checks in the handler. Check(validate(std::string(kGoodOrder) + "&color=green&quantity=2").Ok(), "checkout: colour and quantity accepted");