Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Keep an OAuth connector signed in across launches (#100)

Gian Moraes33f83b96a335
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 49f8b0d..3df13f0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **Agentes no Grok.** Um agente pode rodar no Grok CLI, com a assinatura do grok.com, como roda no Cursor CLI. Cada resposta usa uma pasta própria: os seus plugins, skills e hooks não carregam, e só as ferramentas do Tucano ficam à mão.
> - **Um conector que falha diz por quê.** O passo da resposta mostra o motivo em vermelho, e o agente recebe o mesmo motivo pra explicar, em vez de um ✗ sem nada.
> - **Os passos mostram o que o agente fez.** Cada consulta mostra o SQL ou o que foi pedido, e o que voltou ("120 linhas"); um comando mostra o comando inteiro, e o SQL quando roda um; uma skill diz qual foi lida. Tudo aparece enquanto o agente trabalha, sem nenhum segredo na tela.
+> - **Um conector com login OAuth não pede pra entrar de novo a cada vez que o app abre.** O app se registrava de novo no servidor a cada abertura e perdia o token que renova o acesso; agora guarda o registro e renova sozinho.
### Added
@@ -33,6 +34,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Fixed
+- **An OAuth connector stays signed in across launches.** The app listens for the sign-in callback on a new port each launch, and a saved registration was used only for the exact address it was made with, so every launch registered the app again and the refresh token, which belongs to the client that got it, was refused: the connector asked to sign in again. A loopback address now matches whatever its port (RFC 8252), so the connector refreshes on its own. A new sign-in still registers with the exact address, for servers that want it. Thanks [@GianCdM](https://github.com/GianCdM)! ([#100](https://github.com/eduwxyz/tucano/pull/100))
- **A routine that runs as the app opens finds its connectors.** Routines missed while the app was closed, and any due right as it opens, ran on the first check, before the connectors had finished connecting: the agent was told its tools were offline and ran without them. A routine now waits for the connectors still connecting, up to a minute, then runs anyway (with a line in the log); with none connecting it starts at once, as before. Thanks [@jvitorcarvalho](https://github.com/jvitorcarvalho)! ([#152](https://github.com/eduwxyz/tucano/pull/152))
- **An agent replies once at a time in the same conversation or thread.** When another agent handed the turn to one already replying there, a second reply of it started next to the first, each working from the conversation as it was when it began. The hand-off is now noted instead, and the caller's step says so ("already replying here, will see this next"); when the current reply ends well, one follow-up reply reads everything that came in meanwhile, in the same Claude Code session. A reply that stopped, failed, hit a limit or waits on you gets no follow-up, since you act there anyway. The same agent elsewhere still runs in parallel, and the hand-off router is told who is already replying, and that waiting for someone's update isn't a request. Thanks [@eialanjones](https://github.com/eialanjones)! ([#151](https://github.com/eduwxyz/tucano/pull/151))
- **A connector tool that fails says why.** The reply's step showed a bare ✗ next to the tool's name, and for some failures the agent got an empty result too. The step now shows the reason under its label (a few lines, all of it on a click), and the agent gets it: a reason only in the structured content or an embedded resource, an MCP error's code and data, a timeout in seconds, a result that doesn't match the tool's schema, or a session that couldn't reconnect. An approved call and a routine's poll say it the same way. Thanks [@rjgdias](https://github.com/rjgdias)! ([#133](https://github.com/eduwxyz/tucano/pull/133))
diff --git a/src/core/connectors.ts b/src/core/connectors.ts
index c163e4c..e372436 100644
--- a/src/core/connectors.ts
+++ b/src/core/connectors.ts
@@ -103,6 +103,24 @@ export const staleSession = (e: unknown): boolean =>
const key = (id: string, what: string): string => `connector:${id}:${what}`
+// The gateway's callback port changes on every launch, and RFC 8252 §7.3 has an
+// authorization server treat a loopback redirect as port-agnostic. Comparing the
+// redirect without the port keeps the registration — and the refresh token, which
+// belongs to the client that got it — across restarts, instead of signing in again.
+// Only an http loopback address loses its port; anything else must match whole.
+export const sameLoopbackRedirect = (a: string, b: string): boolean => {
+ const shape = (u: string): string => {
+ try {
+ const { protocol, hostname, pathname, search } = new URL(u)
+ const loopback = protocol === 'http:' && (hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]')
+ return loopback ? `${protocol}//${hostname}${pathname}${search}` : u
+ } catch {
+ return u
+ }
+ }
+ return shape(a) === shape(b)
+}
+
export class ConnectorManager {
private live = new Map<string, Live>()
private oauthStates = new Map<string, { connectorId: string; transport: StreamableHTTPClientTransport }>()
@@ -443,11 +461,14 @@ export class ConnectorManager {
state = randomBytes(16).toString('hex')
return state
},
- // The callback port changes between launches; a registration for another
- // redirect URL is useless, so register again.
+ // The callback port changes between launches; the registration is still good,
+ // so the refresh token that goes with it survives the restart (a refresh sends no
+ // redirect). Signing in again, it must be the exact address: a server that
+ // doesn't take any port on loopback would turn the new one away, so it registers again.
clientInformation: async () => {
const info = await secrets.getJson<OAuthClientInformationMixed & { redirect_uris?: string[] }>(key(id, 'oauth_client'))
- return info && (!info.redirect_uris || info.redirect_uris.includes(redirectUrl)) ? info : undefined
+ const fits = (u: string): boolean => (interactive ? u === redirectUrl : sameLoopbackRedirect(u, redirectUrl))
+ return info && (!info.redirect_uris || info.redirect_uris.some(fits)) ? info : undefined
},
saveClientInformation: (info) => secrets.setJson(key(id, 'oauth_client'), { ...info, redirect_uris: [redirectUrl] }),
tokens: () => secrets.getJson<OAuthTokens>(key(id, 'oauth_tokens')),
diff --git a/test/connectors-oauth.test.ts b/test/connectors-oauth.test.ts
new file mode 100644
index 0000000..cd89ee6
--- /dev/null
+++ b/test/connectors-oauth.test.ts
@@ -0,0 +1,171 @@
+// A connector that signs in through OAuth keeps its credentials between launches.
+// The gateway's callback port changes every launch, and re-registering the app on
+// each one throws away the refresh token, which belongs to the client that got it.
+import { createServer, type Server } from 'node:http'
+import { mkdtempSync } from 'node:fs'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { ConnectorManager, sameLoopbackRedirect } from '../src/core/connectors'
+import { Db } from '../src/core/db'
+import { plainCipher, Secrets } from '../src/core/secrets'
+
+let server: Server
+let base: string
+let db: Db
+let secrets: Secrets
+let opened: string[]
+let registrations: number
+let refreshes: string[]
+let expireAccessToken: () => void
+let revokeRefreshTokens: () => void
+
+const body = async (req: import('node:http').IncomingMessage): Promise<string> => {
+ const chunks: Buffer[] = []
+ for await (const c of req) chunks.push(c as Buffer)
+ return Buffer.concat(chunks).toString()
+}
+
+// An authorization server that registers apps on the fly (RFC 7591) and binds a
+// refresh token to the client that got it, the way Atlassian's MCP server does.
+beforeEach(async () => {
+ opened = []
+ registrations = 0
+ refreshes = []
+ let current = '' // only the newest access token works, as if the older one had expired
+ expireAccessToken = () => {
+ current = ''
+ }
+ const owner = new Map<string, string>()
+ revokeRefreshTokens = () => owner.clear()
+
+ server = createServer((req, res) => {
+ void (async () => {
+ const json = (status: number, payload: unknown): void =>
+ void res.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(payload))
+ const url = new URL(req.url ?? '/', base)
+ if (req.method === 'GET' && url.pathname.startsWith('/.well-known/oauth-protected-resource')) {
+ return json(200, { resource: `${base}/mcp`, authorization_servers: [base] })
+ }
+ if (req.method === 'GET' && url.pathname.startsWith('/.well-known/oauth-authorization-server')) {
+ return json(200, {
+ issuer: base,
+ authorization_endpoint: `${base}/authorize`,
+ token_endpoint: `${base}/token`,
+ registration_endpoint: `${base}/register`,
+ response_types_supported: ['code'],
+ grant_types_supported: ['authorization_code', 'refresh_token'],
+ code_challenge_methods_supported: ['S256'],
+ token_endpoint_auth_methods_supported: ['none']
+ })
+ }
+ if (req.method === 'POST' && url.pathname === '/register') {
+ registrations += 1
+ return json(201, { ...JSON.parse(await body(req)), client_id: `client-${registrations}` })
+ }
+ if (req.method === 'POST' && url.pathname === '/token') {
+ const form = new URLSearchParams(await body(req))
+ const clientId = form.get('client_id') ?? ''
+ const refreshToken = form.get('refresh_token')
+ if (refreshToken) {
+ refreshes.push(`${clientId} (issued to ${owner.get(refreshToken) ?? 'nobody'})`)
+ if (owner.get(refreshToken) !== clientId) return json(400, { error: 'invalid_grant' })
+ current = `at-${owner.size + 1}-${Date.now()}`
+ return json(200, { access_token: current, token_type: 'Bearer', expires_in: 3600, refresh_token: refreshToken })
+ }
+ current = `at-${owner.size + 1}-${Date.now()}`
+ const fresh = `rt-${owner.size + 1}`
+ owner.set(fresh, clientId)
+ return json(200, { access_token: current, token_type: 'Bearer', expires_in: 3600, refresh_token: fresh })
+ }
+
+ // The MCP endpoint: it turns away anything without a token it handed out.
+ if (!current || (req.headers.authorization ?? '').replace(/^Bearer /, '') !== current) {
+ res.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"` }).end()
+ return
+ }
+ if (req.method !== 'POST') {
+ res.writeHead(405).end() // no server-sent stream: the client carries on without it
+ return
+ }
+ const call = JSON.parse(await body(req)) as { id?: number; method?: string; params?: { protocolVersion?: string } }
+ if (call.method === 'initialize') {
+ return json(200, { jsonrpc: '2.0', id: call.id, result: { protocolVersion: call.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'fake', version: '1' } } })
+ }
+ if (call.method === 'tools/list') return json(200, { jsonrpc: '2.0', id: call.id, result: { tools: [] } })
+ res.writeHead(202).end()
+ })()
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'tucano-oauth-')), 'test.db'))
+ secrets = new Secrets(db, plainCipher)
+})
+
+afterEach(async () => {
+ db.close()
+ await new Promise((resolve) => server.close(resolve))
+})
+
+// One launch of the app, listening for the OAuth callback on its own port.
+const launch = (callbackPort: number): ConnectorManager =>
+ new ConnectorManager({ db, secrets, emit: () => {}, openUrl: (u) => opened.push(u), oauthCallbackUrl: () => `http://127.0.0.1:${callbackPort}/oauth/callback` })
+
+describe('OAuth credentials across launches', () => {
+ it('signs in once and refreshes on the next launch, when only the callback port changed', async () => {
+ const first = launch(51001)
+ const id = await first.add({ name: 'Atlassian', kind: 'remote', url: `${base}/mcp`, auth: 'oauth' })
+ await first.connect(id) // the background connect from add()
+ const authorization = await first.authorize(id)
+ expect(authorization).toBeTruthy()
+ expect(registrations).toBe(1)
+ const state = new URL(authorization!).searchParams.get('state')!
+ expect(await first.finishOAuth(state, 'code-1')).toBe(true)
+ expect(first.get(id)!.status).toBe('connected')
+ await first.closeAll()
+ expireAccessToken() // the access token grew old while the app was closed
+
+ // Next launch: same connector, another callback port.
+ const second = launch(51002)
+ await second.connect(id)
+ expect(second.get(id)!.status).toBe('connected')
+ expect(opened).toHaveLength(1) // no browser again
+ expect(registrations).toBe(1) // and no registration again
+ expect(refreshes).toEqual(['client-1 (issued to client-1)'])
+ await second.closeAll()
+ })
+
+ it('registers again for a new sign-in, so a server that wants the exact address still takes it', async () => {
+ const first = launch(51001)
+ const id = await first.add({ name: 'Atlassian', kind: 'remote', url: `${base}/mcp`, auth: 'oauth' })
+ await first.connect(id)
+ const state = new URL((await first.authorize(id))!).searchParams.get('state')!
+ await first.finishOAuth(state, 'code-1')
+ await first.closeAll()
+ expireAccessToken()
+ revokeRefreshTokens() // signed out on the server's side while the app was closed
+
+ const second = launch(51002)
+ await second.connect(id) // in the background: no browser, it waits to be signed in
+ expect(second.get(id)!.status).toBe('needs_auth')
+ expect(opened).toHaveLength(1)
+ const again = new URL((await second.authorize(id))!)
+ expect(registrations).toBe(2) // a registration with this launch's address
+ expect(again.searchParams.get('client_id')).toBe('client-2')
+ expect(again.searchParams.get('redirect_uri')).toBe('http://127.0.0.1:51002/oauth/callback')
+ await second.closeAll()
+ })
+})
+
+describe('the loopback redirect, port aside', () => {
+ it('ignores only the port, and only on an http loopback address', () => {
+ expect(sameLoopbackRedirect('http://127.0.0.1:51001/oauth/callback', 'http://127.0.0.1:52002/oauth/callback')).toBe(true)
+ expect(sameLoopbackRedirect('http://[::1]:1/oauth/callback', 'http://[::1]:2/oauth/callback')).toBe(true)
+ expect(sameLoopbackRedirect('http://localhost:1/oauth/callback', 'http://localhost:2/oauth/callback')).toBe(true)
+ expect(sameLoopbackRedirect('http://127.0.0.1:1/oauth/callback', 'http://127.0.0.1:2/other')).toBe(false)
+ expect(sameLoopbackRedirect('http://127.0.0.1:1/oauth/callback', 'http://localhost:2/oauth/callback')).toBe(false)
+ expect(sameLoopbackRedirect('https://app.example.com:1/oauth/callback', 'https://app.example.com:2/oauth/callback')).toBe(false)
+ expect(sameLoopbackRedirect('https://127.0.0.1:1/oauth/callback', 'https://127.0.0.1:2/oauth/callback')).toBe(false)
+ })
+})