Sign in with Skysparkle to get the access key

The key field now starts a browser sign-in at skysparkle.cc/app/connect
(PKCE). The site returns to cc.skysparkle.sparkledns://connect with a
one-time code, and the app exchanges it for a new key. Pasting a key by
hand still works.

Remove the Gitea templates; the project lives on GitHub.
This commit is contained in:
2026-11-18 14:11:48 +02:00
parent a6f22ddfb2
commit 005768f18a
18 changed files with 355 additions and 140 deletions
@@ -57,6 +57,8 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppLogo.preload(this)
// Opened by the browser at the end of the Skysparkle sign-in (not again after rotation)
if (savedInstanceState == null) handleSignIn(intent)
enableEdgeToEdge()
setContent {
MaterialTheme(colorScheme = AppColors) {
@@ -70,6 +72,27 @@ class MainActivity : ComponentActivity() {
}
}
}
// singleTask: the sign-in callback reaches the running activity instead of opening a second one
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleSignIn(intent)
}
// Back from the browser without finishing the sign-in. A real callback arrives in
// onNewIntent, which always runs before this
override fun onResume() {
super.onResume()
SkysparkleSignIn.cancelWaiting()
}
private fun handleSignIn(intent: Intent?) {
val uri = intent?.data
if (intent?.action == Intent.ACTION_VIEW && SkysparkleSignIn.isCallback(uri)) {
SkysparkleSignIn.handle(this, uri!!)
}
}
}
internal class TestResult(val ok: Boolean, val text: String)
@@ -66,6 +66,12 @@ fun OnboardingScreen(onDone: () -> Unit) {
onDone()
}
// Signed in from the guide: the key is saved, nothing is left to do here
SignInResult { key ->
keyInput = key
finish(useKey = true)
}
BackHandler(enabled = page > 0) { page-- }
Box(
@@ -129,7 +135,6 @@ fun OnboardingScreen(onDone: () -> Unit) {
value = keyInput,
valid = keyValid,
onChange = { keyInput = it },
onGetKey = { openUrl(context, SkysparkleKey.SIGNUP_URL) },
)
}
}
@@ -63,7 +63,6 @@ object Providers {
// keys; the server answers only /dns/<key>, there is no shared public address.
object SkysparkleKey {
const val BASE_URL = "https://skysparkle.cc/dns/"
const val SIGNUP_URL = "https://skysparkle.cc/login#register"
private val KEY = Regex("^[A-Za-z0-9_-]{24}$")
private val IN_URL = Regex("/dns/([A-Za-z0-9_-]{24})(?:[/?#].*)?$")
@@ -1,5 +1,6 @@
package cc.skysparkle.sparkledns
import android.widget.Toast
import androidx.annotation.DrawableRes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
@@ -21,12 +22,15 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -93,6 +97,13 @@ fun SettingsScreen(
testResult = null
}
// Signed in from the key field: the key is already saved, show it and select the server
SignInResult { key ->
keyInput = key
selected = Providers.DEFAULT_ID
testResult = null
}
fun runTest() {
val provider = prefs.resolve()
testing = true
@@ -136,7 +147,6 @@ fun SettingsScreen(
prefs.skysparkleKey = SkysparkleKey.parse(it) ?: it.trim()
testResult = null
},
onGetKey = { openUrl(context, SkysparkleKey.SIGNUP_URL) },
)
}
}
@@ -269,14 +279,30 @@ fun SettingsScreen(
}
}
// Access key for the Skysparkle server, with a link to the account page where keys are made
// Access key for the Skysparkle server: sign in to get it automatically, or paste one by hand
@Composable
internal fun KeyField(value: String, valid: Boolean, onChange: (String) -> Unit, onGetKey: () -> Unit, modifier: Modifier = Modifier) {
internal fun KeyField(value: String, valid: Boolean, onChange: (String) -> Unit, modifier: Modifier = Modifier) {
val context = LocalContext.current
val signIn by SkysparkleSignIn.state.collectAsStateWithLifecycle()
val working = signIn == SkysparkleSignIn.State.Waiting || signIn == SkysparkleSignIn.State.Exchanging
val showError = value.isNotBlank() && !valid
Column(
modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Button(
onClick = { SkysparkleSignIn.start(context) },
enabled = !working,
shape = RoundedCornerShape(14.dp),
modifier = Modifier.fillMaxWidth(),
) {
if (working) {
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp, color = LocalContentColor.current)
Spacer(Modifier.width(10.dp))
}
Text(stringResource(if (working) R.string.sign_in_working else if (valid) R.string.sign_in_again else R.string.sign_in))
}
Text(stringResource(R.string.key_or_paste), color = Palette.Fg3, fontSize = 12.sp, modifier = Modifier.padding(top = 6.dp))
OutlinedTextField(
value = value,
onValueChange = onChange,
@@ -292,8 +318,26 @@ internal fun KeyField(value: String, valid: Boolean, onChange: (String) -> Unit,
color = if (showError) Palette.Blocked else Palette.Fg3,
fontSize = 12.sp,
)
OutlinedButton(onClick = onGetKey, shape = RoundedCornerShape(14.dp)) {
Text(stringResource(R.string.key_get))
}
}
// Result of the Skysparkle sign-in, shown once on the screen that started it
@Composable
internal fun SignInResult(onKey: (String) -> Unit) {
val context = LocalContext.current
val signIn by SkysparkleSignIn.state.collectAsStateWithLifecycle()
LaunchedEffect(signIn) {
when (val s = signIn) {
is SkysparkleSignIn.State.Done -> {
onKey(s.key)
Toast.makeText(context, R.string.sign_in_done, Toast.LENGTH_SHORT).show()
SkysparkleSignIn.consume()
}
is SkysparkleSignIn.State.Failed -> {
Toast.makeText(context, s.message, Toast.LENGTH_LONG).show()
SkysparkleSignIn.consume()
}
else -> Unit
}
}
}
@@ -0,0 +1,172 @@
package cc.skysparkle.sparkledns
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Base64
import android.util.Log
import androidx.annotation.StringRes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.security.MessageDigest
import java.security.SecureRandom
// Sign-in with a Skysparkle account: the app gets its access key without copying it by hand.
//
// OAuth for native apps (RFC 8252) with PKCE (RFC 7636): the account page opens in the browser,
// so the password never passes through the app. After "Connect" the site sends the browser to
// cc.skysparkle.sparkledns://connect?code=…&state=…, and the app trades the one-time code for a
// new key. Only this app knows the verifier, so a code caught by another app is useless.
object SkysparkleSignIn {
private const val CONNECT_URL = "https://skysparkle.cc/app/connect"
private const val TOKEN_URL = "https://skysparkle.cc/api/app/token"
private const val SCHEME = "cc.skysparkle.sparkledns"
private const val HOST = "connect"
// The browser step must be finished within this time (the site keeps codes for 5 minutes)
private const val PENDING_TTL_MS = 30 * 60_000L
sealed interface State {
data object Idle : State
data object Waiting : State
data object Exchanging : State
data class Done(val key: String) : State
data class Failed(@StringRes val message: Int) : State
}
private val _state = MutableStateFlow<State>(State.Idle)
val state: StateFlow<State> = _state.asStateFlow()
// Not tied to a screen: rotating or leaving the screen must not cancel the exchange
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
fun isCallback(uri: Uri?): Boolean = uri?.scheme == SCHEME && uri.host == HOST
// Opens the account page. Verifier and state are kept on disk: the system may stop the app
// while the browser is in front.
fun start(context: Context) {
val verifier = randomToken(32)
val state = randomToken(24)
pending(context).edit()
.putString(P_VERIFIER, verifier)
.putString(P_STATE, state)
.putLong(P_AT, System.currentTimeMillis())
.apply()
val url = Uri.parse(CONNECT_URL).buildUpon()
.appendQueryParameter("challenge", challengeOf(verifier))
.appendQueryParameter("state", state)
.appendQueryParameter("device", Build.MODEL.take(40))
.build()
_state.value = State.Waiting
try {
context.startActivity(Intent(Intent.ACTION_VIEW, url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} catch (e: RuntimeException) {
Log.w("SparkleDNS", "Cannot open the sign-in page", e)
_state.value = State.Failed(R.string.no_browser)
}
}
// The browser came back to the app: check state, then trade the code for a key.
fun handle(context: Context, uri: Uri) {
val app = context.applicationContext
val p = pending(app)
val state = p.getString(P_STATE, null)
val verifier = p.getString(P_VERIFIER, null)
val fresh = System.currentTimeMillis() - p.getLong(P_AT, 0) < PENDING_TTL_MS
if (state == null || verifier == null || !fresh || uri.getQueryParameter("state") != state) {
// A link that this app did not start, or an old one: ignore it
if (state == null || !fresh) _state.value = State.Idle
return
}
p.edit().clear().apply()
if (uri.getQueryParameter("error") != null) {
_state.value = State.Idle // "Cancel" on the site
return
}
val code = uri.getQueryParameter("code")
if (code.isNullOrEmpty()) {
_state.value = State.Failed(R.string.sign_in_failed)
return
}
_state.value = State.Exchanging
scope.launch {
_state.value = when (val r = exchange(code, verifier)) {
is Result.Key -> {
Prefs(app).apply {
skysparkleKey = r.key
providerId = Providers.DEFAULT_ID
}
State.Done(r.key)
}
is Result.Error -> State.Failed(r.message)
}
}
}
// The screen showed the result; the next sign-in starts clean
fun consume() {
val s = _state.value
if (s is State.Done || s is State.Failed) _state.value = State.Idle
}
// Returning from the browser without finishing (back button) should not leave a spinner
fun cancelWaiting() {
if (_state.value == State.Waiting) _state.value = State.Idle
}
private sealed interface Result {
class Key(val key: String) : Result
class Error(@StringRes val message: Int) : Result
}
private fun exchange(code: String, verifier: String): Result {
val body = JSONObject().put("code", code).put("verifier", verifier).toString()
.toRequestBody("application/json".toMediaType())
val request = Request.Builder().url(TOKEN_URL).post(body).build()
return try {
Http.client.newCall(request).execute().use { response ->
val json = runCatching { JSONObject(response.body.string()) }.getOrNull()
val key = json?.optString("key").orEmpty()
when {
response.isSuccessful && SkysparkleKey.parse(key) != null -> Result.Key(key)
json?.optString("error") == "verify_email_first" -> Result.Error(R.string.sign_in_verify)
json?.optString("error") == "invalid_grant" -> Result.Error(R.string.sign_in_expired)
json?.optString("error") == "account_suspended" -> Result.Error(R.string.sign_in_suspended)
else -> Result.Error(R.string.sign_in_failed)
}
}
} catch (e: IOException) {
Log.w("SparkleDNS", "Key exchange failed", e)
Result.Error(R.string.sign_in_network)
}
}
private fun pending(context: Context) =
context.applicationContext.getSharedPreferences("sign_in", Context.MODE_PRIVATE)
private val random = SecureRandom()
private fun randomToken(bytes: Int): String =
b64url(ByteArray(bytes).also(random::nextBytes))
private fun challengeOf(verifier: String): String =
b64url(MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII)))
private fun b64url(data: ByteArray): String =
Base64.encodeToString(data, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
private const val P_VERIFIER = "verifier"
private const val P_STATE = "state"
private const val P_AT = "at"
}