11#include <QRegularExpression>
13#include <QCoreApplication>
14#include <QStringTokenizer>
26static auto isOtpUri(
const QString &value) ->
bool {
38 QString trimmed = line.trimmed();
42 static const QString scheme = QStringLiteral(
"otpauth:");
43 if (!trimmed.startsWith(scheme, Qt::CaseInsensitive)) {
46 qsizetype i = scheme.size();
47 while (i < trimmed.size() && trimmed.at(i).isSpace()) {
50 if (trimmed.mid(i, 2) != QLatin1String(
"//")) {
53 return trimmed.left(scheme.size()) + trimmed.mid(i);
80 qsizetype letters = 0;
81 for (
const QChar c : value) {
82 const char16_t u = c.unicode();
86 if (c.isSpace() || u == u
'-' || u == u
'.' || u == u
'_' || u == u
'=') {
89 if (!((u >= u
'A' && u <= u
'Z') || (u >= u
'a' && u <= u
'z') ||
90 (u >= u
'2' && u <= u
'7'))) {
95 constexpr qsizetype kMinSeedLetters = 16;
105 const qsizetype colon = line.indexOf(u
':');
106 return colon < 0 ? QString() : line.mid(colon + 1);
121 const qsizetype colon = line.indexOf(u
':');
125 const QString value = line.mid(colon + 1);
140 if (
const QString uri =
bareOtpUriOf(line); !uri.isEmpty()) {
143 return line.mid(line.indexOf(u
':') + 1).trimmed();
160 void offer(
const QString &config) {
161 if (!usable.isEmpty()) {
164 if (first.isEmpty()) {
178struct OtpCandidates {
180 OtpCandidate bareLine;
181 OtpCandidate remainingField;
190 auto pick() const -> QString {
191 for (
const OtpCandidate *kind : {&field, &bareLine, &remainingField}) {
192 if (!kind->usable.isEmpty()) {
196 for (
const OtpCandidate *kind : {&field, &bareLine, &remainingField}) {
197 if (!kind->first.isEmpty()) {
217auto takeNamedValue(
const QString &line,
const QStringList &templateFields,
219 const std::function<
bool(
const QString &)> &alsoField,
220 NamedValues &namedValues, OtpCandidates &otp) ->
bool {
221 const qsizetype colon = line.indexOf(u
':');
225 const QString name = line.left(colon);
226 const QString value = line.right(line.length() - colon - 1);
228 if (!templateFields.contains(name) &&
229 !(allFields && !value.startsWith(QStringLiteral(
"//"))) &&
230 !(alsoField && alsoField(name.trimmed()))) {
233 otp.remainingField.offer(value.trimmed());
237 namedValues.append({name.trimmed(), value.trimmed(), line});
241 otp.field.offer(value.trimmed());
251auto moreLinesNotShown(qsizetype count) -> QString {
255 const int n =
static_cast<int>(
256 std::min<qsizetype>(count, std::numeric_limits<int>::max()));
257 return QCoreApplication::translate(
"FileContent",
258 "… %n more line(s) not shown",
nullptr, n);
264struct RemainingText {
268 qsizetype displayed = 0;
269 qsizetype notShown = 0;
276 void add(
const QString &line,
bool shown) {
279 data += QLatin1Char(
'\n');
291 display += QLatin1Char(
'\n');
302 [[nodiscard]]
auto forDisplay() const -> QString {
304 return display + QLatin1Char(
'\n') + moreLinesNotShown(notShown);
313 const QStringList &templateFields,
bool allFields,
314 const std::function<
bool(
const QString &)> &alsoField)
319 QStringTokenizer tokens = QStringView(fileContent).tokenize(u
'\n');
320 auto it = tokens.begin();
322 if (it != tokens.end()) {
326 RemainingText remaining;
341 for (; it != tokens.end(); ++it) {
342 const QString line = it->toString();
343 bool secretPastTheCap =
false;
352 if (takeNamedValue(line, templateFields, allFields, alsoField,
357 takeNamedValue(line, templateFields, allFields, alsoField, pastTheCap,
361 secretPastTheCap = !pastTheCap.isEmpty() && alsoField &&
362 alsoField(pastTheCap.first().name);
366 remaining.add(line, !
isLineHidden(line) && !secretPastTheCap);
369 if (
const QString uri =
bareOtpUriOf(line); !uri.isEmpty()) {
370 otp.bareLine.offer(uri);
378 remaining.data, remaining.forDisplay(),
379 otp.pick(), remaining.lines};
383 const QString trimmed = name.trimmed();
384 return trimmed.compare(QStringLiteral(
"OTP"), Qt::CaseInsensitive) == 0 ||
385 trimmed.compare(QStringLiteral(
"TOTP"), Qt::CaseInsensitive) == 0;
389 const QStringList &secrets) ->
bool {
392 thread_local QStringList cachedSecrets;
393 thread_local QStringList cachedWords;
394 thread_local QRegularExpression cachedPattern;
395 thread_local bool cachedYet =
false;
396 constexpr auto options = QRegularExpression::CaseInsensitiveOption |
397 QRegularExpression::UseUnicodePropertiesOption;
398 if (!cachedYet || secrets != cachedSecrets) {
400 for (
const QString &secret : secrets) {
401 const QString word = secret.trimmed();
402 if (word.isEmpty()) {
410 const QString letters = QStringLiteral(
"\\p{L}\\p{M}");
411 const QString before =
412 word.front().isDigit() ? letters + QStringLiteral(
"\\d") : letters;
413 const QString after =
414 word.back().isDigit() ? letters + QStringLiteral(
"\\d") : letters;
415 cachedWords << QStringLiteral(
"(?<![%1])%2s?(?![%3])")
416 .arg(before, QRegularExpression::escape(word), after);
418 cachedSecrets = secrets;
420 cachedPattern = QRegularExpression(
421 QStringLiteral(
"(?:%1)").arg(cachedWords.join(QLatin1Char(
'|'))),
424 if (cachedWords.isEmpty()) {
433 static const QRegularExpression lowerThenUpper(
434 QStringLiteral(
"(?<=[\\p{Ll}\\d])(?=\\p{Lu})"),
435 QRegularExpression::UseUnicodePropertiesOption);
436 static const QRegularExpression acronymThenWord(
437 QStringLiteral(
"(?<=\\p{Lu})(?=\\p{Lu}\\p{Ll})"),
438 QRegularExpression::UseUnicodePropertiesOption);
439 QString camel = name;
440 camel.replace(lowerThenUpper, QStringLiteral(
" "));
441 QString words = camel;
442 words.replace(acronymThenWord, QStringLiteral(
" "));
443 const auto matches = [&](
const QRegularExpression &pattern) {
444 return pattern.match(name).hasMatch() ||
445 (camel != name && pattern.match(camel).hasMatch()) ||
446 (words != camel && pattern.match(words).hasMatch());
448 if (cachedPattern.isValid()) {
449 return matches(cachedPattern);
453 return std::any_of(cachedWords.cbegin(), cachedWords.cend(),
454 [&matches, options](
const QString &word) {
455 return matches(QRegularExpression(word, options));
460 return value.trimmed().startsWith(QStringLiteral(
"otpauth://"),
461 Qt::CaseInsensitive);
470 static const QString scheme = QStringLiteral(
"otpauth:");
471 for (qsizetype at = text.indexOf(scheme, 0, Qt::CaseInsensitive); at >= 0;
472 at = text.indexOf(scheme, at + 1, Qt::CaseInsensitive)) {
473 qsizetype i = at + scheme.size();
474 while (i < text.size() && text.at(i).isSpace()) {
477 if (text.mid(i, 2) == QLatin1String(
"//")) {
486 QStringView line = text.left(text.indexOf(u
'\n'));
487 if (line.endsWith(u
'\r')) {
490 return line.toString();
497 const qsizetype colon = line.indexOf(u
':');
537 end = text.indexOf(QLatin1Char(
'\n'), end + 1);
542 const qsizetype more =
544 return text.left(end) + QLatin1Char(
'\n') + moreLinesNotShown(more);
561 for (
int i = 0; i < length(); ++i) {
562 if (at(i).name == name) {
static auto boundedForDisplay(const QString &text) -> QString
text cut to kMaxDisplayLines lines, as getRemainingDataForDisplay() is: for showing an entry as it is...
FileContent(QString password, NamedValues namedValues, QString remainingData, QString remainingDataDisplay, QString otpUri, qsizetype remainingLines)
Assemble a parsed entry; only parse() calls this.
qsizetype remainingLines
Number of lines in remainingData.
static auto passwordLine(QStringView text) -> QString
The password of an entry: its first line, without the carriage return of a CRLF line end.
QString remainingData
Body lines that are not fields, joined with newlines; complete.
auto getRemainingLineCount() const -> qsizetype
How many lines getRemainingData() holds.
QString password
The first line of the entry, without the "\r" of a CRLF line end (passwordLine()).
static auto isOtpFieldName(const QString &name) -> bool
Whether a field name designates the one-time password field.
QString otpUri
Raw OTP configuration (URI or bare base32), or empty.
static auto isOtpLine(const QString &line) -> bool
Whether line carries a TOTP shared secret: a bare otpauth:// line, an OTP:/TOTP: field,...
static constexpr int kMaxDisplayLines
Most lines of remaining text getRemainingDataForDisplay() gives.
auto getRemainingData() const -> QString
auto getNamedValues() const -> NamedValues
static constexpr int kMaxNamedFields
Most named fields parse() takes from one entry.
static auto parse(const QString &fileContent, const QStringList &templateFields, bool allFields, const std::function< bool(const QString &)> &alsoField={}) -> FileContent
parse parses the given fileContent in a FileContent object. The password is accessible through getPas...
static auto isSecretFieldName(const QString &name, const QStringList &secrets) -> bool
Whether a field name names a secret: one of secrets occurs in it as whole words, compared case-insens...
NamedValues namedValues
Fields in order of appearance, template fields first.
auto getRemainingDataForDisplay() const -> QString
Like getRemainingData but without data that should not be displayed (like a TOTP secret).
auto getPassword() const -> QString
The password: the first line, without the "\r" of a CRLF line end (passwordLine()).
auto getOtpUri() const -> QString
The entry's raw one-time password configuration, if it has one.
static auto isOtpPasswordLine(const QString &line) -> bool
Whether an entry's first line holds a TOTP shared secret rather than a password.
QString remainingDataDisplay
auto getPasswordForDisplay() const -> QString
Like getPassword but empty when the password line holds a TOTP shared secret (isOtpPasswordLine()).
static auto carriesOtpUri(const QString &text) -> bool
Whether text holds an otpauth URI anywhere: after a list dash, in quotes, behind other text or a seco...
static auto isOtpUriValue(const QString &value) -> bool
Whether a field value is an otpauth URI, and therefore a secret.
The NamedValues class is mostly a list of NamedValue but also has a method to take a specific NamedVa...
auto takeValue(const QString &name) -> QString
Remove and return the value for the named field.
auto takeNamedValue(const QString &name) -> NamedValue
Remove and return the named field, its original line included.
NamedValues()
Construct an empty list.
static auto isValid(const QString &config) -> bool
Convenience validity test, for UI feedback.
static auto otpConfigOf(const QString &line) -> QString
The OTP configuration an OTP line holds: the URI for a bare otpauth:// line (bareOtpUriOf()),...
static auto bareOtpUriOf(const QString &line) -> QString
The otpauth URI a line is written as: a bare otpauth:// line, or the split otpauth: //....
static auto isBase32Seed(const QString &value) -> bool
Whether value is written as a TOTP seed: base32 letters and the digits 2 to 7 only (either case; whit...
static auto isLineHidden(const QString &line) -> bool
Whether a body line must stay out of the parsed display because it carries a TOTP shared secret (File...
static auto afterFirstColon(const QString &line) -> QString
What follows a line's first colon; empty without one.
static auto isOtpUri(const QString &value) -> bool
Shorthand for the public FileContent::isOtpUriValue.
static auto holdsOtpConfig(const QString &line) -> bool
Whether a first line is written as an OTP configuration that otpConfigOf() can read: a bare otpauth U...
Parser for a decrypted password entry: password line, key: value fields, remaining text and the OTP c...
A name/value pair parsed from a password file field.
RFC 6238 TOTP: otpauth URI parsing, code generation and canonical re-serialisation.