// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module Nostro.App:Forms_impl; import std; import Nostro; import Nostro.Ui; import :Forms; import :Format; using namespace Nostro; using namespace Nostro::App; using Moment = std::chrono::system_clock::time_point; namespace { std::string_view Trimmed(std::string_view text) { while(text.starts_with(' ')) { text.remove_prefix(1); } while(text.ends_with(' ')) { text.remove_suffix(1); } return text; } // The most of a link that is read, in bytes, and of the name and the description in one, in characters: SEPA's // limits for the name of an account's holder and for what a payment is for, the second of which RFC 8905 gives for // an IBAN's message. A form's field shows what fits its width and no more: what is longer than a bank carries is // refused, not cut, since what is cut off is still sent. The system's password dialog shows less of a name than // this takes, 64 characters: nostrod cuts a longer one short there. constexpr std::size_t linkLimit = 4096; constexpr std::size_t nameLimit = 70; constexpr std::size_t messageLimit = 140; bool Digits(std::string_view text) { return !text.empty() && std::ranges::all_of(text, [](char c) { return c >= '0' && c <= '9'; }); } bool Alphanumeric(std::string_view text) { return !text.empty() && std::ranges::all_of(text, [](char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }); } // In small letters, as far as ASCII has them: a link's scheme and its options' names are in that. std::string Lowered(std::string_view text) { std::string lowered(text); for(char& c : lowered) { if(c >= 'A' && c <= 'Z') { c = static_cast(c - 'A' + 'a'); } } return lowered; } // Whether every % in `text` begins an escape, two hex digits: UrlDecode leaves one that does not as it is, which // is a guess at what was meant. bool Escaped(std::string_view text) { const auto hex = [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); }; for(std::size_t i = 0; i < text.size(); i++) { if(text[i] == '%' && !(i + 2 < text.size() && hex(text[i + 1]) && hex(text[i + 2]))) { return false; } } return true; } // Whether `text` is fit to be a link's name or description: UTF-8 as the bus takes it, each character in its // shortest form and none that is no character, none that the system's password dialog leaves out as drawing // nothing or turning text around, and no space but the ordinary one. The toolkit's decoder takes a sequence longer // than its character needs, which reads as that character and is not valid: the bus refuses it, after the form // has shown it. bool Plain(std::string_view text) { for(std::size_t i = 0; i < text.size();) { const std::size_t at = i; const std::uint32_t code = Ui::DecodeUtf8(text, i); const std::size_t shortest = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4; // U+FFFD is what the decoder gives for bytes that are no character, and what text that was damaged before // it got here holds. The last two code points of every plane are no characters either, and sd-bus refuses // text with one as it does a sequence that is too long: Unshown has those of the first plane and of the // two planes of private use, not the rest. if(code == 0xFFFD || i - at != shortest || Unshown(code) || (Blank(code) && code != ' ') || (code & 0xFFFEU) == 0xFFFEU) { return false; } } return true; } } Read App::ReadAmount(std::string_view text, Currency currency) { std::string amount(Trimmed(text)); if(amount.empty()) { return {std::nullopt, "Enter an amount"}; } // A comma is a decimal separator to most of Europe, and nostro's own amounts have a point. std::ranges::replace(amount, ',', '.'); const std::size_t point = amount.find('.'); const std::size_t whole = std::min(point, amount.size()); const std::size_t decimals = point == std::string::npos ? 0 : amount.size() - point - 1; if(amount.starts_with('-') || whole == 0 || !std::ranges::all_of(amount, [](char c) { return (c >= '0' && c <= '9') || c == '.'; }) || std::ranges::count(amount, '.') > 1) { return {std::nullopt, "Not an amount: digits, as in 12,50"}; } if(decimals > GetCurrencyDecimals(currency)) { return {std::nullopt, std::format("At most {} decimals", GetCurrencyDecimals(currency))}; } // Twelve digits is hundreds of billions: more is a slip of the finger, and far more would not fit the number. if(whole > 12) { return {std::nullopt, "That is too much"}; } const std::int64_t minor = ParseAmount(amount, currency); if(minor == 0) { return {std::nullopt, "An amount above zero"}; } return {minor, {}}; } std::string App::PartyKind(std::string_view text) { const std::string_view party = Trimmed(text); if(party.empty()) { return {}; } if(party.contains('@')) { return "E-mail address"; } return party.starts_with('+') ? "Phone number" : "IBAN"; } Read App::ReadParty(std::string_view text) { const std::string_view party = Trimmed(text); if(party.empty()) { return {std::nullopt, "An IBAN, an e-mail address or a phone number"}; } const std::size_t at = party.find('@'); if(at != std::string_view::npos && (at == 0 || at + 1 == party.size() || party.contains(' '))) { return {std::nullopt, "Not an e-mail address"}; } try { return {BunqCounterparty::Parse(party, {}), {}}; } catch(const std::invalid_argument&) { return {std::nullopt, party.starts_with('+') ? "Not a phone number: +31 6 12345678" : "Not a valid IBAN: check it for a slip"}; } } Read App::ReadDay(std::string_view day, std::string_view time, bool end) { const std::string_view date = Trimmed(day); const std::string_view clock = Trimmed(time); if(date.empty()) { return {std::nullopt, "A day: YYYY-MM-DD"}; } try { // The day by itself first, so that the error names the field that is wrong. const Moment start = ParseLocalDate(date); if(clock.empty()) { return {end ? ParseLocalDateEnd(date) : start, {}}; } } catch(const std::runtime_error&) { return {std::nullopt, "Not a day: YYYY-MM-DD"}; } try { return {ParseLocalDate(std::format("{} {}", date, clock)), {}}; } catch(const std::runtime_error&) { return {std::nullopt, "Not a time: hh:mm"}; } } Read App::ReadCount(std::string_view text) { const std::string_view digits = Trimmed(text); std::uint32_t count = 0; const std::from_chars_result result = std::from_chars(digits.data(), digits.data() + digits.size(), count); if(digits.empty() || result.ec != std::errc() || result.ptr != digits.data() + digits.size() || count == 0) { return {std::nullopt, "A whole number, 1 or more"}; } return {count, {}}; } Read App::ReadPaymentLink(std::string_view link) { constexpr std::string_view scheme = "payto://iban/"; constexpr std::string_view notOne = "It is not a link to pay an IBAN, which is the kind Nostro reads."; constexpr std::string_view damaged = "It is not written as such a link is: something in it is there twice, or cannot be read."; constexpr std::string_view unreadable = "The amount in it cannot be read."; // The scheme and the kind of account it pays may be in capitals. A # begins a part of an address that such a link // does not have. if(link.size() > linkLimit || link.contains('#') || Lowered(link.substr(0, scheme.size())) != scheme) { return {std::nullopt, std::string(notOne)}; } const std::string_view rest = link.substr(scheme.size()); const std::size_t question = rest.find('?'); std::string_view path = rest.substr(0, question); // A bank's code may come before the IBAN, "payto://iban/ABNANL2A/NL91…". Nostro pays without one: it is held to // its shape and left out. if(const std::size_t slash = path.find('/'); slash != std::string_view::npos) { const std::string_view code = path.substr(0, slash); if(!Alphanumeric(code) || (code.size() != 8 && code.size() != 11)) { return {std::nullopt, std::string(notOne)}; } path.remove_prefix(slash + 1); } // Letters and digits and nothing else: no escape that reads otherwise than it looks, and nothing ReadParty would // take for an e-mail address or a phone number. What is left is an IBAN whose check digits hold, or nothing. const Read party = Alphanumeric(path) ? ReadParty(path) : Read{}; if(!party.value) { return {std::nullopt, "The IBAN in it is not a valid one."}; } PaymentLink asked; asked.iban = party.value->value; // The options are walked here, and not asked of the library's QueryParameter: that gives the first of a name that // is there twice, and takes a name's letters as they are written. A link is refused for the one, and its options // are known in capitals too. std::vector said; const std::string_view options = question == std::string_view::npos ? std::string_view() : rest.substr(question + 1); for(const auto part : std::views::split(options, '&')) { const std::string_view option(part.begin(), part.end()); const std::size_t equals = option.find('='); // An option's name as any reader of the link takes it, its escapes undone and in small letters: "AMOUNT" and // "%61mount" are the amount, so a link cannot say one amount to Nostro and another to whoever reads it next. const std::string name = Lowered(UrlDecode(option.substr(0, equals))); // The sender's name is the user's own to give, and what Nostro does not know may be a later version's. if(name != "amount" && name != "receiver-name" && name != "message" && name != "instruction") { continue; } if(std::ranges::contains(said, name)) { return {std::nullopt, std::string(damaged)}; } said.push_back(name); // An instruction is for the payee's bank to pass on unchanged, which no bank Nostro pays through is asked to // do: RFC 8905 has a link refused whose instruction cannot be kept, rather than paid without it. if(name == "instruction") { return {std::nullopt, "It asks for a reference of a kind Nostro cannot send along."}; } const std::string_view written = equals == std::string_view::npos ? std::string_view() : option.substr(equals + 1); if(!Escaped(written)) { return {std::nullopt, std::string(damaged)}; } const std::string value = UrlDecode(written); if(name == "amount") { // "EUR:12.50": the currency, and digits with at most one point among them and digits on both sides of it. // No sign and no space. And no comma: RFC 8905 has a reader pass over commas, by which "EUR:12,50" is // twelve hundred and fifty, and whoever wrote that meant twelve and a half. It is refused, not guessed at. const std::size_t colon = value.find(':'); const std::string_view sum = colon == std::string::npos ? std::string_view() : std::string_view(value).substr(colon + 1); const std::size_t point = sum.find('.'); if(!Digits(sum.substr(0, point)) || (point != std::string_view::npos && !Digits(sum.substr(point + 1)))) { return {std::nullopt, std::string(unreadable)}; } try { // The one currency there is. With a second one the form's amount, which is read in the paying account's // currency, has to be held to the link's as well. asked.currency = GetCurrency(std::string_view(value).substr(0, colon)); } catch(const std::runtime_error&) { return {std::nullopt, "It asks for a currency Nostro does not pay in."}; } // What the form itself refuses: nothing, more decimals than the currency has, more than it can hold. asked.amount = ReadAmount(sum, asked.currency).value; if(!asked.amount) { return {std::nullopt, std::string(unreadable)}; } continue; } if(!Plain(value)) { return {std::nullopt, "The name or the description in it holds what a payment cannot carry."}; } const std::string_view text = Trimmed(value); const bool message = name == "message"; if(Ui::CountCodepoints(text) > (message ? messageLimit : nameLimit)) { return {std::nullopt, "The name or the description in it is too long."}; } (message ? asked.description : asked.name) = std::string(text); } return {std::move(asked), {}}; } bool PaymentForm::Errors::Any() const noexcept { return !to.empty() || !name.empty() || !amount.empty() || !day.empty() || !time.empty() || !every.empty() || !until.empty(); } PaymentForm::Errors PaymentForm::Check(Currency currency, Moment now, PaymentOrder& order) const { Errors errors; Read party = ReadParty(to.value); errors.to = party.error; const std::string_view holder = Trimmed(name.value); // A bank wants the holder's name with an IBAN; an e-mail address or a phone number finds its own. if(party.value && party.value->type == "IBAN" && holder.empty()) { errors.name = "The name of the account's holder"; } const Read sum = ReadAmount(amount.value, currency); errors.amount = sum.error; BunqSchedule schedule; if(when == When::Scheduled) { const Read first = ReadDay(day.value); errors.day = first.error; if(first.value) { const Read start = ReadDay(day.value, time.value); errors.time = start.error; if(LocalDay(*first.value) < LocalDay(now)) { errors.day = "Today or later"; } schedule.start = start.value.value_or(*first.value); } schedule.unit = std::string(scheduleUnits[unit].unit); // Once has nothing to repeat and nothing to end. if(unit != 0) { if(!Trimmed(every.value).empty()) { const Read count = ReadCount(every.value); errors.every = count.error; schedule.every = count.value.value_or(1); } if(!Trimmed(until.value).empty()) { const Read last = ReadDay(until.value, {}, true); errors.until = last.error; if(last.value && first.value && *last.value <= schedule.start) { errors.until = "After the first payment"; } schedule.end = last.value; } } } if(!errors.Any()) { party.value->name = std::string(holder); order = PaymentOrder{std::move(*party.value), *sum.value, std::string(Trimmed(description.value)), when, std::move(schedule)}; } return errors; } void PaymentForm::Fill(const PaymentLink& link) { Clear(); to.Set(link.iban); name.Set(link.name); if(link.amount) { amount.Set(FormatAmount(*link.amount, link.currency)); } description.Set(link.description); linked = true; } void PaymentForm::Clear() { to.Clear(); name.Clear(); amount.Clear(); description.Clear(); when = When::Now; day.Clear(); time.Clear(); unit = 0; every.Clear(); until.Clear(); tried = false; linked = false; } bool RequestForm::Errors::Any() const noexcept { return !from.empty() || !name.empty() || !amount.empty(); } RequestForm::Errors RequestForm::Check(Currency currency, RequestOrder& order) const { Errors errors; Read party = ReadParty(from.value); errors.from = party.error; const std::string_view holder = Trimmed(name.value); if(party.value && party.value->type == "IBAN" && holder.empty()) { errors.name = "The name of the account's holder"; } const Read sum = ReadAmount(amount.value, currency); errors.amount = sum.error; if(!errors.Any()) { party.value->name = std::string(holder); order = RequestOrder{std::move(*party.value), *sum.value, std::string(Trimmed(description.value))}; } return errors; } void RequestForm::Clear() { from.Clear(); name.Clear(); amount.Clear(); description.Clear(); tried = false; } bool FilterForm::Errors::Any() const noexcept { return !amount.empty() || !from.empty() || !to.empty(); } FilterForm::Errors FilterForm::Check(Currency currency, TransactionQuery& query) const { Errors errors; TransactionQuery asked; asked.limit = query.limit; asked.search = std::string(Trimmed(search.value)); if(!Trimmed(amount.value).empty()) { const Read sum = ReadAmount(amount.value, currency); errors.amount = sum.error; if(sum.value) { // What went out is stored below zero. asked.amount = received ? *sum.value : -*sum.value; } } if(!Trimmed(from.value).empty()) { const Read first = ReadDay(from.value); errors.from = first.error; asked.from = first.value.value_or(asked.from); } if(!Trimmed(to.value).empty()) { const Read last = ReadDay(to.value, {}, true); errors.to = last.error; if(last.value && *last.value < asked.from) { errors.to = "On or after the first day"; } asked.to = last.value.value_or(asked.to); } if(!errors.Any()) { query = std::move(asked); } return errors; } std::vector FilterForm::Chips(Currency currency, Moment now) const { std::vector chips; if(const Read sum = ReadAmount(amount.value, currency); sum.value) { chips.push_back(std::format("{} {}", received ? "Received" : "Paid", Money(*sum.value, currency))); } if(const Read first = ReadDay(from.value); first.value) { chips.push_back(std::format("From {}", ShortDate(*first.value, now))); } if(const Read last = ReadDay(to.value); last.value) { chips.push_back(std::format("Until {}", ShortDate(*last.value, now))); } return chips; } void FilterForm::Reset() { amount.Clear(); received = false; from.Clear(); to.Clear(); } BunqKeyForm::BunqKeyForm() { ips.Set("*"); } std::string BunqKeyForm::Check() const { return key.value.empty() ? "The API key, from the bunq app" : std::string(); } void BunqKeyForm::Clear() { key.Clear(); ips.Set("*"); advanced = false; tried = false; } bool BunqOAuthForm::Errors::Any() const noexcept { return !clientId.empty() || !redirectUri.empty() || !secret.empty(); } BunqOAuthForm::Errors BunqOAuthForm::Check() const { Errors errors; if(Trimmed(clientId.value).empty()) { errors.clientId = "The client id bunq gave the OAuth client"; } const std::string_view uri = Trimmed(redirectUri.value); if(!uri.starts_with("https://") && !uri.starts_with("http://")) { errors.redirectUri = "The redirect address registered with the client: https://…"; } if(secret.value.empty()) { errors.secret = "The client's secret"; } return errors; } void BunqOAuthForm::Begin(std::string newState) { state = std::move(newState); address = BunqConnector::OAuthAuthorizationUrl(sandbox ? BunqEnvironment::Sandbox : BunqEnvironment::Production, Trimmed(clientId.value), Trimmed(redirectUri.value), state); } std::string BunqOAuthForm::Code() const { return BunqConnector::OAuthCodeFromRedirect(Trimmed(redirected.value), state); } void BunqOAuthForm::Clear() { clientId.Clear(); redirectUri.Clear(); secret.Clear(); sandbox = false; redirected.Clear(); state.clear(); address.clear(); tried = false; }