Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ private const val SIGNUP_CODE_REJECTED_CODE = "signup_code_rejected"
/** Storage error code Paykit uses for local and shared state failures. */
private const val STORAGE_ERROR_CODE = "storage_error"

/**
* Protocol error context Paykit 0.1.1-rc9 raises when a social v1 profile holds a link that is not an http(s) URL
* (`paykit-sdk/src/domain/contacts/pubky_app.rs`). Check it again when Paykit is updated.
*/
internal const val PAYKIT_NON_WEB_PROFILE_LINK_CONTEXT = "Pubky profile link URL must be a canonical http or https URL"

/** Storage error contexts Paykit raises when the identity's shared state was saved by a newer Paykit. */
private val NEWER_STATE_CONTEXTS = listOf(
"SDK state blob contains trailing bytes",
Expand All @@ -36,6 +42,11 @@ fun Throwable.isPaykitTemporarilyUnavailable(): Boolean =
fun Throwable.isPaykitMessageTooLarge(): Boolean =
generateSequence(this) { it.cause }.any { it is PaykitException.Protocol && it.code == MESSAGE_TOO_LARGE_CODE }

fun Throwable.isPaykitNonWebProfileLinkRejected(): Boolean =
generateSequence(this) { it.cause }.any {
it is PaykitException.Protocol && it.context == PAYKIT_NON_WEB_PROFILE_LINK_CONTEXT
}

fun Throwable.isPaykitSignupCodeRejected(): Boolean =
generateSequence(this) { it.cause }.any { it is PaykitException.Identity && it.code == SIGNUP_CODE_REJECTED_CODE }

Expand Down
20 changes: 15 additions & 5 deletions app/src/main/java/to/bitkit/ext/String.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package to.bitkit.ext

import android.icu.text.MessageFormat
import to.bitkit.env.Defaults
import to.bitkit.models.linkUrlParts
import to.bitkit.utils.Logger
import java.net.URI

private const val TAG = "StringExt"

Expand Down Expand Up @@ -53,20 +53,30 @@ fun String.formatPlural(argMap: Map<Any, Any>): String =
}

private val WEB_LINK_SCHEMES = setOf("http", "https")
private val URI_SCHEME = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")

/** A URI scheme and its colon at the start of a value. */
internal val URI_SCHEME = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")

/**
* Whether this is an http(s) link, with or without its scheme: the only links a social v1 profile accepts.
* A value with any other scheme, including a bare `host:port`, is refused, as the profile write keeps it unchanged.
* Paykit needs the literal `http://` or `https://`, so a scheme without `//`, or a `\` in the authority, is refused.
*/
fun String.isWebLink(): Boolean {
val value = trim()
if (value.isEmpty() || value.any { it.isWhitespace() }) return false
val hasScheme = URI_SCHEME.containsMatchIn(value)
if (!hasScheme && '@' in value.substringBefore('/')) return false
val uri = runCatching { URI(if (hasScheme) value else "https://$value") }.getOrNull() ?: return false
val host = uri.host ?: return false
return uri.scheme.lowercase() in WEB_LINK_SCHEMES &&
val url = if (hasScheme) value else "https://$value"
val afterScheme = url.substringAfter(':')
if (!afterScheme.startsWith("//")) return false
val authority = afterScheme.drop(2).takeWhile { it !in "/?#" }
val hostAndPort = authority.substringAfterLast('@')
val rawHost = if (hostAndPort.startsWith('[')) hostAndPort else hostAndPort.substringBefore(':')
if ('\\' in authority || rawHost.isEmpty()) return false
val parts = url.linkUrlParts() ?: return false
val host = parts.host.removeSuffix(".")
return parts.scheme in WEB_LINK_SCHEMES &&
'.' in host &&
!host.substringAfterLast('.').all { it.isDigit() }
}
154 changes: 154 additions & 0 deletions app/src/main/java/to/bitkit/models/PubkyAppLink.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
package to.bitkit.models

import to.bitkit.ext.URI_SCHEME
import to.bitkit.ext.isWebLink

/** pubky.app link limits from pubky-app-specs, as Paykit checks them when it publishes a profile. */
const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100
const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300

/** First printable ASCII code; lower codes are control characters. */
private const val ASCII_SPACE = 0x20

/** The ASCII delete control character. */
private const val ASCII_DELETE = 0x7F

/** Highest port `url::Url::parse` accepts. */
private const val MAX_PORT = 65_535

/** Characters `url::Url::parse` refuses in the host of a special URL, as WHATWG's forbidden domain code points. */
private const val FORBIDDEN_HOST_CHARS = " #%/:<>?@[\\]^|"

private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""")
private val SPECIAL_SCHEMES = setOf("http", "https", "ws", "wss", "ftp", "file")
private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""")

/** Why pubky.app would refuse a profile link, checked on the label and URL a profile save sends. */
enum class PubkyAppLinkError {
LABEL_EMPTY,
LABEL_TOO_LONG,
URL_TOO_LONG,
URL_INVALID;

val isLabelError: Boolean get() = this == LABEL_EMPTY || this == LABEL_TOO_LONG
}

/**
* The first rule pubky.app's publisher would refuse [label] and [url] for, after the normalization a profile save
* applies, or null when it accepts them. A blank URL is left to the caller; a label that is empty once on one line is
* reported last, so a URL error shows while the label is still blank. [webOnly] also requires an http(s) link, as a
* social v1 profile does.
*/
fun pubkyAppLinkError(label: String, url: String, webOnly: Boolean): PubkyAppLinkError? {
val title = label.singleLine()
if (title.codePointCount(0, title.length) > PUBKY_APP_LINK_TITLE_MAX_LENGTH) return PubkyAppLinkError.LABEL_TOO_LONG
if (url.isNotBlank()) {
val normalized = url.normalizedLinkUrl()?.takeIf { it.linkUrlParts() != null }
?: return PubkyAppLinkError.URL_INVALID
if (webOnly && !url.isWebLink()) return PubkyAppLinkError.URL_INVALID
if (normalized.codePointCount(0, normalized.length) > PUBKY_APP_LINK_URL_MAX_LENGTH) {
return PubkyAppLinkError.URL_TOO_LONG
}
}
if (title.isEmpty()) return PubkyAppLinkError.LABEL_EMPTY
return null
}

/** One line of text as pubky.app keeps it: control characters become spaces and the ends are trimmed. */
fun String.singleLine() = map { if (it.isISOControl()) ' ' else it }.joinToString("").trim()

/**
* This link as the full URL pubky.app needs, or null when pubky.app cannot hold it. Bitkit accepted links without a
* scheme (a site, an email address, a phone number), which gain one here.
*/
fun String.toPubkyAppLinkUrl(): String? = normalizedLinkUrl()?.takeIf {
it.codePointCount(0, it.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && it.linkUrlParts() != null
}

/**
* Paykit's social v1 link rule (`is_social_v1_web_uri`): a lowercase `http://` or `https://` prefix, no control or
* whitespace character, and a non-empty host, read up to the first `/`, `?` or `#`, after the last `@`, and up to `:`
* unless it starts with `[`. Social v1 drops other links on migration too.
*/
fun String.isSocialV1WebUri(): Boolean {
val rest = removePrefix("http://").takeIf { it != this } ?: removePrefix("https://").takeIf { it != this }
?: return false
if (any { it.code < ASCII_SPACE || it.code == ASCII_DELETE || it.isWhitespace() }) return false
val hostAndPort = rest.takeWhile { it !in "/?#" }.substringAfterLast('@')
val host = if (hostAndPort.startsWith('[')) hostAndPort else hostAndPort.substringBefore(':')
return host.isNotEmpty()
}

/** The lowercase scheme and the host of a URL; the host is empty for a scheme without one, such as `mailto`. */
class LinkUrlParts(val scheme: String, val host: String)

/**
* The scheme and host `url::Url::parse`, which Paykit validates links with, reads from this URL, or null when it
* would refuse it. A WHATWG-style check of what that parser rejects: a control character, a special URL (http, https,
* ws, wss, ftp) with an empty host, a forbidden host character or a port over 65535, and a host ending in an
* all-digit label that is not an IPv4 address (one to four numbers, as in `127.1`). Paths, queries and other
* schemes are accepted, as the parser accepts them.
*/
fun String.linkUrlParts(): LinkUrlParts? {
if (any { it.isISOControl() }) return null
val scheme = URI_SCHEME.find(this)?.value?.dropLast(1)?.lowercase() ?: return null
if (scheme !in SPECIAL_SCHEMES) return LinkUrlParts(scheme, host = "")
val authority = substring(scheme.length + 1).trimStart('/', '\\').takeWhile { it !in "/?#\\" }
val hostAndPort = authority.substringAfterLast('@')
val host = hostAndPort.hostPart() ?: return null
if (!hostAndPort.substring(host.length).isValidPort()) return null
if (scheme == "file") return LinkUrlParts(scheme, host)
if (host.isEmpty() || (!host.startsWith('[') && host.any { it in FORBIDDEN_HOST_CHARS })) return null
if (!host.isValidIpv4Ending()) return null
return LinkUrlParts(scheme, host.lowercase())
}

private fun String.hostPart(): String? {
if (!startsWith('[')) return substringBefore(':')
val end = indexOf(']').takeIf { it > 1 } ?: return null
val address = substring(1, end)
if (!address.all { it.isDigit() || it.lowercaseChar() in 'a'..'f' || it == ':' || it == '.' }) return null
return substring(0, end + 1)
}

private fun String.isValidPort(): Boolean {
if (isEmpty()) return true
val port = removePrefix(":").takeIf { startsWith(':') } ?: return false
if (!port.all { it in '0'..'9' }) return false
val digits = port.trimStart('0')
return digits.length <= MAX_PORT.toString().length && (digits.toIntOrNull() ?: 0) <= MAX_PORT
}

private fun String.isValidIpv4Ending(): Boolean {
val name = removeSuffix(".")
if (startsWith('[') || !name.substringAfterLast('.').all { it.isDigit() }) return true
val numbers = name.split('.').map { it.toLongOrNull() ?: return false }
if (numbers.size !in 1..4) return false
val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1
return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit
}

private fun String.normalizedLinkUrl(): String? {
val value = trim().takeIf { it.isNotEmpty() } ?: return null
val isPhone = value.isPhoneNumber()
if (!isPhone && value.any { it.isWhitespace() }) return null
val scheme = if (isPhone) null else URI_SCHEME.find(value)?.value?.dropLast(1)
return when {
scheme != null -> scheme.lowercase() + value.substring(scheme.length)
value.isEmailAddress() -> "mailto:$value"
isPhone -> "tel:" + value.filterNot { it in " -()." }
'.' in value && !value.startsWith('.') -> "https://$value"
else -> null
}
}

private fun String.isEmailAddress(): Boolean {
val parts = split('@')
return parts.size == 2 && parts[0].isNotEmpty() && '.' in parts[1] && '/' !in this
}

private fun String.isPhoneNumber(): Boolean {
val digits = count { it.isDigit() }
return (startsWith('+') || digits >= 7) && digits >= 5 && all { it in "+0123456789 -()." } && '+' !in drop(1) &&
!ISO_DATE.matches(this) && !IPV4.matches(this)
}
62 changes: 6 additions & 56 deletions app/src/main/java/to/bitkit/repositories/PubkyRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ import to.bitkit.ext.isPaykitTemporarilyUnavailable
import to.bitkit.ext.nowMs
import to.bitkit.ext.runSuspendCatching
import to.bitkit.models.HomegateResponse
import to.bitkit.models.PUBKY_APP_LINK_TITLE_MAX_LENGTH
import to.bitkit.models.PUBKY_APP_LINK_URL_MAX_LENGTH
import to.bitkit.models.PubkyAuthClaim
import to.bitkit.models.PubkyAuthRequest
import to.bitkit.models.PubkyAuthRequestError
Expand All @@ -73,14 +75,16 @@ import to.bitkit.models.PubkyProfileLink
import to.bitkit.models.PubkyPublicKeyFormat
import to.bitkit.models.PubkySessionBackupKind
import to.bitkit.models.PubkySessionBackupV1
import to.bitkit.models.isSocialV1WebUri
import to.bitkit.models.singleLine
import to.bitkit.models.takeCodePoints
import to.bitkit.models.toPubkyAppLinkUrl
import to.bitkit.services.PaykitReadLane
import to.bitkit.services.PaykitReadTimeoutError
import to.bitkit.services.PubkyService
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import java.io.ByteArrayOutputStream
import java.net.URI
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
Expand Down Expand Up @@ -211,11 +215,6 @@ class PubkyRepo @Inject constructor(
private const val PUBKY_APP_NAME_MAX_LENGTH = 50
private const val PUBKY_APP_BIO_MAX_LENGTH = 160
private const val PUBKY_APP_LINKS_MAX_COUNT = 5
private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""")
private val WEB_SCHEMES = setOf("http", "https", "ws", "wss", "ftp")
private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""")
private const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100
private const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300
private const val PUBKY_APP_AVATAR_MAX_BYTES = 5_242_880uL
}

Expand Down Expand Up @@ -1463,7 +1462,7 @@ class PubkyRepo @Inject constructor(
links = links
.mapNotNull { link ->
val title = link.label.singleLine().takeIf { it.isNotEmpty() } ?: return@mapNotNull null
val url = link.url.toPubkyAppLinkUrl()?.takeIf { it.isSocialV1WebUrl() } ?: return@mapNotNull null
val url = link.url.toPubkyAppLinkUrl()?.takeIf { it.isSocialV1WebUri() } ?: return@mapNotNull null
PubkyProfileLink(label = title.takeCodePoints(PUBKY_APP_LINK_TITLE_MAX_LENGTH), url = url)
}
.take(PUBKY_APP_LINKS_MAX_COUNT),
Expand Down Expand Up @@ -1573,55 +1572,6 @@ class PubkyRepo @Inject constructor(
private fun Throwable.isConcurrentUpdate() =
generateSequence(this) { it.cause }.any { it is PaykitException.ConcurrentUpdate }

private fun String.singleLine() = map { if (it.isISOControl()) ' ' else it }.joinToString("").trim()

private fun String.toPubkyAppLinkUrl(): String? {
val value = trim().takeIf { it.isNotEmpty() } ?: return null
val isPhone = value.isPhoneNumber()
if (!isPhone && value.any { it.isWhitespace() }) return null
val scheme = if (isPhone) null else runCatching { URI(value).scheme }.getOrNull()
val url = when {
scheme != null -> scheme.lowercase() + value.substring(scheme.length)
value.isEmailAddress() -> "mailto:$value"
isPhone -> "tel:" + value.filterNot { it in " -()." }
'.' in value && !value.startsWith('.') -> "https://$value"
else -> return null
}
val parsed = runCatching { URI(url) }.getOrNull()
val valid = url.codePointCount(0, url.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH &&
parsed?.scheme != null && parsed.hasValidHost()
return url.takeIf { valid }
}

/**
* Paykit's URL parser reads a web URL's host that ends in an all-digit label as an IPv4 address (one to four
* numbers, as in `127.1`) and rejects it when it is not one; other schemes keep such hosts as they are.
*/
private fun URI.hasValidHost(): Boolean {
if (scheme?.lowercase() !in WEB_SCHEMES) return true
// java.net.URI leaves the host null when the name is not a valid hostname, so fall back to the authority.
val host = host ?: rawAuthority?.substringAfterLast('@')?.substringBefore(':') ?: return true
if (!host.substringAfterLast('.').all { it.isDigit() }) return true
val numbers = host.split('.').map { it.toLongOrNull() ?: return false }
if (numbers.size !in 1..4) return false
val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1
return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit
}

private fun String.isEmailAddress(): Boolean {
val parts = split('@')
return parts.size == 2 && parts[0].isNotEmpty() && '.' in parts[1] && '/' !in this
}

private fun String.isPhoneNumber(): Boolean {
val digits = count { it.isDigit() }
return (startsWith('+') || digits >= 7) && digits >= 5 && all { it in "+0123456789 -()." } && '+' !in drop(1) &&
!ISO_DATE.matches(this) && !IPV4.matches(this)
}

/** Social v1's own link rule: a lowercase `http://` or `https://` prefix; it drops other links on migration too. */
private fun String.isSocialV1WebUrl() = startsWith("http://") || startsWith("https://")

private fun String.isPaykitStorage() = "/pub/paykit/" in this

private fun String.isPubkyAppFile() =
Expand Down
Loading