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
46 changes: 46 additions & 0 deletions app/src/main/java/to/bitkit/models/PubkyAuthRequest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ sealed class PubkyAuthRequestError(cause: Throwable? = null) : AppError(cause =
data object DuplicateBitkitClaim : PubkyAuthRequestError()
data class UnsupportedBitkitClaim(val value: String) : PubkyAuthRequestError()
data object InvalidBitkitClaimCapabilities : PubkyAuthRequestError()
data class SignerMismatch(val expectedSigner: String) : PubkyAuthRequestError()
}

@Immutable
Expand Down Expand Up @@ -130,6 +131,7 @@ data class PubkyAuthRequest(
val homeserverPublicKey: String? = null,
val signupToken: String? = null,
val authorizationUrl: String? = rawUrl,
val expectedSigner: String? = null,
) {
val isSignup: Boolean
get() = isSignupUrl(rawUrl)
Expand All @@ -146,6 +148,48 @@ data class PubkyAuthRequest(
val relayDisplayUrl: String? get() = displayRelay(relay)

companion object {
/** Query parameter naming the only pubky that may approve a grant sign-in. */
private const val EXPECTED_SIGNER_PARAMETER = "spk"

/** A 32-byte key in canonical z-base-32: 52 symbols, the last one carrying a single bit. */
private val CANONICAL_Z32_KEY = Regex("[ybndrfg8ejkmcpqxot1uwisza345h769]{51}[yo]")

/** Length of a z-base-32 key carrying the `pubky` prefix. */
private const val PREFIXED_KEY_LENGTH = 57

/**
* Reads the pubky a sign-in request must be approved with. Absent is fine; a repeated value or anything other
* than a bare canonical z-base-32 key makes the request invalid, as in the Pubky SDK parser for `signin_grant`.
* Only signup requests ignore the parameter, so a sign-in this parser reads differently from the SDK is still
* held to it. Upstream reads `spk` for `signin_grant` alone (pubky/pubky-homeserver at d95161af3e:
* `pubky-sdk/src/actors/auth/deep_links/signin_grant.rs:106` is the only caller of `parse_expected_signer`,
* `deep_link.rs:211` tests that `signin` and `signup_grant` ignore it, `docs/AUTH.md:81`).
*/
fun parseExpectedSigner(rawUrl: String): Result<String?> = runCatching {
val uri = URI(rawUrl)
if (uri.isSignupRequest()) return@runCatching null
val values = uri.rawQuery.orEmpty()
.split("&")
.filter { it.isNotEmpty() }
.map { it.split("=", limit = 2) }
.filter { decodeQueryComponent(it.first()) == EXPECTED_SIGNER_PARAMETER }
.map { decodeQueryComponent(it.getOrElse(1) { "" }) }
require(values.size <= 1) { "Duplicate Pubky auth parameter: $EXPECTED_SIGNER_PARAMETER" }
values.singleOrNull()?.also {
require(CANONICAL_Z32_KEY.matches(it)) { "Malformed Pubky auth parameter: $EXPECTED_SIGNER_PARAMETER" }
}
}.fold(
onSuccess = { Result.success(it) },
onFailure = { Result.failure(PubkyAuthRequestError.InvalidUrl(it)) },
)

/** Whether [publicKey], bare or with the `pubky` prefix, may approve a request naming [expectedSigner]. */
fun isExpectedSigner(expectedSigner: String?, publicKey: String): Boolean {
if (expectedSigner == null) return true
val isPrefixed = publicKey.length == PREFIXED_KEY_LENGTH && publicKey.startsWith("pubky")
return expectedSigner == if (isPrefixed) publicKey.removePrefix("pubky") else publicKey
}

private val RELAY_SCHEMES = setOf("http", "https")

/** A relay host as the Pubky SDK's URL parser would keep it, with an optional port. */
Expand Down Expand Up @@ -259,6 +303,7 @@ data class PubkyAuthRequest(
signupToken: String? = null,
authorizationUrl: String? = rawUrl,
): Result<PubkyAuthRequest> = parseBitkitClaim(rawUrl, capabilities).mapCatching { bitkitClaim ->
val expectedSigner = parseExpectedSigner(rawUrl).getOrThrow()
if (relay.isNotEmpty() && displayRelay(relay) == null) {
throw PubkyAuthRequestError.InvalidUrl(IllegalArgumentException("Unreadable Pubky auth relay"))
}
Expand All @@ -274,6 +319,7 @@ data class PubkyAuthRequest(
homeserverPublicKey = homeserverPublicKey,
signupToken = signupToken,
authorizationUrl = authorizationUrl,
expectedSigner = expectedSigner,
)
}

Expand Down
34 changes: 34 additions & 0 deletions app/src/main/java/to/bitkit/repositories/PubkyRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2054,6 +2054,7 @@ class PubkyRepo @Inject constructor(

suspend fun parseAuthUrl(authUrl: String): Result<PubkyAuthRequest> = runSuspendCatching {
withContext(ioDispatcher) {
validatedExpectedSigner(authUrl)
if (PubkyAuthRequest.isSignupUrl(authUrl) && !PubkyAuthRequest.isGrantSignupUrl(authUrl)) {
val request = PubkyAuthRequest.parseSignup(authUrl).getOrThrow()
pubkyService.validateSignupRequest(
Expand Down Expand Up @@ -2148,6 +2149,7 @@ class PubkyRepo @Inject constructor(
val secretKeyHex = requireNotNull(activeSecretKeyHex()) {
"No secret key available — use Ring to manage authorizations"
}
requireExpectedSigner(authUrl, secretKeyHex)
pubkyService.approveAuth(authUrl, expectedCapabilities, approvedClientId, secretKeyHex)
}
}
Expand All @@ -2165,6 +2167,7 @@ class PubkyRepo @Inject constructor(
val secretKeyHex = requireNotNull(activeSecretKeyHex()) {
"No secret key available — use Ring to manage authorizations"
}
requireExpectedSigner(authUrl, secretKeyHex)
pubkyService.approveAuthWithCompanionClaim(
authUrl = authUrl,
expectedCapabilities = PubkyAuthClaim.REQUIRED_CAPABILITIES,
Expand All @@ -2179,6 +2182,37 @@ class PubkyRepo @Inject constructor(
}
}

/** Fails when [authUrl] names a pubky other than the one that would sign it, before anything is prepared. */
suspend fun checkExpectedSigner(authUrl: String): Result<Unit> = runSuspendCatching {
withContext(ioDispatcher) {
val secretKeyHex = requireNotNull(activeSecretKeyHex()) {
"No secret key available — use Ring to manage authorizations"
}
requireExpectedSigner(authUrl, secretKeyHex)
}
}

/**
* The pubky [authUrl] must be approved with, or null when it names none or any part of the request is invalid,
* so an unusable link is never reported as meant for another pubky.
*/
suspend fun validExpectedSigner(authUrl: String): String? = parseAuthUrl(authUrl).getOrNull()?.expectedSigner

private suspend fun validatedExpectedSigner(authUrl: String): String? {
val expectedSigner = PubkyAuthRequest.parseExpectedSigner(authUrl).getOrThrow() ?: return null
runSuspendCatching { pubkyService.validatePublicKey(expectedSigner) }
.onFailure { throw PubkyAuthRequestError.InvalidUrl(it) }
return expectedSigner
}

private suspend fun requireExpectedSigner(authUrl: String, secretKeyHex: String) {
val expectedSigner = validatedExpectedSigner(authUrl) ?: return
val signer = pubkyService.publicKeyFromSecret(secretKeyHex)
if (!PubkyAuthRequest.isExpectedSigner(expectedSigner, signer)) {
throw PubkyAuthRequestError.SignerMismatch(expectedSigner)
}
}

// endregion

// region Wake
Expand Down
7 changes: 7 additions & 0 deletions app/src/main/java/to/bitkit/services/PubkyService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import com.synonym.paykit.PubkyAuthCompanionClaim
import com.synonym.paykit.PubkyProfileSnapshot
import com.synonym.paykit.PubkyProfileUpdate
import com.synonym.paykit.PubkySessionBootstrapResult
import com.synonym.paykit.normalizePubkyPublicKey
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.withTimeoutOrNull
Expand Down Expand Up @@ -147,6 +148,12 @@ class PubkyService @Inject constructor(
Unit
}

/** Throws unless [publicKey] decodes to an Ed25519 point; `PaykitPublicKeys.normalize` checks only its spelling. */
suspend fun validatePublicKey(publicKey: String): Unit = ServiceQueue.PUBKY.background {
normalizePubkyPublicKey(publicKey)
Unit
}

suspend fun approveAuth(
authUrl: String,
expectedCapabilities: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,20 @@ class PubkyAuthApprovalViewModel @Inject constructor(
}?.joinToString(context.getString(R.string.profile__auth_approval_services_separator)) ?: unknownService
val usdtEnabled = usdtPreferences.enabled.first()
val identityPublicKey = pubkyRepo.publicKey.value ?: pubkyRepo.localIdentityPublicKey()
val expectedSigner = request.expectedSigner
if (expectedSigner != null && identityPublicKey != null &&
!PubkyAuthRequest.isExpectedSigner(expectedSigner, identityPublicKey)
) {
Logger.warn("Refused auth request for another pubky", context = TAG)
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.profile__auth_error_title),
description = PubkyAuthRequestError.SignerMismatch(expectedSigner)
.localizedPubkyAuthMessage(context),
)
_effects.emit(PubkyAuthApprovalEffect.Dismiss)
return@launch
}
val profile = approvalProfile(identityPublicKey)
_uiState.update {
it.copy(
Expand Down Expand Up @@ -279,6 +293,12 @@ class PubkyAuthApprovalViewModel @Inject constructor(
request: PubkyAuthRequest,
authUrl: String,
): Boolean {
if (request.expectedSigner != null) {
pubkyRepo.checkExpectedSigner(authUrl).onFailure {
handleApprovalFailure(it, authUrl)
return false
}
}
val endpoint = runSuspendCatching {
validatedUsdtEndpoint(request)
}.getOrElse {
Expand Down
10 changes: 10 additions & 0 deletions app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,19 @@ import to.bitkit.models.PubkyAuthRequestError
import to.bitkit.repositories.WatchOnlyAccountError
import to.bitkit.services.PubkyRingAuthTimeoutError

/** Characters shown from each end of the pubky a request names. */
private const val SIGNER_EDGE_LENGTH = 4

fun Throwable.localizedPubkyAuthMessage(context: Context): String? {
var current: Throwable? = this
while (current != null) {
if (current is PubkyAuthRequestError.SignerMismatch) {
val signer = current.expectedSigner
return context.getString(
R.string.profile__auth_error_other_pubky,
"${signer.take(SIGNER_EDGE_LENGTH)}...${signer.takeLast(SIGNER_EDGE_LENGTH)}",
)
}
val messageResource = current.pubkyAuthMessageResource()
if (messageResource != null) {
return context.getString(messageResource)
Expand Down
15 changes: 15 additions & 0 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ import to.bitkit.models.PaykitAmountError
import to.bitkit.models.PaykitAsset
import to.bitkit.models.PaykitRequestPayment
import to.bitkit.models.PubkyAuthRequest
import to.bitkit.models.PubkyAuthRequestError
import to.bitkit.models.PubkyContactLink
import to.bitkit.models.PubkyProfile
import to.bitkit.models.PubkyPublicKeyFormat
Expand Down Expand Up @@ -10866,6 +10867,20 @@ class AppViewModel @Inject constructor(
return
}

val expectedSigner = pubkyRepo.validExpectedSigner(authUrl)
Comment thread
jvsena42 marked this conversation as resolved.
Resolved
val publicKey = pubkyRepo.publicKey.value
if (expectedSigner != null && publicKey != null &&
!PubkyAuthRequest.isExpectedSigner(expectedSigner, publicKey)
) {
Logger.warn("Refused auth request for another pubky", context = TAG)
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.profile__auth_error_title),
description = PubkyAuthRequestError.SignerMismatch(expectedSigner).localizedPubkyAuthMessage(context),
)
return
}

if (!pubkyRepo.hasSecretKey()) {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-ar/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,7 @@
<string name="profile__auth_approval_details">التفاصيل</string>
<string name="profile__auth_approval_ok">حسنًا</string>
<string name="profile__auth_approval_relay">المُرحّل</string>
<string name="profile__auth_error_other_pubky">هذا الطلب موجّه إلى %1$s، وليس إلى pubky هذه المحفظة.</string>
<string name="profile__create_nav_title">إنشاء ملف شخصي</string>
<string name="profile__nav_title">الملف الشخصي</string>
<string name="profile__retry_load">حاول مرة أخرى</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-b+es+419/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,7 @@
<string name="profile__auth_approval_details">Detalles</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_approval_title">Autorizar</string>
<string name="profile__auth_error_other_pubky">Esta solicitud es para %1$s, no para el pubky de esta billetera.</string>
<string name="profile__create_nav_title">Crear perfil</string>
<string name="profile__edit_nav_title">Editar Perfil</string>
<string name="profile__nav_title">Perfil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-ca/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,7 @@
<string name="profile__add_tag">Afegeix etiqueta</string>
<string name="profile__auth_approval_details">Detalls</string>
<string name="profile__auth_approval_relay">Relé</string>
<string name="profile__auth_error_other_pubky">Aquesta sol·licitud és per a %1$s, no per al pubky d\'aquesta cartera.</string>
<string name="profile__create_nav_title">Crear perfil</string>
<string name="profile__edit_nav_title">Editar perfil</string>
<string name="profile__nav_title">Perfil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-cs/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,7 @@
<string name="profile__auth_approval_details">Podrobnosti</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_approval_title">Autorizovat</string>
<string name="profile__auth_error_other_pubky">Tento požadavek je určen pro %1$s, ne pro pubky této peněženky.</string>
<string name="profile__create_nav_title">Vytvořit profil</string>
<string name="profile__edit_nav_title">Upravit profil</string>
<string name="profile__nav_title">Profil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@
<string name="profile__auth_approval_authorize">Autorisieren Sie</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_approval_title">Autorisieren Sie</string>
<string name="profile__auth_error_other_pubky">Diese Anfrage ist für %1$s bestimmt, nicht für den Pubky dieses Wallets.</string>
<string name="profile__create_nav_title">Profil erstellen</string>
<string name="profile__edit_nav_title">Profil bearbeiten</string>
<string name="profile__nav_title">Profil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-el/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,7 @@
<string name="profile__auth_approval_details">Λεπτομέρειες</string>
<string name="profile__auth_approval_ok">ΟΚ</string>
<string name="profile__auth_approval_relay">Αναμεταδότης</string>
<string name="profile__auth_error_other_pubky">Αυτό το αίτημα προορίζεται για το %1$s, όχι για το pubky αυτού του πορτοφολιού.</string>
<string name="profile__create_nav_title">Δημιουργία προφίλ</string>
<string name="profile__nav_title">Προφίλ</string>
<string name="profile__retry_load">Προσπαθήστε Ξανά</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-es-rES/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@
<string name="profile__add_tag">Añadir etiqueta</string>
<string name="profile__auth_approval_details">Detalles</string>
<string name="profile__auth_approval_relay">Relé</string>
<string name="profile__auth_error_other_pubky">Esta solicitud es para %1$s, no para el pubky de este monedero.</string>
<string name="profile__create_nav_title">Crear perfil</string>
<string name="profile__edit_nav_title">Editar Perfil</string>
<string name="profile__nav_title">Perfil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@
<string name="profile__add_tag">Añadir etiqueta</string>
<string name="profile__auth_approval_details">Detalles</string>
<string name="profile__auth_approval_relay">Relé</string>
<string name="profile__auth_error_other_pubky">Esta solicitud es para %1$s, no para el pubky de este monedero.</string>
<string name="profile__create_nav_title">Crear perfil</string>
<string name="profile__edit_nav_title">Editar Perfil</string>
<string name="profile__nav_title">Perfil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@
<string name="profile__auth_approval_details">Détails</string>
<string name="profile__auth_approval_relay">Relais</string>
<string name="profile__auth_approval_title">Autoriser</string>
<string name="profile__auth_error_other_pubky">Cette demande est destinée à %1$s, pas au pubky de ce portefeuille.</string>
<string name="profile__create_nav_title">Créer un profil</string>
<string name="profile__edit_nav_title">Modifier le profil</string>
<string name="profile__nav_title">Profil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-it/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@
<string name="profile__add_tag">Aggiungi Tag</string>
<string name="profile__auth_approval_details">Dettagli</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_error_other_pubky">Questa richiesta è per %1$s, non per il pubky di questo portafoglio.</string>
<string name="profile__create_nav_title">Crea Profilo</string>
<string name="profile__edit_nav_title">Modifica Profilo</string>
<string name="profile__nav_title">Profilo</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-nl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,7 @@
<string name="profile__add_link_note">Let op: Iedere link die u toevoegt is openbaar beschikbaar.</string>
<string name="profile__add_tag">Tag toevoegen</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_error_other_pubky">Dit verzoek is voor %1$s, niet voor de pubky van deze wallet.</string>
<string name="profile__create_nav_title">Profiel aanmaken</string>
<string name="profile__edit_nav_title">Profiel Bewerken</string>
<string name="profile__nav_title">Profiel</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-pl/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@
<string name="profile__auth_approval_details">Szczegóły</string>
<string name="profile__auth_approval_relay">Przekaźnik</string>
<string name="profile__auth_approval_title">Autoryzuj</string>
<string name="profile__auth_error_other_pubky">To żądanie jest przeznaczone dla %1$s, a nie dla pubky tego portfela.</string>
<string name="profile__create_nav_title">Utwórz profil</string>
<string name="profile__edit_nav_title">Edytuj profil</string>
<string name="profile__nav_title">Profil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-pt-rBR/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,7 @@
<string name="profile__auth_approval_details">Detalhes</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_approval_title">Autorizar</string>
<string name="profile__auth_error_other_pubky">Esta solicitação é para %1$s, não para o pubky desta carteira.</string>
<string name="profile__create_nav_title">Criar Perfil</string>
<string name="profile__edit_nav_title">Editar perfil</string>
<string name="profile__nav_title">Perfil</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-pt/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,7 @@
<string name="profile__add_tag">Adicionar Tag</string>
<string name="profile__auth_approval_details">Detalhes</string>
<string name="profile__auth_approval_relay">Relay</string>
<string name="profile__auth_error_other_pubky">Este pedido destina-se a %1$s, não ao pubky desta carteira.</string>
<string name="profile__create_nav_title">Criar Perfil</string>
<string name="profile__nav_title">Perfil</string>
<string name="profile__retry_load">Tente novamente</string>
Expand Down
Loading
Loading