Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(connectors): make the OAuth framework provider-generic

Durganshu Mishra3a8e1f097975
diff --git a/app/src/main/java/com/gotcha/connectors/ToolRouter.kt b/app/src/main/java/com/gotcha/connectors/ToolRouter.kt
new file mode 100644
index 0000000..7377899
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/ToolRouter.kt
@@ -0,0 +1,20 @@
+package com.gotcha.connectors
+
+import com.gotcha.tools.ToolResult
+import kotlinx.serialization.json.JsonObject
+
+/**
+ * A connector-backed handler for a group of tools. Routers own the tools whose
+ * implementation depends on connector credentials (email, tasks, calendar,
+ * Notion); the schemas still live in [com.gotcha.tools.ToolDefinitions] and the
+ * agent-mode gating still lives in [com.gotcha.tools.ToolRegistry].
+ *
+ * [ConnectorRegistry.toolHandler] resolves a tool name to the owning router, and
+ * `ToolExecutor.dispatch` consults it before its own `when`.
+ */
+interface ToolRouter {
+ /** Tool names this router claims. Must be disjoint from every other router. */
+ val toolNames: Set<String>
+
+ suspend fun execute(name: String, args: JsonObject): ToolResult
+}
diff --git a/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt b/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt
index 31cebc8..030c12d 100644
--- a/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt
+++ b/app/src/main/java/com/gotcha/connectors/oauth/OAuth2Helper.kt
@@ -19,7 +19,12 @@ data class OAuth2Config(
val authUrl: String,
val tokenUrl: String,
val clientId: String,
- val clientSecret: String,
+ /**
+ * Null/blank for public clients that authenticate with PKCE only (e.g. a
+ * Microsoft Entra "Mobile and desktop applications" registration). The
+ * client_secret form field is then omitted entirely — Entra rejects it.
+ */
+ val clientSecret: String?,
val scopes: List<String>,
val extraAuthParams: Map<String, String> = emptyMap()
)
@@ -82,7 +87,7 @@ class OAuth2Helper(
.add("code", code)
.add("redirect_uri", redirectUri)
.add("client_id", cfg.clientId)
- .add("client_secret", cfg.clientSecret)
+ .addClientSecret(cfg)
.add("code_verifier", codeVerifier)
.build()
return requestToken(cfg.tokenUrl, form, currentRefreshToken = null)
@@ -93,11 +98,15 @@ class OAuth2Helper(
.add("grant_type", "refresh_token")
.add("refresh_token", refreshToken)
.add("client_id", cfg.clientId)
- .add("client_secret", cfg.clientSecret)
+ .addClientSecret(cfg)
.build()
return requestToken(cfg.tokenUrl, form, currentRefreshToken = refreshToken)
}
+ /** Adds client_secret only for confidential clients; public clients must omit it. */
+ private fun FormBody.Builder.addClientSecret(cfg: OAuth2Config): FormBody.Builder =
+ cfg.clientSecret?.takeIf { it.isNotBlank() }?.let { add("client_secret", it) } ?: this
+
private suspend fun requestToken(
tokenUrl: String,
form: FormBody,
diff --git a/app/src/main/java/com/gotcha/connectors/google/GoogleOAuthFlow.kt b/app/src/main/java/com/gotcha/connectors/oauth/OAuthConnectFlow.kt
similarity index 60%
rename from app/src/main/java/com/gotcha/connectors/google/GoogleOAuthFlow.kt
rename to app/src/main/java/com/gotcha/connectors/oauth/OAuthConnectFlow.kt
index 6339da3..f8562ad 100644
--- a/app/src/main/java/com/gotcha/connectors/google/GoogleOAuthFlow.kt
+++ b/app/src/main/java/com/gotcha/connectors/oauth/OAuthConnectFlow.kt
@@ -1,30 +1,37 @@
-package com.gotcha.connectors.google
+package com.gotcha.connectors.oauth
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
-import com.gotcha.connectors.oauth.LoopbackRedirectServer
-import com.gotcha.connectors.oauth.OAuth2Helper
-import com.gotcha.connectors.oauth.Pkce
import java.util.UUID
/**
- * Drives the desktop-app loopback OAuth flow for [GoogleConnector] from the
- * Settings UI: build the authorization URL with PKCE, open it in a Custom Tab,
- * wait on a transient loopback listener for the redirect, then exchange the
- * code. A Desktop-type OAuth client needs no redirect-URI registration, so any
- * ephemeral 127.0.0.1 port works.
+ * Provider-generic loopback OAuth flow driven from the Settings UI: build the
+ * authorization URL with PKCE, open it in a Custom Tab, wait on a transient
+ * loopback listener for the redirect, then exchange the code and hand the tokens
+ * to the connector.
+ *
+ * Works for any provider whose client type permits an unregistered
+ * `http://127.0.0.1:{ephemeral}` redirect — Google Desktop-app clients and
+ * Microsoft Entra public clients both do.
+ *
+ * @param configFor builds the provider config from the credentials typed into the card.
+ * @param onTokens persists the token set and identifies the account; may throw with a
+ * user-facing message.
+ * @param accountLabel account identity to report after [onTokens] succeeded.
*/
-class GoogleOAuthFlow(
+class OAuthConnectFlow(
private val context: Context,
- private val connector: GoogleConnector,
+ private val configFor: (clientId: String, clientSecret: String?) -> OAuth2Config,
+ private val onTokens: suspend (clientId: String, clientSecret: String?, tokens: TokenSet) -> Unit,
+ private val accountLabel: () -> String,
private val oauth: OAuth2Helper = OAuth2Helper()
) {
sealed class Outcome {
- data class Connected(val email: String) : Outcome()
+ data class Connected(val account: String) : Outcome()
data class Failed(val message: String) : Outcome()
}
@@ -35,12 +42,14 @@ class GoogleOAuthFlow(
private var lastState: String? = null
/**
- * Launches the Custom Tab and suspends until the loopback server captures
- * the redirect (or times out after 5 minutes). Call from a coroutine scope
- * tied to the Settings screen.
+ * Launches the Custom Tab and suspends until the loopback server captures the
+ * redirect (or times out after 5 minutes). Call from a coroutine scope tied to
+ * the Settings screen.
*/
- suspend fun connect(clientId: String, clientSecret: String): Outcome {
- val cfg = connector.oauthConfig(clientId.trim(), clientSecret.trim())
+ suspend fun connect(clientId: String, clientSecret: String? = null): Outcome {
+ val id = clientId.trim()
+ val secret = clientSecret?.trim()
+ val cfg = configFor(id, secret)
val server = LoopbackRedirectServer()
val verifier = Pkce.generateVerifier()
val challenge = Pkce.challengeS256(verifier)
@@ -50,16 +59,15 @@ class GoogleOAuthFlow(
lastState = state
return try {
- val authUrl = oauth.buildAuthorizationUrl(cfg, server.redirectUri, state, challenge)
- openCustomTab(authUrl)
+ openCustomTab(oauth.buildAuthorizationUrl(cfg, server.redirectUri, state, challenge))
when (val result = server.awaitCode(state)) {
is LoopbackRedirectServer.Result.Error -> Outcome.Failed(result.message)
is LoopbackRedirectServer.Result.Code -> {
val tokens = oauth.exchangeCode(cfg, result.code, server.redirectUri, verifier)
- connector.completeConnect(clientId.trim(), clientSecret.trim(), tokens)
+ onTokens(id, secret, tokens)
relaunchApp()
- Outcome.Connected(connector.credentials()?.accountEmail.orEmpty())
+ Outcome.Connected(accountLabel())
}
}
} catch (e: Exception) {
@@ -71,11 +79,15 @@ class GoogleOAuthFlow(
/**
* Fallback for a died Custom Tab listener: the user pastes the final
- * `http://127.0.0.1:.../?code=...&state=...` URL manually. Reuses the
- * redirect URI, PKCE verifier and state from the most recent [connect]
- * attempt, so this only works right after calling it.
+ * `http://127.0.0.1:.../?code=...&state=...` URL manually. Reuses the redirect
+ * URI, PKCE verifier and state from the most recent [connect] attempt, so this
+ * only works right after calling it.
*/
- suspend fun connectWithPastedUrl(clientId: String, clientSecret: String, pastedUrl: String): Outcome {
+ suspend fun connectWithPastedUrl(
+ clientId: String,
+ clientSecret: String? = null,
+ pastedUrl: String
+ ): Outcome {
val redirectUri = lastRedirectUri
val verifier = lastVerifier
val expectedState = lastState
@@ -88,11 +100,12 @@ class GoogleOAuthFlow(
if (uri.getQueryParameter("state") != expectedState) {
return Outcome.Failed("State mismatch — start Connect again and paste the new redirect URL.")
}
- val cfg = connector.oauthConfig(clientId.trim(), clientSecret.trim())
+ val id = clientId.trim()
+ val secret = clientSecret?.trim()
return try {
- val tokens = oauth.exchangeCode(cfg, code, redirectUri, verifier)
- connector.completeConnect(clientId.trim(), clientSecret.trim(), tokens)
- Outcome.Connected(connector.credentials()?.accountEmail.orEmpty())
+ val tokens = oauth.exchangeCode(configFor(id, secret), code, redirectUri, verifier)
+ onTokens(id, secret, tokens)
+ Outcome.Connected(accountLabel())
} catch (e: Exception) {
Outcome.Failed(e.message ?: "Connection failed.")
}
diff --git a/app/src/main/java/com/gotcha/ui/ConnectorCards.kt b/app/src/main/java/com/gotcha/ui/ConnectorCards.kt
new file mode 100644
index 0000000..221bcae
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/ConnectorCards.kt
@@ -0,0 +1,238 @@
+package com.gotcha.ui
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.unit.dp
+import com.gotcha.connectors.oauth.OAuthConnectFlow
+import kotlinx.coroutines.launch
+
+/**
+ * The two reusable Settings → Connectors card shapes.
+ *
+ * [TokenConnectorCard] — a set of text fields plus Connect/Disconnect, for
+ * connectors authenticated by a pasted secret (IMAP app password, Notion
+ * internal integration token).
+ *
+ * [OAuthConnectorCard] — client credentials plus the loopback consent flow and
+ * its paste-URL fallback, for BYO-OAuth connectors (Google, Microsoft).
+ *
+ * Connectors own their own credential storage, so these talk to the connector
+ * objects directly — there is nothing for SettingsRepository to persist.
+ */
+
+/** Title + live status line + explanatory blurb and numbered setup steps. */
+@Composable
+private fun CardHeader(title: String, status: String, blurb: String?, steps: List<String>) {
+ Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)
+ Text(status, style = MaterialTheme.typography.bodyMedium)
+ if (blurb != null) Text(blurb, style = MaterialTheme.typography.bodySmall)
+ if (steps.isNotEmpty()) {
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ steps.forEach { Text(it, style = MaterialTheme.typography.bodySmall) }
+ }
+ }
+}
+
+@Composable
+fun TokenConnectorCard(
+ title: String,
+ statusLine: () -> String,
+ isConnected: () -> Boolean,
+ fields: List<TokenFieldState>,
+ /** Performs the connect (may hit the network) and returns the status message to show. */
+ onConnect: suspend () -> String,
+ onDisconnect: () -> Unit,
+ blurb: String? = null,
+ steps: List<String> = emptyList(),
+ canConnect: () -> Boolean = { fields.all { it.value.isNotBlank() } },
+ aboveFields: @Composable () -> Unit = {},
+ belowFields: @Composable () -> Unit = {}
+) {
+ val scope = rememberCoroutineScope()
+ // Bumped after connect/disconnect so statusLine() is re-read.
+ var refreshTick by remember { mutableStateOf(0) }
+ var busy by remember { mutableStateOf(false) }
+ var status by remember { mutableStateOf("") }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ key(refreshTick) { CardHeader(title, statusLine(), blurb, steps) }
+
+ if (!isConnected()) {
+ aboveFields()
+ fields.forEach { field ->
+ OutlinedTextField(
+ value = field.value,
+ onValueChange = { field.value = it },
+ label = { Text(field.label) },
+ singleLine = true,
+ visualTransformation = if (field.secret) {
+ PasswordVisualTransformation()
+ } else {
+ androidx.compose.ui.text.input.VisualTransformation.None
+ },
+ keyboardOptions = KeyboardOptions(keyboardType = field.keyboard),
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ belowFields()
+ Button(
+ onClick = {
+ busy = true
+ scope.launch {
+ status = onConnect()
+ busy = false
+ refreshTick++
+ }
+ },
+ enabled = !busy && canConnect(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (busy) "Connecting…" else "Connect") }
+ } else {
+ OutlinedButton(
+ onClick = {
+ onDisconnect()
+ fields.filter { it.secret }.forEach { it.value = "" }
+ status = "Disconnected."
+ refreshTick++
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Disconnect") }
+ }
+ if (status.isNotBlank()) Text(status, style = MaterialTheme.typography.bodySmall)
+ }
+}
+
+@Composable
+fun OAuthConnectorCard(
+ title: String,
+ statusLine: () -> String,
+ isConnected: () -> Boolean,
+ needsReconnect: () -> Boolean,
+ initialClientId: String,
+ /** Null for public clients (Microsoft) — the secret field is hidden entirely. */
+ initialClientSecret: String?,
+ flow: OAuthConnectFlow,
+ onDisconnect: () -> Unit,
+ blurb: String? = null,
+ steps: List<String> = emptyList(),
+ extraFields: @Composable () -> Unit = {}
+) {
+ val scope = rememberCoroutineScope()
+ var refreshTick by remember { mutableStateOf(0) }
+ var clientId by remember { mutableStateOf(initialClientId) }
+ var clientSecret by remember { mutableStateOf(initialClientSecret.orEmpty()) }
+ var pastedUrl by remember { mutableStateOf("") }
+ var showPasteFallback by remember { mutableStateOf(false) }
+ var busy by remember { mutableStateOf(false) }
+ var status by remember { mutableStateOf("") }
+ val usesSecret = initialClientSecret != null
+
+ fun apply(outcome: OAuthConnectFlow.Outcome) {
+ status = when (outcome) {
+ is OAuthConnectFlow.Outcome.Connected -> "Connected as ${outcome.account}."
+ is OAuthConnectFlow.Outcome.Failed -> outcome.message
+ }
+ busy = false
+ refreshTick++
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ key(refreshTick) { CardHeader(title, statusLine(), blurb, steps) }
+
+ if (!isConnected() || needsReconnect()) {
+ OutlinedTextField(
+ value = clientId,
+ onValueChange = { clientId = it },
+ label = { Text("Client ID") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ if (usesSecret) {
+ OutlinedTextField(
+ value = clientSecret,
+ onValueChange = { clientSecret = it },
+ label = { Text("Client secret") },
+ singleLine = true,
+ visualTransformation = PasswordVisualTransformation(),
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ extraFields()
+ Button(
+ onClick = {
+ busy = true
+ status = "Opening sign-in…"
+ scope.launch {
+ apply(flow.connect(clientId, clientSecret.takeIf { usesSecret }))
+ }
+ },
+ enabled = !busy && clientId.isNotBlank() && (!usesSecret || clientSecret.isNotBlank()),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text(if (busy) "Waiting for sign-in…" else "Connect") }
+
+ TextButton(onClick = { showPasteFallback = !showPasteFallback }) {
+ Text(
+ if (showPasteFallback) {
+ "Hide paste-URL fallback"
+ } else {
+ "Browser didn't return? Paste redirect URL"
+ }
+ )
+ }
+ if (showPasteFallback) {
+ OutlinedTextField(
+ value = pastedUrl,
+ onValueChange = { pastedUrl = it },
+ label = { Text("Pasted redirect URL") },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth()
+ )
+ Button(
+ onClick = {
+ busy = true
+ scope.launch {
+ apply(
+ flow.connectWithPastedUrl(
+ clientId,
+ clientSecret.takeIf { usesSecret },
+ pastedUrl
+ )
+ )
+ }
+ },
+ enabled = !busy && pastedUrl.isNotBlank(),
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Finish sign-in with pasted URL") }
+ }
+ } else {
+ OutlinedButton(
+ onClick = {
+ onDisconnect()
+ clientSecret = ""
+ status = "Disconnected."
+ refreshTick++
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) { Text("Disconnect") }
+ }
+ if (status.isNotBlank()) Text(status, style = MaterialTheme.typography.bodySmall)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/ui/TokenFieldState.kt b/app/src/main/java/com/gotcha/ui/TokenFieldState.kt
new file mode 100644
index 0000000..bdb2b3b
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/TokenFieldState.kt
@@ -0,0 +1,26 @@
+package com.gotcha.ui
+
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.text.input.KeyboardType
+
+/** One editable field in a [TokenConnectorCard]; the card owns its state. */
+class TokenFieldState(
+ val label: String,
+ initial: String,
+ val secret: Boolean = false,
+ val keyboard: KeyboardType = KeyboardType.Text
+) {
+ var value by mutableStateOf(initial)
+}
+
+@Composable
+fun rememberTokenField(
+ label: String,
+ initial: String,
+ secret: Boolean = false,
+ keyboard: KeyboardType = KeyboardType.Text
+): TokenFieldState = remember { TokenFieldState(label, initial, secret, keyboard) }
diff --git a/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt b/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt
index b7e90a0..d8f2bd6 100644
--- a/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt
+++ b/app/src/test/java/com/gotcha/connectors/oauth/OAuth2HelperTest.kt
@@ -85,6 +85,32 @@ class OAuth2HelperTest {
assertTrue(body.contains("refresh_token=rt-old"))
}
+ @Test
+ fun `public client omits client_secret entirely`() = runTest {
+ val publicCfg = cfg.copy(clientSecret = null)
+ server.enqueue(MockResponse().setBody("""{"access_token":"at-3","expires_in":3600}"""))
+ helper.exchangeCode(publicCfg, "code", "http://127.0.0.1:8080", "verifier")
+ val exchangeBody = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
+ assertTrue(
+ "public clients must not send client_secret",
+ !exchangeBody.contains("client_secret")
+ )
+ assertTrue(exchangeBody.contains("client_id=client-id"))
+
+ server.enqueue(MockResponse().setBody("""{"access_token":"at-4","expires_in":3600}"""))
+ helper.refresh(publicCfg, "rt")
+ val refreshBody = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
+ assertTrue(!refreshBody.contains("client_secret"))
+ }
+
+ @Test
+ fun `blank client secret is treated as absent`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"access_token":"at-5","expires_in":3600}"""))
+ helper.refresh(cfg.copy(clientSecret = ""), "rt")
+ val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
+ assertTrue(!body.contains("client_secret"))
+ }
+
@Test(expected = OAuthInvalidGrant::class)
fun `invalid_grant throws typed exception`() = runTest {
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":"invalid_grant"}"""))