Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: sign in to the GitHub connector with a code

leepokaif47d766022c5
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
index d94e8226..c181bb2e 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
@@ -92,6 +92,8 @@ data class AppState(
val screenRequest: ScreenRequest? = null,
/** The host sent data this app can't read even after fetching everything again. */
val unreadable: Boolean = false,
+ /** A sign-in with a code (GitHub): the code, shown before its page opens until Copy and open or Cancel. */
+ val signInCode: String? = null,
/** The update this phone asked of a computer that's behind (`requestHostUpdate`). */
val hostUpdate: HostUpdate? = null,
val error: String? = null,
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
index e236164c..598390bb 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
@@ -52,6 +52,7 @@ class AppStore internal constructor(
internal val setupTerminals = mutableMapOf<String, SetupTerminalSession>()
internal val appConnections = mutableMapOf<String, AppConnectionSession>()
internal var oauthRequestId: String? = null
+ internal val signInCodeAnswer = SignInCodeAnswer()
internal var voiceBinding: VoiceBinding? = null
internal var voiceGeneration: Int? = null
/** A "Talk to Codync" call waiting for the link (`requestCall`). */
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
index 41783411..bad398e4 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
@@ -1,5 +1,7 @@
package com.codync.android
+import android.content.ClipData
+import android.content.ClipboardManager
import android.net.Uri
import java.io.IOException
import androidx.lifecycle.viewModelScope
@@ -10,13 +12,19 @@ import kotlinx.serialization.json.*
// Connector sign-in in the browser, and its return to the app.
-fun AppStore.connectorSignIn(id: String, requestId: String? = null) = action("oauth") {
+/** [declined] completes when the user cancels a sign-in with a code before its page opens. */
+fun AppStore.connectorSignIn(id: String, requestId: String? = null, declined: CompletableDeferred<Unit>? = null) = action("oauth") {
val generation = state.value.generation
oauthRequestId = requestId
- val response = hostQuery("connectorSignIn", body("id" to id), 60_000)
+ // `showsCode`: this app can show a sign-in's code (GitHub); hosts send code sign-ins only to apps that can.
+ val response = hostQuery("connectorSignIn", buildJsonObject { put("id", id); put("showsCode", true) }, 60_000)
val plan = WireJson.decodeFromJsonElement<ConnectorSignIn>(response)
val computer = state.value.computer
externalHttps(plan.url)
+ plan.code?.let { code ->
+ if (!askSignInCode(code, declined)) { oauthRequestId = null; return@action }
+ application.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Codync", code))
+ }
if (plan.callback == "app") {
val pending = PendingConnectorOAuth.create(plan, id, computer.id, System.currentTimeMillis()).copy(requestId = requestId)
withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).save(pending) }
@@ -45,6 +53,16 @@ fun AppStore.connectorSignIn(id: String, requestId: String? = null) = action("oa
if (complete == null) throw IOException("Sign-in wasn't confirmed. Check the computer and installed connections before trying again.")
}
}
+/** Shows a sign-in's [code] until Copy and open (true) or Cancel; a Cancel completes [declined] before the dialog closes. */
+private suspend fun AppStore.askSignInCode(code: String, declined: CompletableDeferred<Unit>?): Boolean {
+ mutableState.update { it.copy(signInCode = code) }
+ return try { signInCodeAnswer.ask().also { if (!it) declined?.complete(Unit) } }
+ finally { mutableState.update { it.copy(signInCode = null) } }
+}
+/** Copy and open on the sign-in code's dialog. */
+fun AppStore.openSignInCode() = signInCodeAnswer.open()
+/** The sign-in code's dialog closed: Cancel, answered a main-thread turn later. */
+fun AppStore.dismissSignInCode() = signInCodeAnswer.dismissed { contextScope.launch(Dispatchers.Main) { it() } }
fun AppStore.cancelConnectorSignIn() = action("cancelOAuth") { cancelOAuthPending(null) }
fun AppStore.cancelConnectionRequestSignIn(entryId: String) = action("cancelOAuth") { cancelOAuthPending(entryId) }
internal suspend fun AppStore.cancelOAuthPending(requestId: String?) {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
index 578202c7..3bf28e70 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
@@ -182,6 +182,13 @@ private data class Editing<T>(val computerId: String, val draft: T)
val inline = root == Root.Pairing || showPairing || access != null || creating != null || editor != null || groupEditor != null
val error = app.error ?: states.firstNotNullOfOrNull { it.error }
CodyncDialog("Something went wrong", error != null && !inline, accounts::clearError, error, cancel = "OK") { emptyList() }
+ // A connector sign-in with a code (GitHub), from wherever it started: the code, before its page opens.
+ val coding = states.firstOrNull { it.signInCode != null }
+ val codeStore = coding?.let { accounts.store(it.computer.id) }
+ CodyncDialog(coding?.signInCode.orEmpty(), codeStore != null, { codeStore?.dismissSignInCode() },
+ "Paste this code on the sign-in page that opens next.") {
+ listOf(DialogAction("Copy and open") { codeStore?.openSignInCode() })
+ }
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt b/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt
index 00584ef5..177bb074 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/InstalledView.kt
@@ -49,11 +49,16 @@ private data class Removal(val id: String, val name: String, val skill: Boolean)
if (connectors.isEmpty() && skills.isEmpty()) MarketEmpty("shippingbox", "Nothing installed", "Connectors and skills you add show up here.")
if (connectors.isNotEmpty()) CardSection("Connectors") {
for (c in connectors) row {
- InstalledRow(c.name, if (c.needsSignIn) "Sign in so bots can use it" else c.command ?: c.url ?: c.description, icon = {
+ val subtitle = when {
+ c.needsSignIn -> "Sign in so bots can use it"
+ c.canSignIn -> "Sign in instead of using a saved token"
+ else -> c.command ?: c.url ?: c.description
+ }
+ InstalledRow(c.name, subtitle, icon = {
if (c.kind == "composio") AppLogo(c.logo, c.name, 32.dp) else ServiceLogo(null, c.name, c.registryName, 32.dp)
}, accessory = {
if (signingIn == c.id) Spinner()
- else if (c.needsSignIn) PrimaryButton("Sign in") {
+ else if (c.needsSignIn || c.canSignIn) PrimaryButton("Sign in") {
signingIn = c.id
run { try { if (!store.signInConnector(c.id)) throw IOException("Sign-in to ${c.name} wasn't confirmed.") } finally { signingIn = null } }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt
index e5090ef5..f6218858 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt
@@ -2,6 +2,8 @@ package com.codync.android
import com.codync.android.core.InstalledConnector
import com.codync.android.core.WireJson
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.buildJsonObject
@@ -48,13 +50,17 @@ internal suspend fun AppStore.skillDetails(id: String?, source: String?): String
/**
* Signs in to a connector and waits while the browser finishes it (the store catches the return);
- * false when the store reports a failure or ten minutes pass.
+ * false when the store reports a failure or ten minutes pass. Cancel on a sign-in code ends it
+ * quietly: it throws [CancellationException], which callers pass on.
*/
internal suspend fun AppStore.signInConnector(id: String, requestId: String? = null): Boolean {
clearError()
- connectorSignIn(id, requestId)
+ val declined = CompletableDeferred<Unit>()
+ connectorSignIn(id, requestId, declined)
fun signedIn(s: AppState) = s.plugins?.connectors?.any { it.id == id && it.auth == "signedIn" } == true
- val settled = withTimeoutOrNull(600_000) { state.first { signedIn(it) || it.error != null } } ?: return false
+ // The code's dialog closing changes the state, so `first` sees a Cancel at once.
+ val settled = withTimeoutOrNull(600_000) { state.first { signedIn(it) || it.error != null || declined.isCompleted } } ?: return false
+ if (declined.isCompleted) throw CancellationException("The sign-in was cancelled.")
return signedIn(settled)
}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt
index b4a7110e..22899f04 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/ConnectorOAuth.kt
@@ -3,9 +3,30 @@ package com.codync.android.core
import java.net.URI
import java.net.URLDecoder
import java.security.MessageDigest
+import kotlinx.coroutines.CompletableDeferred
import kotlinx.serialization.Serializable
-@Serializable data class ConnectorSignIn(val url: String, val callback: String)
+/** A connector's sign-in page, who catches its return, and for a sign-in with a code (GitHub) the code to type there. */
+@Serializable data class ConnectorSignIn(val url: String, val callback: String, val code: String? = null)
+
+/** The answer to a sign-in code's dialog: true for Copy and open, false for Cancel. One code at a time. */
+class SignInCodeAnswer {
+ private var reply: CompletableDeferred<Boolean>? = null
+
+ /** Waits for the answer to a newly shown code; a code still waiting answers no. */
+ suspend fun ask(): Boolean {
+ reply?.complete(false)
+ return CompletableDeferred<Boolean>().also { reply = it }.await()
+ }
+
+ fun open() { reply?.complete(true) }
+
+ /** The dialog closed. Its buttons close it before they act, so the no waits for [later] to run it, after Copy and open had its turn. */
+ fun dismissed(later: (() -> Unit) -> Unit) {
+ val waiting = reply ?: return
+ later { waiting.complete(false) }
+ }
+}
@Serializable data class PendingConnectorOAuth(val connectorId: String, val computerId: String,
val stateHash: String, val expiresAt: Long, val requestId: String? = null) {
fun validate(back: OAuthReturn, computer: String, now: Long) {
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
index 71f7bfff..53a2820d 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
@@ -5,7 +5,9 @@ import kotlinx.serialization.SerialName
@Serializable data class InstalledConnector(val id: String, val name: String, val description: String = "",
val registryName: String? = null, val kind: String, val command: String? = null, val url: String? = null,
- val keys: List<String> = emptyList(), val logo: String? = null, val auth: String? = null) {
+ val keys: List<String> = emptyList(), val logo: String? = null, val auth: String? = null,
+ /** Set up with a saved token where it could sign in instead (GitHub); older hosts leave it out. */
+ val canSignIn: Boolean = false) {
val needsSignIn: Boolean get() = auth == "signedOut"
}
@Serializable data class InstalledSkill(val id: String, val name: String, val description: String = "", val source: String, val path: String)
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt
index 54c05826..81e951cc 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ConnectorOAuthTest.kt
@@ -1,5 +1,8 @@
package com.codync.android.core
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.async
+import kotlinx.coroutines.runBlocking
import org.junit.Assert.*
import org.junit.Test
@@ -16,6 +19,34 @@ class ConnectorOAuthTest {
catch (_: IllegalArgumentException) { }
}
}
+ @Test fun aSignInWithACodeCarriesTheCode() {
+ val plan = WireJson.decodeFromString<ConnectorSignIn>("""{"url":"https://github.com/login/device","callback":"host","code":"ABCD-1234"}""")
+ assertEquals("ABCD-1234", plan.code)
+ assertNull(WireJson.decodeFromString<ConnectorSignIn>("""{"url":"https://a.example","callback":"app"}""").code)
+ }
+ @Test fun copyAndOpenAnswersYesWhicheverCloseComesFirstAndCancelAnswersNo() = runBlocking {
+ val prompt = SignInCodeAnswer()
+ val later = mutableListOf<() -> Unit>()
+ fun ask() = async(start = CoroutineStart.UNDISPATCHED) { prompt.ask() }
+ fun nextTurn() { later.forEach { it() }; later.clear() }
+ // The dialog closes, then Copy and open acts: the close's no comes a turn later.
+ var answer = ask()
+ prompt.dismissed { later += it }
+ prompt.open()
+ nextTurn()
+ assertTrue(answer.await())
+ // Copy and open, then the dialog closes.
+ answer = ask()
+ prompt.open()
+ prompt.dismissed { later += it }
+ nextTurn()
+ assertTrue(answer.await())
+ // Cancel.
+ answer = ask()
+ prompt.dismissed { later += it }
+ nextTurn()
+ assertFalse(answer.await())
+ }
@Test fun callbackParsingRejectsRepeatedFieldsMixedResultsAndOtherDestinations() {
val cancelled = OAuthReturn.parse("codync://oauth?state=fixture&error=access_denied&error_description=User+cancelled", "codync")
assertEquals("User cancelled", cancelled.error)
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
index 36c14df4..c4d483bc 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
@@ -19,4 +19,11 @@ class MarketTest {
assertTrue(InstalledConnector("c", "Connector", kind = "remote", auth = "signedOut").needsSignIn)
assertFalse(InstalledConnector("c", "Connector", kind = "remote", auth = "future").needsSignIn)
}
+
+ @Test fun tokenConnectorsOfferSignInOnlyWhenTheHostSaysSo() {
+ val older = """{"id":"github","name":"GitHub","kind":"remote","keys":["Authorization"],"auth":"none"}"""
+ assertFalse(WireJson.decodeFromString<InstalledConnector>(older).canSignIn)
+ val newer = """{"id":"github","name":"GitHub","kind":"remote","keys":["Authorization"],"auth":"none","canSignIn":true}"""
+ assertTrue(WireJson.decodeFromString<InstalledConnector>(newer).canSignIn)
+ }
}
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 01bb1f71..35fb6e55 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -25,6 +25,7 @@ import { NewBotView, NewGroupView } from './bots/NewBotView'
import { ImportBotsSheet } from './bots/ImportBotsView'
import { BotEditorView } from './bots/BotEditorView'
import { MarketplaceView } from './marketplace/MarketplaceView'
+import { SignInCodeDialog } from './marketplace/ConnectorSheets'
import { SettingsView, type SettingsPage } from './settings/SettingsView'
import { ApprovalSheet } from './settings/ApprovalSheet'
import { SearchPalette } from './SearchPalette'
@@ -491,6 +492,7 @@ function ChatSplitView() {
/>
<SectionNameDialog naming={naming} onClose={() => setNaming(null)} />
<Dialog open={errorMessage !== null} title={tr('Something went wrong')} message={errorMessage} actions={[]} cancel="OK" onClose={() => app.clearErrors()} />
+ <SignInCodeDialog />
</div>
)
}
diff --git a/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx b/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx
index 42c395bc..fb55cbcb 100644
--- a/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx
@@ -55,8 +55,9 @@ export function ConnectionRequestCard({ entry }: { entry: Entry }) {
} else if (request.connectorId) {
const id = request.connectorId
const connector = (await market.connectors(client)).find((c) => c.id === id)
- if (connector && needsSignIn(connector)) await pluginsFor(store).signIn(id)
- await market.finishConnectionRequest(client, entry.id, { connectorId: id })
+ // Cancelled: the card stays pending.
+ const signedIn = !(connector && needsSignIn(connector)) || (await pluginsFor(store).signIn(id))
+ if (signedIn) await market.finishConnectionRequest(client, entry.id, { connectorId: id })
} else if (request.registryName) {
setItem(await market.connectorInfo(client, request.registryName))
}
diff --git a/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx b/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx
index 765f0475..5f5c47c2 100644
--- a/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/ConnectorSheets.tsx
@@ -1,14 +1,31 @@
import { useEffect, useRef, useState } from 'react'
import { CardForm, CardSection, ChoiceList, IconButton, SegmentedChoice, Spinner } from '../../components/Controls'
-import { ModalHeader, SheetPage, useDismiss } from '../../components/Overlay'
+import { Dialog, ModalHeader, SheetPage, useDismiss } from '../../components/Overlay'
+import { useModel } from '../../lib/observable'
import { VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
import { errorText, market, needsSignIn, type InstalledConnector, type MarketConnector, type MarketInput } from './market-models'
import { ErrorText, Field, WebLink } from './pieces'
import { usePlugins } from './plugins'
+import { signInCode } from './sign-in-code'
import { useTr } from '../../lib/use-language'
+/** A sign-in with a code (GitHub): the code to paste on its page, before the page opens. */
+export function SignInCodeDialog() {
+ const tr = useTr()
+ const prompt = useModel(signInCode)
+ return (
+ <Dialog
+ open={prompt.code !== null}
+ title={prompt.code ?? ''}
+ message={tr('Paste this code on the sign-in page that opens next.')}
+ actions={[{ title: 'Copy and open', action: () => prompt.open() }]}
+ onClose={() => prompt.close()}
+ />
+ )
+}
+
/**
* `addsAtOnce`: opened by an Add, so a connector with nothing to fill in installs at once. Opened to
* look at it, nothing installs until Add in the header.
@@ -38,7 +55,11 @@ export function InstallConnectorSheet({ item, requestId, addsAtOnce = true, done
const c = await plugins.installConnector(item, option.id, values)
setInstalled(c)
setValues({})
- if (needsSignIn(c)) await plugins.signIn(c.id)
+ // Cancelled: the sheet stays as it is.
+ if (needsSignIn(c) && !(await plugins.signIn(c.id))) {
+ setSaving(false)
+ return
+ }
if (requestId) await market.finishConnectionRequest(client, requestId, { connectorId: c.id })
else await market.verifyConnector(client, c.id)
await plugins.refresh()
diff --git a/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx b/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
index c08a5c13..fb97130b 100644
--- a/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
@@ -269,11 +269,11 @@ function InstalledView({ back }: { back: () => void }) {
<ItemRow
key={c.id}
title={c.name}
- subtitle={needsSignIn(c) ? 'Sign in so bots can use it' : (c.command ?? c.url ?? c.description)}
+ subtitle={needsSignIn(c) ? tr('Sign in so bots can use it') : c.canSignIn ? tr('Sign in instead of using a saved token') : (c.command ?? c.url ?? c.description)}
icon={c.kind === 'composio' ? <AppLogo url={c.logo} name={c.name} /> : <ServiceLogo name={c.name} registryName={c.registryName} />}
trailing={(
<>
- {signingIn === c.id ? <Spinner /> : needsSignIn(c) ? <Button onClick={() => void signIn(c.id)}>Sign in</Button> : null}
+ {signingIn === c.id ? <Spinner /> : needsSignIn(c) || c.canSignIn ? <Button onClick={() => void signIn(c.id)}>Sign in</Button> : null}
<RemoveButton title={c.name} onClick={() => setRemoving({ id: c.id, name: c.name, isSkill: false })} />
</>
)}
diff --git a/apps/desktop/src/renderer/views/marketplace/market-models.ts b/apps/desktop/src/renderer/views/marketplace/market-models.ts
index 0012665b..fdf3bb87 100644
--- a/apps/desktop/src/renderer/views/marketplace/market-models.ts
+++ b/apps/desktop/src/renderer/views/marketplace/market-models.ts
@@ -18,14 +18,17 @@ export interface InstalledConnector {
logo?: string | null
/** Remote servers: `none`, `signedOut` (waits for sign-in; bots don't get it yet) or `signedIn`. */
auth?: string | null
+ /** Set up with a saved token where signing in works now (GitHub): offer the sign-in. Older hosts omit it. */
+ canSignIn?: boolean
}
export const needsSignIn = (c: InstalledConnector) => c.auth === 'signedOut'
-/** Where a connector's sign-in page is and who catches its return: `app` or `host`. */
+/** Where a connector's sign-in page is and who catches its return: `app` or `host`; `code`: what to type there (GitHub). */
export interface ConnectorSignIn {
url: string
callback: string
+ code?: string | null
}
export interface ComposioStatus {
@@ -194,7 +197,8 @@ export const market = {
(await c.call<{ connector: InstalledConnector }>('installConnector', body, s(45))).connector,
/** Adds every server in a pasted MCP config (`mcpServers` / `servers` JSON, or one server's entry). */
importConnectors: async (c: HostClient, config: string) => (await c.call<{ items: InstalledConnector[] }>('importConnectors', { config }, s(60))).items,
- connectorSignIn: (c: HostClient, id: string) => c.call<ConnectorSignIn>('connectorSignIn', { id }, s(60)),
+ // `showsCode`: this app shows a device sign-in's code, so the host may answer with one.
+ connectorSignIn: (c: HostClient, id: string) => c.call<ConnectorSignIn>('connectorSignIn', { id, showsCode: true }, s(60)),
finishConnectorSignIn: async (c: HostClient, state: string, code: string | null, error: string | null) =>
(await c.call<{ connector: InstalledConnector }>('connectorSignInFinish', { state, code, error }, s(60))).connector,
removeConnector: (c: HostClient, id: string) => c.call('removeConnector', { id }),
diff --git a/apps/desktop/src/renderer/views/marketplace/plugins.ts b/apps/desktop/src/renderer/views/marketplace/plugins.ts
index 2448ca15..0fec8edf 100644
--- a/apps/desktop/src/renderer/views/marketplace/plugins.ts
+++ b/apps/desktop/src/renderer/views/marketplace/plugins.ts
@@ -1,6 +1,7 @@
import { Observable, useModel } from '../../lib/observable'
import type { BotStore } from '../../store/bot-store'
-import { market, needsSignIn, sleep, type InstalledConnector, type InstalledSkill, type MarketConnector } from './market-models'
+import { market, sleep, type InstalledConnector, type InstalledSkill, type MarketConnector } from './market-models'
+import { signInCode } from './sign-in-code'
/** What's installed on one computer, for the Marketplace and bot settings (kit BotStore's plugin state). */
export class Plugins extends Observable {
@@ -42,13 +43,15 @@ export class Plugins extends Observable {
return this.after(market.finishConnectorSignIn(await this.store.ready(), state, code, error))
}
- /** Waits while the user signs in in the computer's browser (the host catches the return). */
+ /**
+ * Waits while the user signs in in the computer's browser (the host catches the return).
+ * A connector with a saved token reads `none` until then, so only `signedIn` ends the wait.
+ */
async waitForSignIn(id: string) {
for (let i = 0; i < 150; i++) {
await sleep(2000)
await this.refresh()
- const c = this.installedConnectors.find((c) => c.id === id)
- if (c && !needsSignIn(c)) return
+ if (this.installedConnectors.find((c) => c.id === id)?.auth === 'signedIn') return
}
}
@@ -72,24 +75,30 @@ export class Plugins extends Observable {
* Signs in to a remote connector (host/src/market/oauth.rs). With an `app` callback the system
* browser returns `codync://oauth?…` and the code goes to the host; with `host` the browser
* returns to the host directly and we wait for the connector to flip to signed in.
- * Returns quietly when the user cancels.
+ * A sign-in with a code (GitHub) shows the code first, then waits the same way.
+ * False when the user cancels, so the caller stops there too.
*/
async signIn(id: string) {
const plan = await market.connectorSignIn(await this.store.ready(), id)
- if (!URL.canParse(plan.url)) return
+ if (!URL.canParse(plan.url)) return false
+ if (plan.code) {
+ if (!(await signInCode.ask(plan.code))) return false
+ window.codync.app.copy(plan.code)
+ }
if (plan.callback !== 'app') {
window.codync.app.openExternal(plan.url)
await this.waitForSignIn(id)
- return
+ return true
}
let back: string
try {
back = await window.codync.app.authenticate(plan.url, window.codync.appScheme)
} catch {
- return
+ return false
}
const items = new URL(back).searchParams
await this.finishConnectorSignIn(items.get('state') ?? '', items.get('code'), items.get('error_description') ?? items.get('error'))
+ return true
}
}
diff --git a/apps/desktop/src/renderer/views/marketplace/sign-in-code.test.ts b/apps/desktop/src/renderer/views/marketplace/sign-in-code.test.ts
new file mode 100644
index 00000000..4778b256
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/sign-in-code.test.ts
@@ -0,0 +1,24 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { SignInCode } from './sign-in-code.ts'
+
+test('the dialog closing before its action still opens the page', async () => {
+ const prompt = new SignInCode()
+ const answer = prompt.ask('ABCD-1234')
+ assert.equal(prompt.code, 'ABCD-1234')
+ // Dialog calls onClose, then the action.
+ prompt.close()
+ prompt.open()
+ assert.equal(await answer, true)
+ assert.equal(prompt.code, null)
+})
+
+test('closing alone cancels, and a new code cancels the old one', async () => {
+ const prompt = new SignInCode()
+ const first = prompt.ask('AAAA-1111')
+ const second = prompt.ask('BBBB-2222')
+ assert.equal(await first, false)
+ prompt.close()
+ assert.equal(await second, false)
+ assert.equal(prompt.code, null)
+})
diff --git a/apps/desktop/src/renderer/views/marketplace/sign-in-code.ts b/apps/desktop/src/renderer/views/marketplace/sign-in-code.ts
new file mode 100644
index 00000000..4dfd3270
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/sign-in-code.ts
@@ -0,0 +1,38 @@
+import { Observable } from '../../lib/observable.ts'
+
+/**
+ * The code a device sign-in (GitHub) asks for, shown before its page opens: one at a time, for
+ * every computer. ChatWindow renders it as a dialog above whatever sheet started the sign-in.
+ */
+export class SignInCode extends Observable {
+ code: string | null = null
+ #reply: ((open: boolean) => void) | null = null
+
+ /** Shows `code`; true once the user wants it copied and the page opened. */
+ ask(code: string) {
+ this.#settle(false)
+ this.code = code
+ this.changed()
+ return new Promise<boolean>((resolve) => (this.#reply = resolve))
+ }
+
+ open() {
+ this.#settle(true)
+ }
+
+ /** The dialog closes before it runs its action, so a close only counts as Cancel once that action had its turn. */
+ close() {
+ queueMicrotask(() => this.#settle(false))
+ }
+
+ #settle(open: boolean) {
+ const reply = this.#reply
+ if (!reply) return
+ this.#reply = null
+ this.code = null
+ this.changed()
+ reply(open)
+ }
+}
+
+export const signInCode = new SignInCode()
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift
index 6ec64ece..aa8698a9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift
@@ -18,6 +18,8 @@ public struct InstalledConnector: Codable, Hashable, Sendable, Identifiable {
public var logo: String?
/// Remote servers: `none`, `signedOut` (waits for sign-in; bots don't get it yet) or `signedIn`.
public var auth: String?
+ /// Set up with a token that a sign-in can replace (GitHub); absent from older hosts.
+ public var canSignIn: Bool?
public var needsSignIn: Bool { auth == "signedOut" }
}
@@ -27,6 +29,8 @@ public struct InstalledConnector: Codable, Hashable, Sendable, Identifiable {
public struct ConnectorSignIn: Decodable, Sendable {
public var url: String
public var callback: String
+ /// A sign-in with a code (GitHub): what to paste on `url`; the host waits for it.
+ public var code: String?
}
// MARK: Composio (host/src/market/composio.rs): apps connected through composio.dev
@@ -204,8 +208,10 @@ public extension HostClient {
return res.items
}
+ /// `showsCode`: this app shows the code of a sign-in with a code (GitHub).
func connectorSignIn(_ id: String) async throws -> ConnectorSignIn {
- try await call("connectorSignIn", ["id": id], timeout: 60)
+ struct Body: Encodable { var id: String; var showsCode = true }
+ return try await call("connectorSignIn", Body(id: id), timeout: 60)
}
@discardableResult
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 0a380aaf..af0d4c38 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "Dieser Computer ist in keinem Konto: er nutzt ein privates Relay",
"This computer isn't in your account": "Dieser Computer ist nicht in deinem Konto",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses iPhone bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen.",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses Telefon bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen."
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Dieses Telefon bekommt keine Benachrichtigungen des Kontos mehr und behält seine Computer, sodass du nach dem erneuten Anmelden nichts scannen musst. Um es von ihnen zu entfernen, nutze stattdessen „Neu beginnen“ in den Einstellungen.",
+ "Paste this code on the sign-in page that opens next.": "Füge diesen Code auf der Anmeldeseite ein, die sich als Nächstes öffnet.",
+ "Copy and open": "Kopieren und öffnen",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "Code {code} kopiert: auf der geöffneten Seite einfügen, dann mit ^r aktualisieren",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "Code {code} kopiert: auf {url} einfügen, dann mit ^r aktualisieren",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "Code {code} kopiert. Auf der Anmeldeseite einfügen, dann mit Enter prüfen. Ctrl+X bricht ab.",
+ "Sign in instead of using a saved token": "Anmelden statt eines gespeicherten Tokens",
+ "↵ sign in instead of the token": "↵ anmelden statt Token",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "Code {code} kopiert: auf {url} einfügen, dann mit Enter prüfen. Ctrl+X bricht ab."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 4e441239..8fbec3fc 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "Este ordenador no está en ninguna cuenta: usa un relé privado",
"This computer isn't in your account": "Este ordenador no está en tu cuenta",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este iPhone deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes.",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este teléfono deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes."
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Este teléfono deja de recibir las notificaciones de la cuenta y conserva sus ordenadores, así que al volver a iniciar sesión no hace falta escanear. Para quitarlo de ellos, usa en su lugar «Empezar de nuevo» en Ajustes.",
+ "Paste this code on the sign-in page that opens next.": "Pega este código en la página de inicio de sesión que se abre a continuación.",
+ "Copy and open": "Copiar y abrir",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "Código {code} copiado: pégalo en la página que se abrió y luego ^r actualiza",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "Código {code} copiado: pégalo en {url} y luego ^r actualiza",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "Código {code} copiado. Pégalo en la página de inicio de sesión y luego Enter comprueba. Ctrl+X cancela.",
+ "Sign in instead of using a saved token": "Inicia sesión en lugar de usar un token guardado",
+ "↵ sign in instead of the token": "↵ iniciar sesión en lugar del token",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "Código {code} copiado: pégalo en {url} y luego Enter comprueba. Ctrl+X cancela."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index bfba10e0..76f1b1c0 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "Cet ordinateur n'est dans aucun compte : il utilise un relais privé",
"This computer isn't in your account": "Cet ordinateur n'est pas dans votre compte",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Cet iPhone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages.",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Ce téléphone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages."
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "Ce téléphone ne reçoit plus les notifications du compte et garde ses ordinateurs : en vous reconnectant, rien à scanner. Pour le retirer de ces ordinateurs, utilisez plutôt « Recommencer » dans Réglages.",
+ "Paste this code on the sign-in page that opens next.": "Collez ce code sur la page de connexion qui s’ouvre ensuite.",
+ "Copy and open": "Copier et ouvrir",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "Code {code} copié : collez-le sur la page ouverte, puis ^r pour actualiser",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "Code {code} copié : collez-le sur {url}, puis ^r pour actualiser",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "Code {code} copié. Collez-le sur la page de connexion, puis Entrée pour vérifier. Ctrl+X pour annuler.",
+ "Sign in instead of using a saved token": "Se connecter au lieu d’utiliser un jeton enregistré",
+ "↵ sign in instead of the token": "↵ se connecter au lieu du jeton",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "Code {code} copié : collez-le sur {url}, puis Entrée pour vérifier. Ctrl+X pour annuler."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 0d498141..11efb72a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "このコンピュータはどのアカウントにもありません: プライベートリレーを使っています",
"This computer isn't in your account": "このコンピュータはあなたのアカウントにありません",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "この iPhone はアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "このスマートフォンはアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。"
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "このスマートフォンはアカウントの通知を受け取らなくなりますが、コンピュータは残るので、もう一度サインインすればスキャンは不要です。コンピュータから外すには、代わりに設定の「やり直す」を使ってください。",
+ "Paste this code on the sign-in page that opens next.": "このコードを、次に開くサインイン ページに貼り付けてください。",
+ "Copy and open": "コピーして開く",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "コード {code} をコピーしました: 開いたページに貼り付けてから ^r で更新",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "コード {code} をコピーしました: {url} に貼り付けてから ^r で更新",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "コード {code} をコピーしました。サインイン ページに貼り付けてから Enter で確認。Ctrl+X でキャンセル。",
+ "Sign in instead of using a saved token": "保存したトークンの代わりにサインイン",
+ "↵ sign in instead of the token": "↵ トークンの代わりにサインイン",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "コード {code} をコピーしました: {url} に貼り付けてから Enter で確認。Ctrl+X でキャンセル。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 2e474499..8acd92b9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "이 컴퓨터는 어떤 계정에도 없습니다: 개인 릴레이를 사용합니다",
"This computer isn't in your account": "이 컴퓨터는 내 계정에 없습니다",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 iPhone은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요.",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 휴대폰은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요."
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "이 휴대폰은 계정 알림을 더 이상 받지 않지만 컴퓨터는 그대로 남아 있어, 다시 로그인하면 스캔할 필요가 없습니다. 컴퓨터에서 제거하려면 대신 설정에서 '처음부터 시작'을 사용하세요.",
+ "Paste this code on the sign-in page that opens next.": "다음에 열리는 로그인 페이지에 이 코드를 붙여 넣으세요.",
+ "Copy and open": "복사하고 열기",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "코드 {code} 복사됨: 열린 페이지에 붙여 넣은 뒤 ^r로 새로고침",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "코드 {code} 복사됨: {url}에 붙여 넣은 뒤 ^r로 새로고침",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "코드 {code} 복사됨. 로그인 페이지에 붙여 넣은 뒤 Enter로 확인. Ctrl+X로 취소.",
+ "Sign in instead of using a saved token": "저장된 토큰 대신 로그인하세요",
+ "↵ sign in instead of the token": "↵ 토큰 대신 로그인",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "코드 {code} 복사됨: {url}에 붙여 넣은 뒤 Enter로 확인. Ctrl+X로 취소."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index 7648b0c2..e6d043a2 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "这台电脑不在任何账户里:它用私人中继",
"This computer isn't in your account": "这台电脑不在你的账户里",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台 iPhone 不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台手机不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。"
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "这台手机不再收到这个账户的通知,但会保留它的电脑,重新登录后不用再扫码。要把它从那些电脑上移除,请改用设置里的“重新开始”。",
+ "Paste this code on the sign-in page that opens next.": "把这组代码粘贴到接下来打开的登录页。",
+ "Copy and open": "复制并打开",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "代码 {code} 已复制:粘贴到刚打开的页面,然后按 ^r 刷新",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "代码 {code} 已复制:到 {url} 粘贴,然后按 ^r 刷新",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "代码 {code} 已复制。粘贴到登录页后,按 Enter 检查。Ctrl+X 取消。",
+ "Sign in instead of using a saved token": "改用登录,不再用已存的 token",
+ "↵ sign in instead of the token": "↵ 改用登录,不再用 token",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "代码 {code} 已复制:到 {url} 粘贴后,按 Enter 检查。Ctrl+X 取消。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index 14a82aee..2dc7e670 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1511,5 +1511,13 @@
"This computer isn't in an account: it uses a private relay": "這臺電腦不在任何賬戶裡:它用私人中繼",
"This computer isn't in your account": "這臺電腦不在你的賬戶裡",
"This iPhone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這臺 iPhone 不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。",
- "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這支手機不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。"
+ "This phone stops getting the account's notifications and keeps its computers, so signing back in needs no scan. To take it off them, use Start over in Settings instead.": "這支手機不再收到這個賬戶的通知,但會保留它的電腦,重新登入後不用再掃碼。要把它從那些電腦上移除,請改用設定裡的「重新開始」。",
+ "Paste this code on the sign-in page that opens next.": "把這組代碼貼到接下來開啟的登入頁。",
+ "Copy and open": "複製並開啟",
+ "Code {code} copied: paste it on the page that opened, then ^r refreshes": "代碼 {code} 已複製:貼到剛開啟的頁面,然後按 ^r 重新整理",
+ "Code {code} copied: paste it at {url}, then ^r refreshes": "代碼 {code} 已複製:到 {url} 貼上,然後按 ^r 重新整理",
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels.": "代碼 {code} 已複製。貼到登入頁後,按 Enter 檢查。Ctrl+X 取消。",
+ "Sign in instead of using a saved token": "改用登入,不再用已存的 token",
+ "↵ sign in instead of the token": "↵ 改用登入,不再用 token",
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels.": "代碼 {code} 已複製:到 {url} 貼上後,按 Enter 檢查。Ctrl+X 取消。"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
index 56433f29..914da83b 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
@@ -1,4 +1,3 @@
-import AuthenticationServices
import CodyncKit
import SwiftUI
@@ -7,8 +6,7 @@ struct ConnectionRequestCard: View {
let entry: Entry
let request: ConnectionRequest
@Environment(BotStore.self) private var model
- @Environment(\.webAuthenticationSession) private var webAuthenticationSession
- @Environment(\.openURL) private var openURL
+ private var signInFlow = ConnectorSignInFlow()
@State private var app: ComposioApp?
@State private var item: MarketConnector?
@State private var agent: Backend?
@@ -67,6 +65,7 @@ struct ConnectionRequestCard: View {
ComposioConnectSheet(app: app, requestId: entry.id) { self.app = nil }
}
.codyncSheet(item: $agent) { AgentSheet(initial: $0, recheck: true) }
+ .signInCodeDialog(signInFlow.codePrompt)
.onDisappear { value = ""; username = "" }
}
@@ -146,9 +145,8 @@ struct ConnectionRequestCard: View {
value = ""
} else if let id = request.connectorId {
let connectors = try await client.connectors()
- if connectors.first(where: { $0.id == id })?.needsSignIn == true {
- try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(id)
- }
+ // Cancelled: the card stays pending.
+ if connectors.first(where: { $0.id == id })?.needsSignIn == true, try await !signInFlow.signIn(id) { return }
try await client.finishConnectionRequest(entry.id, connectorId: id)
} else if let name = request.registryName {
let loaded = try await client.connectorInfo(name)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift
index 6a4505da..f5dc8561 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectorSignInFlow.swift
@@ -5,26 +5,34 @@ import SwiftUI
/// Signs in to a remote connector (host/src/market/oauth.rs). From the phone, the system sign-in sheet
/// catches the return (`codync://oauth?…`) and hands the code to the host; on the computer itself
/// the browser returns to the host directly and we wait for the connector to flip to signed in.
+/// A sign-in with a code (GitHub) shows the code first (`codePrompt`), then waits the same way.
+/// A view keeps one as a property and presents its code with `.signInCodeDialog(signIn.codePrompt)`.
@MainActor
-struct ConnectorSignInFlow {
- let model: BotStore
- let webAuthenticationSession: WebAuthenticationSession
- let openURL: OpenURLAction
+struct ConnectorSignInFlow: DynamicProperty {
+ @Environment(BotStore.self) private var model
+ @Environment(\.webAuthenticationSession) private var webAuthenticationSession
+ @Environment(\.openURL) private var openURL
+ @State var codePrompt = SignInCodePrompt()
- /// Returns quietly when the user cancels.
- func signIn(_ id: String) async throws {
+ /// `false` when the user cancels, so the caller stops there too.
+ @discardableResult
+ func signIn(_ id: String) async throws -> Bool {
let plan = try await model.connectorSignIn(id)
- guard let url = URL(string: plan.url) else { return }
+ guard let url = URL(string: plan.url) else { return false }
+ if let code = plan.code {
+ guard await codePrompt.ask(code) else { return false }
+ Pasteboard.copy(code)
+ }
guard plan.callback == "app" else {
openURL(url)
try await model.waitForSignIn(id)
- return
+ return true
}
let back: URL
do {
back = try await webAuthenticationSession.authenticate(using: url, callbackURLScheme: AppEnvironment.current.urlScheme, preferredBrowserSession: .shared)
} catch let error as ASWebAuthenticationSessionError where error.code == .canceledLogin {
- return
+ return false
}
let items = URLComponents(url: back, resolvingAgainstBaseURL: false)?.queryItems ?? []
func value(_ name: String) -> String? { items.first { $0.name == name }?.value }
@@ -33,5 +41,6 @@ struct ConnectorSignInFlow {
code: value("code"),
error: value("error_description") ?? value("error")
)
+ return true
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/CustomConnectorSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/CustomConnectorSheet.swift
index e5b0a19d..8fd01a83 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/CustomConnectorSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/CustomConnectorSheet.swift
@@ -1,4 +1,3 @@
-import AuthenticationServices
import CodyncKit
import SwiftUI
@@ -7,8 +6,7 @@ struct CustomConnectorSheet: View {
@Environment(BotStore.self) private var model
@Environment(\.dismissModal) private var dismiss
- @Environment(\.webAuthenticationSession) private var webAuthenticationSession
- @Environment(\.openURL) private var openURL
+ private var signInFlow = ConnectorSignInFlow()
@State private var name = ""
@State private var mode = Mode.command
@State private var target = ""
@@ -36,6 +34,7 @@ struct CustomConnectorSheet: View {
form
}
.background(Palette.background)
+ .signInCodeDialog(signInFlow.codePrompt)
}
private var footer: String {
@@ -102,9 +101,8 @@ struct CustomConnectorSheet: View {
name: name, command: remote ? nil : target, url: remote ? target : nil,
env: remote ? [:] : pairs, headers: remote ? pairs : [:]
)]
- let signIn = ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL)
for c in added where c.needsSignIn {
- try await signIn.signIn(c.id)
+ try await signInFlow.signIn(c.id)
}
dismiss()
} catch {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift
index 55bb781f..aabce3c5 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstallConnectorSheet.swift
@@ -1,4 +1,3 @@
-import AuthenticationServices
import CodyncKit
import SwiftUI
@@ -11,8 +10,7 @@ struct InstallConnectorSheet: View {
let done: () -> Void
@Environment(BotStore.self) private var model
@Environment(\.dismissModal) private var dismiss
- @Environment(\.webAuthenticationSession) private var webAuthenticationSession
- @Environment(\.openURL) private var openURL
+ private var signInFlow = ConnectorSignInFlow()
@State private var optionId = ""
@State private var values: [String: String] = [:]
@State private var installed: InstalledConnector?
@@ -49,6 +47,7 @@ struct InstallConnectorSheet: View {
started = true
if addsAtOnce && item.options.count == 1 && item.options[0].inputs.isEmpty { install() }
}
+ .signInCodeDialog(signInFlow.codePrompt)
.onDisappear { values.removeAll() }
}
@@ -122,8 +121,10 @@ struct InstallConnectorSheet: View {
let c = try await model.installConnector(item, option: option.id, inputs: values)
installed = c
values.removeAll()
- if c.needsSignIn {
- try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(c.id)
+ // Cancelled: the sheet stays as it is.
+ if c.needsSignIn, try await !signInFlow.signIn(c.id) {
+ saving = false
+ return
}
if let requestId {
try await client.finishConnectionRequest(requestId, connectorId: c.id)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstalledView.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstalledView.swift
index b38740ee..0e454f92 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstalledView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/InstalledView.swift
@@ -1,12 +1,10 @@
-import AuthenticationServices
import CodyncKit
import SwiftUI
struct InstalledView: View {
let back: () -> Void
@Environment(BotStore.self) private var model
- @Environment(\.webAuthenticationSession) private var webAuthenticationSession
- @Environment(\.openURL) private var openURL
+ private var signInFlow = ConnectorSignInFlow()
@State private var removing: Removal?
@State private var signingIn: String?
@State private var viewingSkill: SkillRef?
@@ -30,6 +28,7 @@ struct InstalledView: View {
}
.background(Palette.background)
.codyncSheet(item: $viewingSkill) { SkillSheet(skill: $0) }
+ .signInCodeDialog(signInFlow.codePrompt)
}
private var list: some View {
@@ -40,7 +39,8 @@ struct InstalledView: View {
if !model.installedConnectors.isEmpty {
CardSection("Connectors") {
ForEach(model.installedConnectors) { c in
- InstalledRow(title: c.name, subtitle: c.needsSignIn ? "Sign in so bots can use it" : c.command ?? c.url ?? c.description) {
+ InstalledRow(title: c.name, subtitle: c.needsSignIn ? "Sign in so bots can use it"
+ : c.canSignIn == true ? "Sign in instead of using a saved token" : c.command ?? c.url ?? c.description) {
if c.kind == "composio" {
AppLogo(url: c.logo, name: c.name, size: 32)
} else {
@@ -49,7 +49,7 @@ struct InstalledView: View {
} accessory: {
if signingIn == c.id {
Spinner()
- } else if c.needsSignIn {
+ } else if c.needsSignIn || c.canSignIn == true {
Button(L10n.tr("Sign in")) { signIn(c.id) }
.buttonStyle(PrimaryButtonStyle())
.controlSize(.small)
@@ -96,7 +96,7 @@ struct InstalledView: View {
signingIn = id
Task {
do {
- try await ConnectorSignInFlow(model: model, webAuthenticationSession: webAuthenticationSession, openURL: openURL).signIn(id)
+ try await signInFlow.signIn(id)
} catch {
model.lastError = error.localizedDescription
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/SignInCodePrompt.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/SignInCodePrompt.swift
new file mode 100644
index 00000000..5e2482b5
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/SignInCodePrompt.swift
@@ -0,0 +1,50 @@
+import SwiftUI
+
+/// The code a sign-in with a code (GitHub) asks the user to paste, shown before its page opens.
+/// `ConnectorSignInFlow` awaits it; the view that started the sign-in presents it with `signInCodeDialog`.
+@MainActor @Observable
+final class SignInCodePrompt {
+ /// The code on screen.
+ private(set) var code: String?
+ @ObservationIgnored private var reply: CheckedContinuation<Bool, Never>?
+ /// Counts the asks, so a late "no" can't answer a newer one.
+ @ObservationIgnored private var asks = 0
+
+ /// `true` once the user wants the code copied and the page opened.
+ func ask(_ code: String) async -> Bool {
+ settle(false)
+ asks += 1
+ self.code = code
+ return await withCheckedContinuation { reply = $0 }
+ }
+
+ func open() {
+ settle(true)
+ }
+
+ /// Cancel, or the dialog fading out after `open`. Answers on the next turn, after the action ran.
+ func dismissed() {
+ code = nil
+ let asked = asks
+ Task { if self.asks == asked { self.settle(false) } }
+ }
+
+ private func settle(_ open: Bool) {
+ reply?.resume(returning: open)
+ reply = nil
+ }
+}
+
+extension View {
+ /// Shows `prompt`'s code over this view; a view that goes away answers no.
+ func signInCodeDialog(_ prompt: SignInCodePrompt) -> some View {
+ codyncDialog(
+ prompt.code ?? "",
+ isPresented: Binding(get: { prompt.code != nil }, set: { if !$0 { prompt.dismissed() } }),
+ message: "Paste this code on the sign-in page that opens next."
+ ) {
+ [DialogAction("Copy and open") { prompt.open() }]
+ }
+ .onDisappear { prompt.dismissed() }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Plugins.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Plugins.swift
index e4dd20ee..be4b85e0 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Plugins.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Plugins.swift
@@ -48,11 +48,12 @@ extension BotStore {
}
/// Waits while the user signs in in the computer's browser (the host catches the return).
+ /// A connector set up with a token reads `none` until then, so this waits for `signedIn` itself.
public func waitForSignIn(_ id: String) async throws {
for _ in 0..<150 {
try await Task.sleep(for: .seconds(2))
await refreshPlugins()
- if installedConnectors.first(where: { $0.id == id })?.needsSignIn == false { return }
+ if installedConnectors.first(where: { $0.id == id })?.auth == "signedIn" { return }
}
}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ConnectionRequestTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ConnectionRequestTests.swift
index eb7eec2f..693a1494 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/ConnectionRequestTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/ConnectionRequestTests.swift
@@ -2,6 +2,15 @@ import Foundation
import Testing
@testable import CodyncKit
+@Test func tokenConnectorsOfferSignInOnlyWhenTheHostSaysSo() throws {
+ let older = #"{"id":"github","name":"GitHub","description":"","kind":"remote","keys":["Authorization"],"auth":"none"}"#
+ #expect(try JSONDecoder().decode(InstalledConnector.self, from: Data(older.utf8)).canSignIn != true)
+ let newer = #"{"id":"github","name":"GitHub","description":"","kind":"remote","keys":["Authorization"],"auth":"none","canSignIn":true}"#
+ #expect(try JSONDecoder().decode(InstalledConnector.self, from: Data(newer.utf8)).canSignIn == true)
+ let plan = #"{"url":"https://github.com/login/device","callback":"host","code":"ABCD-1234"}"#
+ #expect(try JSONDecoder().decode(ConnectorSignIn.self, from: Data(plan.utf8)).code == "ABCD-1234")
+}
+
@Test func secureConnectionRequestIsChatVisibleWithoutCredentialValues() throws {
let wire = #"{"id":"request","seq":1,"botId":"bot","rev":1,"kind":"notice","turn":1,"createdAt":0,"updatedAt":0,"data":{"text":"Connect the service","connectionRequest":{"kind":"secret","status":"pending","title":"Example","botId":"bot","connectorId":"example","field":"API_KEY","location":"env"}}}"#
let entry = try JSONDecoder().decode(Entry.self, from: Data(wire.utf8))
diff --git a/apps/ios/Kit/Tests/CodyncUITests/SignInCodePromptTests.swift b/apps/ios/Kit/Tests/CodyncUITests/SignInCodePromptTests.swift
new file mode 100644
index 00000000..af17e3aa
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/SignInCodePromptTests.swift
@@ -0,0 +1,33 @@
+import Foundation
+import Testing
+@testable import CodyncUI
+
+/// Starts `ask` and waits until the code is on screen.
+@MainActor private func asking(_ prompt: SignInCodePrompt, _ code: String) async -> Task<Bool, Never> {
+ let answer = Task { await prompt.ask(code) }
+ while prompt.code == nil { await Task.yield() }
+ return answer
+}
+
+@MainActor @Test func copyAndOpenAnswersYesWhicheverCloseComesFirst() async {
+ let prompt = SignInCodePrompt()
+ // The fading card: the action runs, then the dialog closes.
+ var answer = await asking(prompt, "ABCD-1234")
+ prompt.open()
+ prompt.dismissed()
+ #expect(await answer.value)
+ #expect(prompt.code == nil)
+ // A card that closes in place: the dialog closes, then the action runs.
+ answer = await asking(prompt, "EFGH-5678")
+ prompt.dismissed()
+ prompt.open()
+ #expect(await answer.value)
+}
+
+@MainActor @Test func cancellingTheCodeEndsTheSignInQuietly() async {
+ let prompt = SignInCodePrompt()
+ let answer = await asking(prompt, "ABCD-1234")
+ prompt.dismissed()
+ #expect(await answer.value == false)
+ #expect(prompt.code == nil)
+}
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index b961a603..e4b4e974 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -91,8 +91,11 @@ Installing a remote connector probes it: a 401 to `initialize`, or (with no head
| --- | --- | --- |
| On the computer (desktop app, TUI; loopback caller) | `http://127.0.0.1:<port>/oauth/callback` | the host's callback page |
| On the phone (E2E channel caller) | `<cloud>/v1/oauth/callback` → 302 `codync://oauth?…` | the app's system sign-in sheet sends `connectorSignInFinish` |
+| Anywhere, with a code (GitHub) | none | the host polls the token endpoint |
-The cloud page is stateless and the code is useless without the PKCE verifier held by the host. Servers without dynamic client registration (e.g. GitHub) need a token header instead (custom connector, URL + headers). `connectorTarget` (loopback only) hands the proxy the URL and headers.
+The cloud page is stateless and the code is useless without the PKCE verifier held by the host.
+
+GitHub has no dynamic client registration, so it signs in through Codync's own OAuth App (the "Codync" app on leepokai's account that Clerk's GitHub sign-in also uses; Device Flow enabled; client id in `oauth/device.rs`) with the device flow (RFC 8628). The app is used only for a connector whose URL starts with its `resource` and whose metadata names its issuer, and asks for its own fixed scopes, never the server's: any server can name GitHub as its issuer, and the token goes to the connector's URL. `connectorSignIn {id, showsCode: true}` answers `{url, callback: "host", code}`. The iPhone, Android and desktop apps show the code in a dialog whose **Copy and open** copies it and opens GitHub's page (GitHub can't prefill it), then wait for the connector to read signed in, as with the loopback page; its Cancel ends the sign-in quietly, and an Add or a connection request started from it stops there too. The terminal UI has no dialog: it copies the code, opens the page and keeps the code in its hint (Extensions) or note (connection request), with the page's address when no browser opened. The host polls in the background until the code is entered, refused or expired (15 minutes). The token doesn't expire and has no refresh token, so a 401 signs the connector out. A client that doesn't send `showsCode` gets "Update Codync on this device to sign in to GitHub." A GitHub connector set up with a token header before this (no `oauth`; its URL starts with the app's `resource`) lists `canSignIn: true`: the installed list says *Sign in instead of using a saved token* beside a Sign in button (terminal UI: `↵ sign in instead of the token`). Its token keeps working until the device sign-in lands; then the host stores the sign-in and drops the `Authorization` header (`device::signed_in`), so clients wait for `auth: "signedIn"`, not merely not signed out. An organization that restricts OAuth Apps hides its repositories from the new token until an owner approves Codync; the user manual says so, since the old token is gone by then. Other servers without dynamic client registration need a token header instead (custom connector, URL + headers). `connectorTarget` (loopback only) hands the proxy the URL and headers.
Registry packages install only at the exact version the MCP Registry lists (no `latest`), since they run as the user. An enabled skill tells the bot where its instruction folder lives. These are distinct from the built-in `team` and `computer` MCP services.
diff --git a/host/src/api/marketplace.rs b/host/src/api/marketplace.rs
index 97b52ae7..1e814641 100644
--- a/host/src/api/marketplace.rs
+++ b/host/src/api/marketplace.rs
@@ -150,7 +150,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
} else {
market::oauth::Callback::App
};
- market::oauth::start(&hub.store, hub.port, str_arg(&b, "id")?, callback).await?
+ market::oauth::start(hub, str_arg(&b, "id")?, callback, b["showsCode"] == true).await?
}
"connectorSignInFinish" => {
let c = market::oauth::finish(&hub.store, str_arg(&b, "state")?, b["code"].as_str(), b["error"].as_str())
diff --git a/host/src/market/mod.rs b/host/src/market/mod.rs
index 6cc03b60..7e72b05a 100644
--- a/host/src/market/mod.rs
+++ b/host/src/market/mod.rs
@@ -121,6 +121,8 @@ impl Connector {
Some(o) if o.signed_in() => "signedIn",
Some(_) => "signedOut",
},
+ // Set up with a token before Codync could sign in to it (GitHub): it can switch.
+ "canSignIn": self.oauth.is_none() && self.url.as_deref().is_some_and(oauth::offers_sign_in),
})
}
}
@@ -340,9 +342,15 @@ mod tests {
let remote = c.acp(exe, 1).unwrap();
assert_eq!(remote["args"][1], "remote", "remote servers go through the proxy");
assert_eq!(remote["env"], only_data_dir);
+ assert_eq!(c.public()["canSignIn"], false, "only servers Codync has its own app for");
c.oauth = Some(oauth::OAuth::default());
assert!(c.acp(exe, 1).is_none(), "not signed in yet");
assert_eq!(c.public()["auth"], "signedOut");
+ assert_eq!(c.public()["canSignIn"], false, "already signs in");
+ c.url = Some("https://api.githubcopilot.com/mcp/".into());
+ assert_eq!(c.public()["canSignIn"], false, "already signs in");
+ c.oauth = None;
+ assert_eq!(c.public()["canSignIn"], true, "set up with a token: can switch to signing in");
}
#[tokio::test]
diff --git a/host/src/market/oauth.rs b/host/src/market/oauth.rs
index 384f421c..780bb440 100644
--- a/host/src/market/oauth.rs
+++ b/host/src/market/oauth.rs
@@ -1,5 +1,6 @@
//! Sign-in for remote MCP connectors (MCP authorization: OAuth 2.1 + PKCE,
-//! protected resource metadata, dynamic client registration).
+//! protected resource metadata, dynamic client registration). Servers where Codync has its own
+//! app instead (GitHub) sign in with a code: see `device`.
//!
//! The tokens live on this computer. The sign-in page redirects to one of two places:
//! - `http://127.0.0.1:<port>/oauth/callback`, served by this host, when the user signs
@@ -9,14 +10,22 @@
//!
//! The authorization code alone is useless: the PKCE verifier never leaves this host.
+mod device;
+mod discovery;
+
+pub use device::offers_sign_in;
+pub use discovery::required;
+use discovery::{resource_metadata, server_metadata, split};
+
use crate::LockExt;
+use crate::hub::Hub;
use crate::market::{self, Connector};
use crate::store::Store;
use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
-use std::sync::Mutex;
+use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
const TIMEOUT: Duration = Duration::from_secs(20);
@@ -93,104 +102,6 @@ fn app_uri(store: &Store) -> Option<String> {
})
}
-async fn get_json(url: &str) -> Result<Value> {
- let res = crate::http().get(url).header("accept", "application/json").timeout(TIMEOUT).send().await?;
- if !res.status().is_success() {
- bail!("{url} answered {}", res.status());
- }
- Ok(res.json().await?)
-}
-
-/// `true` when the server wants sign-in: an unauthenticated `initialize` gets 401, or the server
-/// lets `initialize` through, refuses only tool calls, and says so in its resource metadata.
-pub async fn required(url: &str, headers: &std::collections::BTreeMap<String, String>) -> bool {
- let mut req = crate::http()
- .post(url)
- .header("accept", "application/json, text/event-stream")
- .json(&json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
- "protocolVersion": crate::mcp::PROTOCOL_VERSION, "capabilities": {},
- "clientInfo": {"name": "codync", "version": env!("CARGO_PKG_VERSION")},
- }}))
- .timeout(TIMEOUT);
- for (k, v) in headers {
- req = req.header(k, v);
- }
- let Ok(res) = req.send().await else { return false };
- if res.status() == reqwest::StatusCode::UNAUTHORIZED {
- return true;
- }
- if res.status().is_success() {
- // Headers the user gave (an API key) are their way in; don't ask for sign-in on top.
- return headers.is_empty()
- && resource_metadata(url).await["authorization_servers"].as_array().is_some_and(|a| !a.is_empty());
- }
- if !matches!(res.status().as_u16(), 400 | 404 | 405) {
- return false;
- }
- // Not streamable HTTP: ask the older SSE endpoint instead (the stream is dropped unread).
- let mut req = crate::http().get(url).header("accept", "text/event-stream").timeout(TIMEOUT);
- for (k, v) in headers {
- req = req.header(k, v);
- }
- req.send().await.is_ok_and(|r| r.status() == reqwest::StatusCode::UNAUTHORIZED)
-}
-
-/// `resource_metadata="…"` from a `WWW-Authenticate: Bearer …` header.
-fn resource_metadata_hint(header: &str) -> Option<String> {
- let (_, rest) = header.split_once("resource_metadata=")?;
- let rest = rest.trim_start_matches('"');
- let end = rest.find(['"', ',', ' ']).unwrap_or(rest.len());
- Some(rest[..end].to_owned()).filter(|s| s.starts_with("https://") || s.starts_with("http://"))
-}
-
-/// `https://a.b/x/y` → (`https://a.b`, `/x/y`), without a trailing `/`.
-fn split(url: &str) -> Result<(String, String)> {
- let u = reqwest::Url::parse(url)?;
- let path = u.path().trim_end_matches('/').to_owned();
- Ok((u.origin().ascii_serialization(), path))
-}
-
-/// The protected resource metadata (RFC 9728): which authorization server, which scopes.
-async fn resource_metadata(url: &str) -> Value {
- let hint = crate::http()
- .post(url)
- .header("accept", "application/json, text/event-stream")
- .json(&json!({"jsonrpc": "2.0", "id": 0, "method": "ping"}))
- .timeout(TIMEOUT)
- .send()
- .await
- .ok()
- .and_then(|r| r.headers().get("www-authenticate")?.to_str().ok().and_then(resource_metadata_hint));
- let mut tries: Vec<String> = hint.into_iter().collect();
- if let Ok((origin, path)) = split(url) {
- tries.push(format!("{origin}/.well-known/oauth-protected-resource{path}"));
- tries.push(format!("{origin}/.well-known/oauth-protected-resource"));
- }
- for t in tries {
- if let Ok(v) = get_json(&t).await {
- return v;
- }
- }
- Value::Null
-}
-
-/// The authorization server metadata (RFC 8414, then `OpenID` discovery).
-async fn server_metadata(issuer: &str) -> Result<Value> {
- let (origin, path) = split(issuer)?;
- for t in [
- format!("{origin}/.well-known/oauth-authorization-server{path}"),
- format!("{origin}/.well-known/openid-configuration{path}"),
- format!("{issuer}/.well-known/openid-configuration"),
- ] {
- if let Ok(v) = get_json(&t).await
- && v["authorization_endpoint"].is_string()
- {
- return Ok(v);
- }
- }
- bail!("{origin} doesn't describe how to sign in")
-}
-
fn text(v: &Value) -> Option<String> {
v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
}
@@ -203,28 +114,37 @@ fn update(store: &Store, id: &str, f: impl FnOnce(&mut Connector)) -> Result<Con
})
}
-/// Starts signing in to connector `id`: the page to open.
-pub async fn start(store: &Store, port: u16, id: &str, callback: Callback) -> Result<Value> {
+/// Starts signing in to connector `id`: the page to open, and the code to type there for a device sign-in.
+/// `shows_code`: the client can show that code (older apps can't).
+pub async fn start(hub: &Arc<Hub>, id: &str, callback: Callback, shows_code: bool) -> Result<Value> {
+ let store = &hub.store;
let c = market::connectors(store)?.into_iter().find(|c| c.id == id).ok_or_else(|| anyhow!("unknown connector"))?;
let url = c.url.clone().ok_or_else(|| anyhow!("{} runs on this computer; it has nothing to sign in to", c.name))?;
- let app = app_uri(store);
- let redirect_uri = match callback {
- Callback::Host => loopback_uri(port),
- Callback::App => app
- .clone()
- .ok_or_else(|| anyhow!("The Codync cloud is off on this computer, so sign in from the computer itself."))?,
- };
let resource = resource_metadata(&url).await;
let issuer = resource["authorization_servers"][0]
.as_str()
.map_or_else(|| split(&url).map(|(origin, _)| origin), |s| Ok(s.trim_end_matches('/').to_owned()))?;
let meta = server_metadata(&issuer).await.with_context(|| format!("signing in to {}", c.name))?;
- let authorize = text(&meta["authorization_endpoint"]).ok_or_else(|| anyhow!("no authorization endpoint"))?;
let token_endpoint = text(&meta["token_endpoint"]).ok_or_else(|| anyhow!("no token endpoint"))?;
+ if let Some(app) = device::app(&issuer, &url) {
+ if !shows_code {
+ bail!("Update Codync on this device to sign in to {}.", c.name);
+ }
+ return device::start(hub, &c, &meta, app, token_endpoint).await;
+ }
+
+ let app = app_uri(store);
+ let redirect_uri = match callback {
+ Callback::Host => loopback_uri(hub.port),
+ Callback::App => app
+ .clone()
+ .ok_or_else(|| anyhow!("The Codync cloud is off on this computer, so sign in from the computer itself."))?,
+ };
+ let authorize = text(&meta["authorization_endpoint"]).ok_or_else(|| anyhow!("no authorization endpoint"))?;
// Register once with every redirect URI we might use; again if they changed.
- let wanted: Vec<String> = std::iter::once(loopback_uri(port)).chain(app).collect();
+ let wanted: Vec<String> = std::iter::once(loopback_uri(hub.port)).chain(app).collect();
let mut oauth = c.oauth.clone().unwrap_or_default();
if oauth.client_id.is_empty() || !wanted.iter().all(|u| oauth.redirect_uris.contains(u)) {
let register = text(&meta["registration_endpoint"]).ok_or_else(|| {
@@ -322,27 +242,36 @@ pub async fn finish(store: &Store, state: &str, code: Option<&str>, error: Optio
}
async fn token_request(oauth: &OAuth, form: &[(&str, &str)]) -> Result<Value> {
+ let (status, v) = token_post(oauth, form).await?;
+ if !status.is_success() || !v["access_token"].is_string() {
+ bail!("The sign-in server refused the request ({status}). Reopen sign-in and try again.");
+ }
+ Ok(v)
+}
+
+/// The token endpoint's answer as is: a device sign-in reads its `error` while it waits.
+async fn token_post(oauth: &OAuth, form: &[(&str, &str)]) -> Result<(reqwest::StatusCode, Value)> {
let mut form: Vec<(&str, &str)> = form.to_vec();
form.push(("client_id", &oauth.client_id));
if let Some(secret) = &oauth.client_secret {
form.push(("client_secret", secret));
}
+ post_form(&oauth.token_endpoint, &form).await.context("can't reach the sign-in server")
+}
+
+/// Posts `form`: the status and the JSON answer (`Null` when it isn't JSON).
+async fn post_form(url: &str, form: &[(&str, &str)]) -> Result<(reqwest::StatusCode, Value)> {
let body = form.iter().map(|(k, v)| format!("{}={}", encode(k), encode(v))).collect::<Vec<_>>().join("&");
let res = crate::http()
- .post(&oauth.token_endpoint)
+ .post(url)
.header("content-type", "application/x-www-form-urlencoded")
.header("accept", "application/json")
.body(body)
.timeout(TIMEOUT)
.send()
- .await
- .context("can't reach the sign-in server")?;
+ .await?;
let status = res.status();
- let v: Value = res.json().await.unwrap_or(Value::Null);
- if !status.is_success() || !v["access_token"].is_string() {
- bail!("The sign-in server refused the request ({status}). Reopen sign-in and try again.");
- }
- Ok(v)
+ Ok((status, res.json().await.unwrap_or(Value::Null)))
}
fn encode(s: &str) -> String {
@@ -424,52 +353,6 @@ async fn fresh(store: &Store, c: &Connector, o: &OAuth, stale: bool) -> Result<O
mod tests {
use super::*;
- #[test]
- fn reads_the_resource_metadata_hint() {
- let h = r#"Bearer error="invalid_token", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource""#;
- assert_eq!(
- resource_metadata_hint(h).as_deref(),
- Some("https://mcp.example.com/.well-known/oauth-protected-resource")
- );
- assert_eq!(resource_metadata_hint("Bearer realm=\"x\""), None);
- assert_eq!(resource_metadata_hint("Bearer resource_metadata=\"javascript:x\""), None);
- }
-
- #[test]
- fn splits_origin_and_path() {
- assert_eq!(split("https://mcp.linear.app/mcp/").unwrap(), ("https://mcp.linear.app".into(), "/mcp".into()));
- assert_eq!(split("https://a.b").unwrap(), ("https://a.b".into(), String::new()));
- }
-
- /// Serves `initialize` with `status`, and protected resource metadata when `metadata`.
- async fn server(status: u16, metadata: bool) -> String {
- use axum::{Json, Router, http::StatusCode, routing};
- let code = StatusCode::from_u16(status).unwrap();
- let mut router = Router::new().route("/mcp", routing::post(move || async move { (code, Json(json!({}))) }));
- if metadata {
- router = router.route(
- "/.well-known/oauth-protected-resource",
- routing::get(|| async { Json(json!({"authorization_servers": ["https://auth.example"]})) }),
- );
- }
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let url = format!("http://{}/mcp", listener.local_addr().unwrap());
- tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
- url
- }
-
- #[tokio::test]
- async fn sign_in_is_required_when_the_server_asks_for_it() {
- let none = std::collections::BTreeMap::new();
- assert!(required(&server(401, false).await, &none).await);
- assert!(!required(&server(200, false).await, &none).await);
- // Lets `initialize` through, refuses tool calls, and publishes its metadata.
- let lazy = server(200, true).await;
- assert!(required(&lazy, &none).await);
- let key = std::collections::BTreeMap::from([("x-api-key".to_owned(), "k".to_owned())]);
- assert!(!required(&lazy, &key).await);
- }
-
#[test]
fn form_values_are_encoded() {
assert_eq!(encode("a b&c=d/+"), "a+b%26c%3Dd%2F%2B");
diff --git a/host/src/market/oauth/device.rs b/host/src/market/oauth/device.rs
new file mode 100644
index 00000000..0d6ceff0
--- /dev/null
+++ b/host/src/market/oauth/device.rs
@@ -0,0 +1,181 @@
+//! Device sign-in (OAuth 2.0 device authorization grant, RFC 8628) for servers that don't let apps
+//! register themselves but where Codync has its own app: GitHub. The user types a short code on the
+//! server's page, from any device; this host polls for the token, so no redirect has to reach it.
+
+use super::{OAuth, post_form, store_tokens, text, token_post, update};
+use crate::hub::Hub;
+use crate::market::Connector;
+use anyhow::{Context, Result, anyhow, bail};
+use serde_json::{Value, json};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+/// Codync's own OAuth app for one server.
+pub(super) struct App {
+ issuer: &'static str,
+ /// Where the server's MCP endpoints start: only connectors there get this app's tokens.
+ resource: &'static str,
+ /// Public: the device grant needs no secret.
+ client_id: &'static str,
+ /// Fixed here, never taken from the server's metadata.
+ scopes: &'static [&'static str],
+}
+
+/// GitHub: the "Codync" OAuth App, the one Clerk's GitHub sign-in also uses, with the scopes
+/// GitHub's MCP server lists.
+const APPS: &[App] = &[App {
+ issuer: "https://github.com/login/oauth",
+ resource: "https://api.githubcopilot.com/mcp",
+ client_id: "Ov23li6EcblWW0wYQR4y",
+ scopes: &[
+ "repo",
+ "read:org",
+ "read:user",
+ "user:email",
+ "read:packages",
+ "write:packages",
+ "read:project",
+ "project",
+ "gist",
+ "notifications",
+ ],
+}];
+const GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
+
+/// Codync's app for the connector at `url` whose metadata names `issuer`. Both must match: any
+/// server can name GitHub as its issuer, and the app's tokens go only to the server it's for.
+pub(super) fn app(issuer: &str, url: &str) -> Option<&'static App> {
+ APPS.iter().find(|a| a.issuer == issuer && url.starts_with(a.resource))
+}
+
+/// A server Codync can sign in to with its own app: a connector set up for it with a token from
+/// before that (no `oauth`) can switch to signing in.
+pub fn offers_sign_in(url: &str) -> bool {
+ APPS.iter().any(|a| url.starts_with(a.resource))
+}
+
+/// Asks the server for a code and waits for the token in the background.
+/// The plan: the page to type the code on, and the code.
+pub(super) async fn start(
+ hub: &Arc<Hub>,
+ c: &Connector,
+ meta: &Value,
+ app: &App,
+ token_endpoint: String,
+) -> Result<Value> {
+ let endpoint =
+ text(&meta["device_authorization_endpoint"]).ok_or_else(|| anyhow!("{} has no sign-in with a code", c.name))?;
+ let (status, v) = post_form(&endpoint, &[("client_id", app.client_id), ("scope", &app.scopes.join(" "))])
+ .await
+ .with_context(|| format!("can't reach {}", c.name))?;
+ let (Some(device_code), Some(code), Some(page)) =
+ (text(&v["device_code"]), text(&v["user_code"]), text(&v["verification_uri"]))
+ else {
+ bail!("{} refused the sign-in ({status})", c.name);
+ };
+ // Nothing changes on the connector until the token arrives: one that works with a token keeps working.
+ let oauth = OAuth { client_id: app.client_id.to_owned(), token_endpoint, ..OAuth::default() };
+ let interval = v["interval"].as_u64().unwrap_or(5);
+ let lasts = Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
+ tokio::spawn(poll(hub.clone(), c.id.clone(), oauth, device_code, interval, lasts));
+ Ok(json!({"url": page, "callback": "host", "code": code}))
+}
+
+/// What one answer from the token endpoint means.
+#[derive(Debug, PartialEq)]
+enum Step {
+ Done,
+ /// Ask again after this many seconds.
+ Wait(u64),
+ Stop,
+}
+
+fn step(v: &Value, interval: u64) -> Step {
+ if v["access_token"].is_string() {
+ return Step::Done;
+ }
+ match v["error"].as_str() {
+ // No answer we can read (a 5xx page) is worth another try too.
+ Some("authorization_pending") | None => Step::Wait(interval),
+ // RFC 8628 §3.5: five seconds more (GitHub sends the new interval).
+ Some("slow_down") => Step::Wait(v["interval"].as_u64().unwrap_or(interval + 5)),
+ _ => Step::Stop,
+ }
+}
+
+async fn poll(hub: Arc<Hub>, id: String, oauth: OAuth, device_code: String, mut interval: u64, lasts: Duration) {
+ let until = Instant::now() + lasts;
+ while Instant::now() < until {
+ tokio::time::sleep(Duration::from_secs(interval)).await;
+ let v = match token_post(&oauth, &[("grant_type", GRANT), ("device_code", &device_code)]).await {
+ Ok((_, v)) => v,
+ // A dropped connection doesn't end the sign-in.
+ Err(error) => {
+ tracing::debug!(connector = %id, error = format!("{error:#}"), "device sign-in poll failed");
+ continue;
+ }
+ };
+ match step(&v, interval) {
+ Step::Done => {
+ if let Err(error) = update(&hub.store, &id, |c| signed_in(c, &oauth, &v)) {
+ tracing::warn!(connector = %id, error = format!("{error:#}"), "couldn't save the sign-in");
+ }
+ return;
+ }
+ Step::Wait(next) => interval = next,
+ Step::Stop => {
+ tracing::info!(connector = %id, error = v["error"].as_str().unwrap_or("unknown"), "device sign-in ended");
+ return;
+ }
+ }
+ }
+}
+
+/// Keeps the token, and drops the token header the connector was set up with before it could sign in.
+fn signed_in(c: &mut Connector, app: &OAuth, v: &Value) {
+ c.oauth = Some(app.clone());
+ store_tokens(c, v);
+ c.headers.retain(|k, _| !k.eq_ignore_ascii_case("authorization"));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn signing_in_replaces_the_token_header() {
+ let mut c: Connector = serde_json::from_value(json!({
+ "id": "github", "name": "GitHub", "url": "https://api.githubcopilot.com/mcp/",
+ "headers": {"Authorization": "Bearer ghp_old", "X-MCP-Toolsets": "repos"},
+ }))
+ .unwrap();
+ assert!(offers_sign_in(c.url.as_deref().unwrap()));
+ let app = OAuth { client_id: "id".into(), token_endpoint: "https://github.com/t".into(), ..OAuth::default() };
+ signed_in(&mut c, &app, &json!({"access_token": "gho_new"}));
+ let o = c.oauth.unwrap();
+ assert_eq!((o.client_id.as_str(), o.access_token.as_str()), ("id", "gho_new"));
+ assert_eq!(c.headers.keys().collect::<Vec<_>>(), ["X-MCP-Toolsets"]);
+ }
+
+ #[test]
+ fn only_github_s_own_server_gets_codync_s_github_app() {
+ let github = "https://github.com/login/oauth";
+ assert!(app(github, "https://api.githubcopilot.com/mcp/").is_some());
+ assert!(app(github, "https://api.githubcopilot.com/mcp/readonly").is_some());
+ // Another server naming GitHub as its issuer would get a GitHub token sent to it.
+ assert!(app(github, "https://evil.example/mcp").is_none());
+ assert!(app(github, "https://api.githubcopilot.com.evil.example/mcp").is_none());
+ assert!(app("https://mcp.linear.app", "https://mcp.linear.app/mcp").is_none());
+ }
+
+ #[test]
+ fn polls_until_the_token_arrives() {
+ assert_eq!(step(&json!({"error": "authorization_pending"}), 5), Step::Wait(5));
+ assert_eq!(step(&json!({"error": "slow_down", "interval": 10}), 5), Step::Wait(10));
+ assert_eq!(step(&json!({"error": "slow_down"}), 5), Step::Wait(10));
+ assert_eq!(step(&json!({"access_token": "gho_x", "token_type": "bearer"}), 5), Step::Done);
+ assert_eq!(step(&json!({"error": "access_denied"}), 5), Step::Stop);
+ assert_eq!(step(&json!({"error": "expired_token"}), 5), Step::Stop);
+ assert_eq!(step(&Value::Null, 5), Step::Wait(5));
+ }
+}
diff --git a/host/src/market/oauth/discovery.rs b/host/src/market/oauth/discovery.rs
new file mode 100644
index 00000000..de1e707f
--- /dev/null
+++ b/host/src/market/oauth/discovery.rs
@@ -0,0 +1,155 @@
+//! Finding out how a remote MCP server signs in: whether it wants sign-in at all, its protected
+//! resource metadata (RFC 9728) and its authorization server's metadata (RFC 8414).
+
+use super::TIMEOUT;
+use anyhow::{Result, bail};
+use serde_json::{Value, json};
+
+async fn get_json(url: &str) -> Result<Value> {
+ let res = crate::http().get(url).header("accept", "application/json").timeout(TIMEOUT).send().await?;
+ if !res.status().is_success() {
+ bail!("{url} answered {}", res.status());
+ }
+ Ok(res.json().await?)
+}
+
+/// `true` when the server wants sign-in: an unauthenticated `initialize` gets 401, or the server
+/// lets `initialize` through, refuses only tool calls, and says so in its resource metadata.
+pub async fn required(url: &str, headers: &std::collections::BTreeMap<String, String>) -> bool {
+ let mut req = crate::http()
+ .post(url)
+ .header("accept", "application/json, text/event-stream")
+ .json(&json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
+ "protocolVersion": crate::mcp::PROTOCOL_VERSION, "capabilities": {},
+ "clientInfo": {"name": "codync", "version": env!("CARGO_PKG_VERSION")},
+ }}))
+ .timeout(TIMEOUT);
+ for (k, v) in headers {
+ req = req.header(k, v);
+ }
+ let Ok(res) = req.send().await else { return false };
+ if res.status() == reqwest::StatusCode::UNAUTHORIZED {
+ return true;
+ }
+ if res.status().is_success() {
+ // Headers the user gave (an API key) are their way in; don't ask for sign-in on top.
+ return headers.is_empty()
+ && resource_metadata(url).await["authorization_servers"].as_array().is_some_and(|a| !a.is_empty());
+ }
+ if !matches!(res.status().as_u16(), 400 | 404 | 405) {
+ return false;
+ }
+ // Not streamable HTTP: ask the older SSE endpoint instead (the stream is dropped unread).
+ let mut req = crate::http().get(url).header("accept", "text/event-stream").timeout(TIMEOUT);
+ for (k, v) in headers {
+ req = req.header(k, v);
+ }
+ req.send().await.is_ok_and(|r| r.status() == reqwest::StatusCode::UNAUTHORIZED)
+}
+
+/// `resource_metadata="…"` from a `WWW-Authenticate: Bearer …` header.
+fn resource_metadata_hint(header: &str) -> Option<String> {
+ let (_, rest) = header.split_once("resource_metadata=")?;
+ let rest = rest.trim_start_matches('"');
+ let end = rest.find(['"', ',', ' ']).unwrap_or(rest.len());
+ Some(rest[..end].to_owned()).filter(|s| s.starts_with("https://") || s.starts_with("http://"))
+}
+
+/// `https://a.b/x/y` → (`https://a.b`, `/x/y`), without a trailing `/`.
+pub(super) fn split(url: &str) -> Result<(String, String)> {
+ let u = reqwest::Url::parse(url)?;
+ let path = u.path().trim_end_matches('/').to_owned();
+ Ok((u.origin().ascii_serialization(), path))
+}
+
+/// The protected resource metadata (RFC 9728): which authorization server, which scopes.
+pub(super) async fn resource_metadata(url: &str) -> Value {
+ let hint = crate::http()
+ .post(url)
+ .header("accept", "application/json, text/event-stream")
+ .json(&json!({"jsonrpc": "2.0", "id": 0, "method": "ping"}))
+ .timeout(TIMEOUT)
+ .send()
+ .await
+ .ok()
+ .and_then(|r| r.headers().get("www-authenticate")?.to_str().ok().and_then(resource_metadata_hint));
+ let mut tries: Vec<String> = hint.into_iter().collect();
+ if let Ok((origin, path)) = split(url) {
+ tries.push(format!("{origin}/.well-known/oauth-protected-resource{path}"));
+ tries.push(format!("{origin}/.well-known/oauth-protected-resource"));
+ }
+ for t in tries {
+ if let Ok(v) = get_json(&t).await {
+ return v;
+ }
+ }
+ Value::Null
+}
+
+/// The authorization server metadata (RFC 8414, then `OpenID` discovery).
+pub(super) async fn server_metadata(issuer: &str) -> Result<Value> {
+ let (origin, path) = split(issuer)?;
+ for t in [
+ format!("{origin}/.well-known/oauth-authorization-server{path}"),
+ format!("{origin}/.well-known/openid-configuration{path}"),
+ format!("{issuer}/.well-known/openid-configuration"),
+ ] {
+ if let Ok(v) = get_json(&t).await
+ && v["authorization_endpoint"].is_string()
+ {
+ return Ok(v);
+ }
+ }
+ bail!("{origin} doesn't describe how to sign in")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_the_resource_metadata_hint() {
+ let h = r#"Bearer error="invalid_token", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource""#;
+ assert_eq!(
+ resource_metadata_hint(h).as_deref(),
+ Some("https://mcp.example.com/.well-known/oauth-protected-resource")
+ );
+ assert_eq!(resource_metadata_hint("Bearer realm=\"x\""), None);
+ assert_eq!(resource_metadata_hint("Bearer resource_metadata=\"javascript:x\""), None);
+ }
+
+ #[test]
+ fn splits_origin_and_path() {
+ assert_eq!(split("https://mcp.linear.app/mcp/").unwrap(), ("https://mcp.linear.app".into(), "/mcp".into()));
+ assert_eq!(split("https://a.b").unwrap(), ("https://a.b".into(), String::new()));
+ }
+
+ /// Serves `initialize` with `status`, and protected resource metadata when `metadata`.
+ async fn server(status: u16, metadata: bool) -> String {
+ use axum::{Json, Router, http::StatusCode, routing};
+ let code = StatusCode::from_u16(status).unwrap();
+ let mut router = Router::new().route("/mcp", routing::post(move || async move { (code, Json(json!({}))) }));
+ if metadata {
+ router = router.route(
+ "/.well-known/oauth-protected-resource",
+ routing::get(|| async { Json(json!({"authorization_servers": ["https://auth.example"]})) }),
+ );
+ }
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}/mcp", listener.local_addr().unwrap());
+ tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
+ url
+ }
+
+ #[tokio::test]
+ async fn sign_in_is_required_when_the_server_asks_for_it() {
+ let none = std::collections::BTreeMap::new();
+ assert!(required(&server(401, false).await, &none).await);
+ assert!(!required(&server(200, false).await, &none).await);
+ // Lets `initialize` through, refuses tool calls, and publishes its metadata.
+ let lazy = server(200, true).await;
+ assert!(required(&lazy, &none).await);
+ let key = std::collections::BTreeMap::from([("x-api-key".to_owned(), "k".to_owned())]);
+ assert!(!required(&lazy, &key).await);
+ }
+}
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index ac15ba2d..64bcd5d4 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -427,6 +427,10 @@ pub fn mismatch_text(m: &crate::compat::Mismatch, host: &str) -> String {
/// OSC 52: the terminal puts it on the clipboard, over SSH too.
pub fn copy(text: &str) {
+ // Tests run in the developer's terminal: leave its clipboard alone.
+ if cfg!(test) {
+ return;
+ }
let mut out = std::io::stdout();
let _ = write!(out, "\x1b]52;c;{}\x07", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, text));
let _ = out.flush();
diff --git a/host/src/tui/connections.rs b/host/src/tui/connections.rs
index 1e64b9ff..ef2de5cc 100644
--- a/host/src/tui/connections.rs
+++ b/host/src/tui/connections.rs
@@ -127,7 +127,7 @@ impl App {
),
Step::Installed => ("connectors", json!({}), Step::Installed),
Step::Authorize if f.choice == 0 => {
- ("connectorSignIn", json!({"id":c.request["connectorId"]}), Step::SignIn)
+ ("connectorSignIn", json!({"id":c.request["connectorId"],"showsCode":true}), Step::SignIn)
}
Step::AppStart => ("composioConnect", json!({"toolkit":c.request["toolkit"]}), Step::AppStart),
Step::AppCheck if c.metadata["status"] == "needsFields" => (
@@ -219,10 +219,21 @@ impl App {
Step::SignIn => {
c.step = Step::Authorize;
f.choice = 1;
- f.note = "Sign-in link copied. Finish in browser, then Enter checks. Ctrl+X cancels.".into();
- if let Some(url) = value["url"].as_str() {
+ let url = value["url"].as_str().unwrap_or_default();
+ let opened = super::manage::open_browser(url, &self.url);
+ // A sign-in with a code (GitHub): the code is what to paste on the page.
+ if let Some(code) = value["code"].as_str() {
+ super::app::copy(code);
+ f.note = if opened {
+ "Code {code} copied. Paste it on the sign-in page, then Enter checks. Ctrl+X cancels."
+ } else {
+ "Code {code} copied: paste it at {url}, then Enter checks. Ctrl+X cancels."
+ }
+ .replace("{code}", code)
+ .replace("{url}", url);
+ } else {
super::app::copy(url);
- super::manage::open_browser(url, &self.url);
+ f.note = "Sign-in link copied. Finish in browser, then Enter checks. Ctrl+X cancels.".into();
}
}
Step::AppStart | Step::AppCheck => {
@@ -294,6 +305,9 @@ mod tests {
Json(match method.as_str() {
"connectorInfo" => json!({"name":"fixture","options":[{"id":"local","inputs":[{"name":"key","secret":true,"required":true}]}]}),
"installConnector" => json!({"connector":{"id":"connector","auth":"signedOut"}}),
+ "connectorSignIn" => {
+ json!({"url":"https://github.com/login/device","callback":"host","code":"ABCD-1234"})
+ }
"composioConnect" => json!({"status":"needsFields","mode":"apiKey","fields":[{"name":"token","label":"Token","secret":true}]}),
"composioConnectFields" => json!({"status":"active"}),
_ => json!({}),
@@ -306,7 +320,8 @@ mod tests {
axum::serve(listener, router).await.unwrap();
});
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
- (App::new(super::super::net::Client::new(&url, Some("fixture")), tx, url), rx, calls, task)
+ // A computer elsewhere (the TUI over SSH), so no browser opens.
+ (App::new(super::super::net::Client::new(&url, Some("fixture")), tx, String::new()), rx, calls, task)
}
fn open(app: &mut App, request: &Value) {
@@ -365,12 +380,16 @@ mod tests {
reply(&mut app, &mut rx).await;
key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
reply(&mut app, &mut rx).await;
+ // A sign-in with a code, and no browser here: the note names the code and the page.
+ let Some(Overlay::Fields(f)) = app.overlays.last() else { panic!("fields") };
+ assert!(f.note.contains("ABCD-1234") && f.note.contains("https://github.com/login/device"), "{}", f.note);
key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
reply(&mut app, &mut rx).await;
let calls = calls.lock().unwrap();
let methods: Vec<_> = calls.iter().map(|c| c["method"].as_str().unwrap()).collect();
assert_eq!(methods, ["connectorInfo", "installConnector", "connectorSignIn", "connectorRequestFinish"]);
assert_eq!(calls[1]["body"]["inputs"]["key"], "fixture-key");
+ assert_eq!(calls[2]["body"]["showsCode"], true);
assert_eq!(calls[3]["body"]["connectorId"], "connector");
assert!(app.overlays.is_empty());
server.abort();
diff --git a/host/src/tui/manage/market.rs b/host/src/tui/manage/market.rs
index 542b084b..ccab5991 100644
--- a/host/src/tui/manage/market.rs
+++ b/host/src/tui/manage/market.rs
@@ -185,7 +185,7 @@ impl App {
let act = match self.market_rows(&m).get(m.cursor) {
Some(Row::Node) => Act::Node,
Some(Row::Agent(b)) => Act::Agent(s(b, "id")),
- Some(Row::Installed(c)) if c["auth"] == "signedOut" => Act::SignIn(s(c, "id")),
+ Some(Row::Installed(c)) if c["auth"] == "signedOut" || c["canSignIn"] == true => Act::SignIn(s(c, "id")),
Some(Row::Custom) => Act::Custom,
Some(Row::Registry(c)) => Act::Install((*c).clone()),
Some(Row::Skill(v)) => Act::Skill((*v).clone(), true),
@@ -204,7 +204,7 @@ impl App {
}
Act::SignIn(id) => {
self.flash("Starting the sign-in…");
- self.sheet("connectorSignIn", json!({"id": id}), Reply::SignIn);
+ self.sheet("connectorSignIn", json!({"id": id, "showsCode": true}), Reply::SignIn);
}
Act::Custom => {
self.overlays.push(Overlay::Market(m));
@@ -410,4 +410,23 @@ mod tests {
let Some(Overlay::Agent(a)) = app.overlays.last() else { panic!("the agent sheet is open") };
assert!(!a.busy && !app.agent_set_up(a), "a registry agent that never ran waits for Set up");
}
+
+ #[tokio::test]
+ async fn a_connector_with_a_saved_token_signs_in_with_a_code() {
+ let mut app = open();
+ for (can_sign_in, starts) in [(false, false), (true, true)] {
+ app.plugins.0 = vec![json!({"id": "github", "name": "GitHub", "auth": "none", "canSignIn": can_sign_in})];
+ app.hint = None;
+ move_to(&mut app, 0);
+ let Some(Overlay::Market(m)) = app.overlays.pop() else { panic!("the marketplace is open") };
+ let m = app.market_key(m, KeyEvent::from(KeyCode::Enter)).expect("the marketplace stays open");
+ app.overlays.push(m);
+ assert_eq!(app.hint.is_some(), starts, "canSignIn {can_sign_in}: \"Starting the sign-in…\"");
+ }
+ // No browser opens from this TUI (not on the computer): the hint names the code and the page.
+ let device = "https://github.com/login/device";
+ app.on_sheet_reply(Reply::SignIn, Ok(json!({"url": device, "callback": "host", "code": "ABCD-1234"})));
+ let hint = &app.hint.as_ref().expect("the code shows").0;
+ assert!(hint.contains("ABCD-1234") && hint.contains(device), "{hint}");
+ }
}
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index eabf0636..1f58ce47 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -1,8 +1,10 @@
//! Replies to the sheets' commands.
use serde_json::{Value, json};
+use std::time::{Duration, Instant};
use super::super::app::{After, AgentModel, App, Entry, Overlay, Toggle, rename_fold};
+use super::super::l10n::tr;
use super::{Market, MemoryMode, Reply, Shell, open_browser, s};
impl App {
@@ -188,11 +190,24 @@ impl App {
}
Reply::SignIn => {
let url = s(&v, "url");
- super::super::app::copy(&url);
- if open_browser(&url, &self.url) {
- self.flash("Finish in the browser, then ^r refreshes");
+ let opened = open_browser(&url, &self.url);
+ // A sign-in with a code (GitHub): the code is what to paste, and it stays up meanwhile.
+ if let Some(code) = v["code"].as_str() {
+ super::super::app::copy(code);
+ let text = if opened {
+ tr("Code {code} copied: paste it on the page that opened, then ^r refreshes")
+ } else {
+ tr("Code {code} copied: paste it at {url}, then ^r refreshes")
+ };
+ let text = text.replace("{code}", code).replace("{url}", &url);
+ self.hint = Some((text, Instant::now() + Duration::from_mins(2)));
} else {
- self.flash("Sign-in link copied: open it on this computer, then ^r refreshes");
+ super::super::app::copy(&url);
+ self.flash(if opened {
+ "Finish in the browser, then ^r refreshes"
+ } else {
+ "Sign-in link copied: open it on this computer, then ^r refreshes"
+ });
}
}
Reply::Models(backend) => {
diff --git a/host/src/tui/sheets/market_view.rs b/host/src/tui/sheets/market_view.rs
index 4cb6a32d..535d1868 100644
--- a/host/src/tui/sheets/market_view.rs
+++ b/host/src/tui/sheets/market_view.rs
@@ -62,6 +62,7 @@ pub fn draw(buf: &mut Buffer, area: Rect, app: &App, m: &Market) {
Row::Installed(c) => {
let right = match s(c, "auth") {
"signedOut" => tr("↵ sign in"),
+ _ if c["canSignIn"] == true => tr("↵ sign in instead of the token"),
_ if c["kind"] == "composio" => std::borrow::Cow::Borrowed("Composio"),
_ => tr("installed"),
};
diff --git a/web/content/docs/connectors-and-skills.mdx b/web/content/docs/connectors-and-skills.mdx
index 3607b07b..ee3dcc18 100644
--- a/web/content/docs/connectors-and-skills.mdx
+++ b/web/content/docs/connectors-and-skills.mdx
@@ -36,7 +36,11 @@ Some hosted connectors ask you to sign in with your account on that service. The
The tokens stay on the computer and are refreshed when they expire. Until someone signs in, bots don't get the connector, and your library shows a **Sign in** button for it.
-Some services don't offer this kind of sign-in (GitHub is one). For those, add the server as a custom connector with its URL and a token header.
+GitHub signs in with a short code instead. Codync shows the code; press **Copy and open**, paste the code on the GitHub page that opens, and authorize Codync. The connector is ready as soon as GitHub confirms. In the terminal, the code is copied and shown at the bottom while GitHub's page opens, or next to the page's address when the terminal can't open a browser.
+
+If you added GitHub earlier with a personal access token, your library shows **Sign in instead of using a saved token** next to it. Sign in there and Codync switches the connector over and deletes the saved token, so it no longer stops working when the token expires. If one of your GitHub organizations restricts OAuth app access, an owner of that organization approves Codync first (on GitHub, in the organization's third-party access settings); until then bots can't see that organization's repositories, so keep the token if you need them.
+
+A few services don't offer any sign-in Codync can use. For those, add the server as a custom connector with its URL and a token header.
## Add a custom connector