Nostro/interfaces/Nostro-Utils.cppm

186 lines
8.8 KiB
Text
Raw Normal View History

2026-11-01 18:35:23 +01:00
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
2026-10-31 20:50:57 +01:00
export module Nostro:Utils;
import std;
namespace fs = std::filesystem;
export namespace Nostro {
constexpr std::string EscB(std::string_view s) {
std::string out;
out.reserve(s.size() + 8);
for (const char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
2026-11-01 18:35:23 +01:00
if (static_cast<std::uint8_t>(c) < 0x20) {
out += std::format("\\u{:04x}", static_cast<std::uint8_t>(c));
2026-10-31 20:50:57 +01:00
} else {
out += c;
}
}
}
return out;
}
constexpr std::chrono::system_clock::time_point ParseTimestamp(std::string_view text) {
const auto field = [text](std::size_t offset, std::size_t length) {
2026-11-01 18:35:23 +01:00
// substr cuts a field that would run past the end short, and the size check refuses it.
const std::string_view digits = text.substr(offset, length);
2026-10-31 20:50:57 +01:00
std::uint32_t value = 0;
2026-11-01 18:35:23 +01:00
const std::from_chars_result result = std::from_chars(digits.data(), digits.data() + digits.size(), value);
if(digits.size() != length || result.ec != std::errc() || result.ptr != digits.data() + digits.size()) {
2026-10-31 20:50:57 +01:00
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
return value;
};
if(text.size() < 19 || text[4] != '-' || text[7] != '-' || text[10] != ' ' || text[13] != ':' || text[16] != ':') {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
std::uint32_t micros = 0;
if(text.size() > 19) {
const std::size_t digits = text.size() - 20;
if(text[19] != '.' || digits == 0 || digits > 6) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
micros = field(20, digits);
for(std::size_t i = digits; i < 6; i++) {
micros *= 10;
}
}
const std::chrono::year_month_day date(std::chrono::year(static_cast<std::int32_t>(field(0, 4))), std::chrono::month(field(5, 2)), std::chrono::day(field(8, 2)));
if(!date.ok()) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
return std::chrono::sys_days(date) + std::chrono::hours(field(11, 2)) + std::chrono::minutes(field(14, 2)) + std::chrono::seconds(field(17, 2)) + std::chrono::microseconds(micros);
}
2026-11-01 18:35:23 +01:00
// The inverse of ParseTimestamp: "YYYY-MM-DD hh:mm:ss.ffffff" in UTC, the format bunq reads and writes.
inline std::string FormatTimestamp(std::chrono::system_clock::time_point time) {
return std::format("{:%Y-%m-%d %H:%M:%S}", std::chrono::floor<std::chrono::microseconds>(time));
}
// "YYYY-MM-DD" or "YYYY-MM-DD hh:mm" in the local time zone, for dates typed by a person, moved `addDays` days on
// by the calendar: ParseLocalDate(day, 1) is the midnight that ends `day`, 23 or 25 hours on when the clocks change.
inline std::chrono::system_clock::time_point ParseLocalDate(std::string_view text, std::int32_t addDays = 0) {
const auto number = [text](std::size_t offset, std::size_t length) {
int value = 0;
const char* const first = text.data() + offset;
const std::from_chars_result result = std::from_chars(first, first + length, value);
if(result.ec != std::errc() || result.ptr != first + length) {
throw std::runtime_error(std::format("'{}' is not a date (YYYY-MM-DD or YYYY-MM-DD hh:mm)", text));
}
return value;
};
const bool hasTime = text.size() == 16;
if((text.size() != 10 && !hasTime) || text[4] != '-' || text[7] != '-' || (hasTime && (text[10] != ' ' || text[13] != ':'))) {
throw std::runtime_error(std::format("'{}' is not a date (YYYY-MM-DD or YYYY-MM-DD hh:mm)", text));
}
std::tm local{};
local.tm_year = number(0, 4) - 1900;
local.tm_mon = number(5, 2) - 1;
local.tm_mday = number(8, 2);
local.tm_hour = hasTime ? number(11, 2) : 0;
local.tm_min = hasTime ? number(14, 2) : 0;
local.tm_isdst = -1;
const std::chrono::year_month_day date(std::chrono::year(local.tm_year + 1900), std::chrono::month(local.tm_mon + 1), std::chrono::day(local.tm_mday));
if(!date.ok() || local.tm_hour > 23 || local.tm_min > 59) {
throw std::runtime_error(std::format("'{}' is not a date (YYYY-MM-DD or YYYY-MM-DD hh:mm)", text));
}
// mktime normalises a day past the month's end, and works out the offset of the day it lands on.
local.tm_mday += addDays;
return std::chrono::system_clock::from_time_t(std::mktime(&local));
}
feat(app): add the Nostro app, a window for phones and desktops Linux phones have no banking apps, and a command line is no answer on a phone. The app does everything the nostro command does and, like it, only talks to nostrod: it holds no key and no token. - Nostro.Ui, a toolkit whose screens are functions that fill a frame, ported from imsd-messages ca5cd72d; Nostro.App, the app's state, forms and screens; Nostro.Ui.Shell, which puts them on a Wayland window with Crafter.Graphics; nostro-app; and Nostro.DebugCommands for the --debug-api build. - Client: every method also in an asynchronous form for an sd-event loop, with DaemonMissing and OutcomeUnknown. - nostrod's Flatpak is net.catcrafts.Nostrod now and the app takes net.catcrafts.Nostro; install.sh moves the state. The app's Flatpak, both Flatpaks cross-built for aarch64, and the licence texts they carry. - nostro-fake-system, a made-up bus and bank with a real nostrod on them, to look at the app against. The README's screenshots are taken on it. - The nostro command: an API key's environment is the key's own to say, so --sandbox is for bunq-oauth alone, and a virtual card is listed as VIRTUAL. The published contract changes in three places, before any release (design rule 10): - Transactions' query takes `stored`: answered from what nostrod has stored, without asking the bank. The app searches with it; before, every search was a call to bunq. - AddBunq's `environment` no longer chooses over what the key says of itself: a key of the other environment is refused. - SetCardStatus refuses to freeze or unfreeze a virtual card. bunq reports one as DEACTIVATED however well it pays, and leaves it as it is when asked, without an error. The app is GPL-3.0-only, the library stays LGPL-3.0-only, and no code moved from one to the other (design rule 13). Transaction's schema is unchanged. Verified: the 17 tests pass with every line, function and region of what they link run, and the five lint runs are clean. Every screen was looked at on the made-up system, at a phone's and a desktop's sizes in the light and the dark look, on Plasma under Wayland. What is said of bunq's cards comes from its sandbox, with throwaway users, and from one real virtual card. Known to have been used against production: connecting, and reading accounts, payments and cards. Not known to have been tried: a payment from the app against bunq, OAuth against bunq, and anything on a phone. Building the app takes --graphics=, a Crafter.Graphics checkout on its branch claude/nostro-app, until that branch is merged and pinned here. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 12:27:14 +01:00
// The last moment a date ends a range at: for "YYYY-MM-DD" the end of that day, so a range up to 2026-10-31 includes
// that day; for "YYYY-MM-DD hh:mm" that minute.
inline std::chrono::system_clock::time_point ParseLocalDateEnd(std::string_view text) {
return text.size() == 10 ? ParseLocalDate(text, 1) - std::chrono::microseconds(1) : ParseLocalDate(text);
}
2026-11-01 18:35:23 +01:00
// "YYYY-MM-DD hh:mm" in the local time zone.
inline std::string FormatLocalTime(std::chrono::system_clock::time_point time) {
const std::time_t seconds = std::chrono::system_clock::to_time_t(time);
const std::tm local = *std::localtime(&seconds);
return std::format("{:04}-{:02}-{:02} {:02}:{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday, local.tm_hour, local.tm_min);
}
// Percent-encodes everything but RFC 3986's unreserved characters, for a query parameter.
constexpr std::string UrlEncode(std::string_view text) {
constexpr std::string_view hex = "0123456789ABCDEF";
std::string out;
for(const char c : text) {
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '~') {
out += c;
} else {
const std::uint8_t byte = static_cast<std::uint8_t>(c);
out += '%';
out += hex[byte >> 4];
out += hex[byte & 0xF];
}
}
return out;
}
// Decodes %XX and, as in a query string, '+' for a space. A '%' not followed by two hex digits stays as it is.
constexpr std::string UrlDecode(std::string_view text) {
const auto digit = [](char c) -> std::int32_t {
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'a' && c <= 'f') return c - 'a' + 10;
if(c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
std::string out;
for(std::size_t i = 0; i < text.size(); i++) {
if(text[i] == '+') {
out += ' ';
} else if(text[i] == '%' && i + 2 < text.size() && digit(text[i + 1]) >= 0 && digit(text[i + 2]) >= 0) {
out += static_cast<char>(digit(text[i + 1]) * 16 + digit(text[i + 2]));
i += 2;
} else {
out += text[i];
}
}
return out;
}
// The decoded value of `name` in the query string of `url` (everything between '?' and '#'), if it is there.
constexpr std::optional<std::string> QueryParameter(std::string_view url, std::string_view name) {
const std::size_t question = url.find('?');
if(question == std::string_view::npos) {
return std::nullopt;
}
std::string_view query = url.substr(question + 1);
query = query.substr(0, query.find('#'));
for(const auto part : std::views::split(query, '&')) {
const std::string_view pair(part.begin(), part.end());
const std::size_t equals = pair.find('=');
if(UrlDecode(pair.substr(0, equals)) == name) {
return equals == std::string_view::npos ? std::string() : UrlDecode(pair.substr(equals + 1));
}
}
return std::nullopt;
}
// Where the library's warnings go: a connector that could not be refreshed, an account it skipped, a request made
// but not read back. A line on stderr unless the program replaces it; a daemon sends them to the client that made
// the call instead, as on stderr they would only reach its journal.
std::function<void(std::string_view)> noteSink = [](std::string_view note) {
std::println(std::cerr, "{}", note);
};
// Hands `note` to noteSink.
inline void Note(std::string_view note) {
noteSink(note);
}
2026-10-31 20:50:57 +01:00
}