diff --git a/docs/inventory/visible-controls.json b/docs/inventory/visible-controls.json index e9741aa9f..8fb64157a 100644 --- a/docs/inventory/visible-controls.json +++ b/docs/inventory/visible-controls.json @@ -2547,7 +2547,7 @@ {"source": "flybot_workspace/static/settings/app.mjs", "line": 657, "construction": "const confirm = document.createElement('button');", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/settings/app.mjs", "line": 865, "construction": "const button = document.createElement('button');", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/settings/app.mjs", "line": 1019, "construction": "const remove = document.createElement('button');", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, - {"source": "flybot_workspace/static/settings/connected-tools.mjs", "line": 46, "construction": "const button = document.createElement('button')", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, + {"source": "flybot_workspace/static/settings/connected-tools.mjs", "line": 53, "construction": "const button = document.createElement('button')", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/settings/custom-mcp.mjs", "line": 23, "construction": "const remove = document.createElement('button')", "execution_profile": "settings", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/shell/app.mjs", "line": 261, "construction": "link = doc.createElement('a');", "execution_profile": "shell", "verification": "unverified dynamic construction site; conditional instances require execution"}, {"source": "flybot_workspace/static/shell/app.mjs", "line": 437, "construction": "const skip = document.createElement('a');", "execution_profile": "shell", "verification": "unverified dynamic construction site; conditional instances require execution"}, diff --git a/flybot_workspace/static/settings/connected-tools.mjs b/flybot_workspace/static/settings/connected-tools.mjs index e6b6348a2..add456505 100644 --- a/flybot_workspace/static/settings/connected-tools.mjs +++ b/flybot_workspace/static/settings/connected-tools.mjs @@ -1,5 +1,9 @@ -// One-shot owner approvals. No execution is authorized by provider/model text. -// Kept separate from the settings layout so unrelated UI polish stays isolated. +// Activity and one-time decisions for the current account's connected tools. +const APPROVAL_STATUS = { + pending: '待确认', approved: '已允许', executing: '执行中', succeeded: '已完成', + denied: '已拒绝', failed: '执行失败', expired: '已过期', unknown: '结果未确认', +} + export async function mountToolApprovals(document, fetcher = globalThis.fetch, schedule = globalThis.setInterval) { const keyCard = document.getElementById('composio-key-card') if (!keyCard || (globalThis.location && globalThis.location.pathname !== '/settings/connectors')) return @@ -8,9 +12,9 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s section.className = 'composio-key-card' const title = document.createElement('h2') title.className = 'composio-key-title' - title.textContent = '智能体工具调用 · 逐次确认' + title.textContent = '应用工具调用' const note = document.createElement('p') - note.textContent = '下方每次确认只允许这一项工具和这些参数执行一次(读取也需要确认)。外部工具可能发送消息、修改或删除数据;仅在核实完整参数后允许。拒绝或超时不会自动重试。' + note.textContent = '在私聊里,已授权的 GitHub 只读查询(如检查 PR 是否合并)会自动执行。修改数据、发送消息和其他工具调用需要确认。每次确认只允许所示工具和参数执行一次。' const list = document.createElement('div') list.setAttribute('aria-live', 'polite') section.append(title, note, list) @@ -25,23 +29,26 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s const response = await fetcher('/v1/composio/approvals', {credentials: 'same-origin'}) if (!response.ok) return const payload = await response.json() - const pending = (payload.items || []).slice(0, 10) - const raw = JSON.stringify(pending) + const calls = (payload.items || []).slice(0, 10) + const raw = JSON.stringify(calls) if (raw === previous) return - const rows = pending.map(item => { + const rows = calls.map(item => { const row = document.createElement('div') const label = document.createElement('strong') const task = typeof item.task_id === 'string' && item.task_id ? ' · 任务 ' + item.task_id.slice(0, 8) : '' - label.textContent = item.name + ' · ' + item.status + task + const automatic = item.approval_mode === 'automatic_read' + const mode = automatic ? ' · 自动只读' : '' + label.textContent = item.name + mode + ' · ' + (APPROVAL_STATUS[item.status] ?? '状态未知') + task const context = document.createElement('p') - context.textContent = '请求:' + item.prompt + '\n连接:' + (item.account ? item.account.toolkit + ' / ' + item.account.account_id : '连接已移除') + const prompt = item.prompt ? '请求:' + item.prompt + '\n' : '' + context.textContent = prompt + '连接:' + (item.account ? item.account.toolkit + ' / ' + item.account.account_id : '连接已移除') const args = document.createElement('pre') args.style.whiteSpace = 'pre-wrap' args.style.overflowWrap = 'anywhere' args.textContent = JSON.stringify(item.arguments, null, 2) const status = document.createElement('p') - if (item.status === 'unknown' || item.status === 'executing') status.textContent = '执行结果不明;不要重试,请先到提供方核实。' - const actions = item.status === 'pending' ? [['deny', '拒绝'], ['approve', '允许此调用一次']] : [] + if (item.status === 'unknown') status.textContent = '请先到应用核实执行结果。' + const actions = !automatic && item.status === 'pending' ? [['deny', '拒绝'], ['approve', '允许此调用一次']] : [] for (const [decision, text] of actions) { const button = document.createElement('button') button.type = 'button' @@ -64,7 +71,7 @@ export async function mountToolApprovals(document, fetcher = globalThis.fetch, s return row }) list.replaceChildren(...rows) - if (!rows.length) list.textContent = '暂无待确认调用。请在私人聊天中请求智能体使用你授权的应用;群聊、定时任务和对外 API 尚未接通个人工具。' + if (!rows.length) list.textContent = '暂无工具调用记录。' previous = raw } catch { /* A polling failure grants nothing. */ } finally { busy = false } diff --git a/flybot_workspace/static/settings/index.html b/flybot_workspace/static/settings/index.html index 9c8201cc1..dd08c2861 100644 --- a/flybot_workspace/static/settings/index.html +++ b/flybot_workspace/static/settings/index.html @@ -1046,7 +1046,7 @@

Composio API key

自定义 MCP 服务器 · 仅当前账号

-

公开 HTTPS:443 Streamable HTTP;不支持本地命令、私网、重定向或 URL 查询参数。凭据仅加密保存在管理服务,不会交给 DS-Bot。每次工具调用(包括读取)都需要在上方逐次确认。

+

公开 HTTPS:443 Streamable HTTP;不支持本地命令、私网、重定向或 URL 查询参数。凭据仅加密保存在管理服务,不会交给 DS-Bot。自定义 MCP 的每次调用都需要在上方确认。

diff --git a/runtime/flybot-image/native-ds-bot-overlay.mjs b/runtime/flybot-image/native-ds-bot-overlay.mjs index f6faf9202..55e2ddce2 100644 --- a/runtime/flybot-image/native-ds-bot-overlay.mjs +++ b/runtime/flybot-image/native-ds-bot-overlay.mjs @@ -55,7 +55,7 @@ const files = { ], 'src/host/capabilities.js': [ '656fcc0b0fb7fd597dfd0f62bd49522d92becd4ed1c77dd53ba016f045614c89', - '321be0845446f49d8e0a8a2c6fc6acc95e178042b33a5c37e93aa7f2e6c079ca', + 'bff22001141ec0ea02714a2e440575adf7d863a036eb91f487f3f7725046349c', ], 'src/host/channel.js': [ '34b2a23af48a7c90984cca4050d3187816a9873fd513005cfb4663a6b8a33cb8', diff --git a/runtime/flybot-image/native-ds-bot.patch b/runtime/flybot-image/native-ds-bot.patch index 55bb5b5fa..dd9ec8509 100644 --- a/runtime/flybot-image/native-ds-bot.patch +++ b/runtime/flybot-image/native-ds-bot.patch @@ -1255,10 +1255,24 @@ index 9116437..1ee020e 100644 if (rt.isSwitchingPart?.(sessionId)) return false const session = ctx.get('agents')?.get(sessionId)?.session diff --git a/src/host/capabilities.js b/src/host/capabilities.js -index efe6323..85c65df 100644 +index efe6323..e0e439e 100644 --- a/src/host/capabilities.js +++ b/src/host/capabilities.js -@@ -397,7 +397,9 @@ export function install(rt) { +@@ -336,6 +336,13 @@ export function install(rt) { + let config + try { + config = configFor(item, bot.id) ++ // Never pass the private read endpoint to a group or detached task. ++ if (name === 'ot-apps' && config.transport === 'streamable-http' ++ && rt.chatOwners?.get(sessionId) === bot.id ++ && rt.groupOwners?.has(sessionId) === false && rt.taskOwners?.has(sessionId) === false) { ++ const url = await rt.flybotWorkspaceApps?.ownerPrivateToolUrl?.(config.url) ++ if (url) config.url = url ++ } + } catch (error) { + await drop() + statusSet(bot.id, name, sessionId, { state: 'error', error: rt.redactSecrets(error.message).slice(0, 300) }) +@@ -397,7 +404,9 @@ export function install(rt) { } const desiredFor = (agent, bot) => { const sessionId = agent.session.id diff --git a/runtime/flybot-workspace-web/features/connectors/connectors.js b/runtime/flybot-workspace-web/features/connectors/connectors.js index e26415aa2..211547cf8 100644 --- a/runtime/flybot-workspace-web/features/connectors/connectors.js +++ b/runtime/flybot-workspace-web/features/connectors/connectors.js @@ -1,6 +1,6 @@ // B4 connectors in the user's own DS-Bot: the user's own Composio key and // connections, user-configured remote MCP servers, and the one-shot owner -// approval for every tool call. Port of composio.py, connected_tools.py, +// approval for calls outside the verified read allowlist. Port of composio.py, connected_tools.py, // composio_principals (personal scope) and custom_mcp.py. Keys and bearer // tokens are sealed at rest; nothing here falls back to another key. import { createHash, randomUUID } from 'node:crypto' @@ -16,6 +16,28 @@ const MAX_ARGS = 12000 const MAX_RESULT = 10000 const MAX_CALLS_KEPT = 100 const APPROVAL_TTL = 300 +const AUTOMATIC_READ = 'automatic_read' +// Each entry is a known read in Composio's GitHub toolkit. Tool descriptions, +// name prefixes, and hints from custom MCP servers do not grant execution. +// https://docs.composio.dev/toolkits/github +// https://docs.github.com/en/rest/pulls/pulls#check-if-a-pull-request-has-been-merged +const GITHUB_READS = new Set([ + 'GITHUB_CHECK_IF_PULL_REQUEST_HAS_BEEN_MERGED', + 'GITHUB_CHECK_IF_PULL_REQUEST_MERGED', + 'GITHUB_GET_A_PULL_REQUEST', + 'GITHUB_LIST_PULL_REQUESTS', + 'GITHUB_GET_A_REPOSITORY', + 'GITHUB_GET_REPOS', + 'GITHUB_LIST_REPOS', + 'GITHUB_LIST_REPOSITORIES', + 'GITHUB_LIST_REPOSITORIES_FOR_THE_AUTHENTICATED_USER', + 'GITHUB_LIST_REPOSITORIES_FOR_A_USER', + 'GITHUB_GET_AN_ISSUE', + 'GITHUB_LIST_REPOSITORY_ISSUES', + 'GITHUB_GET_A_RELEASE', + 'GITHUB_GET_A_RELEASE_BY_TAG_NAME', + 'GITHUB_LIST_RELEASES', +]) const newId = () => randomUUID().replaceAll('-', '') const KEY_PURPOSE = 'flybot-workspace.composio.key' const mcpPurpose = id => `flybot-workspace.mcp.${id}` @@ -40,6 +62,7 @@ const keyView = row => (row ? { configured: true, key_hint: row.key_hint, revisi const serverView = row => ({ id: row.id, name: row.name, origin: row.origin, revision: row.revision, created: row.created, updated: row.updated }) const callView = (row, withArgs = false) => { const view = { id: row.id, task_id: null, name: row.name, status: row.status, created: row.created, expires: row.expires } + if (row.approval_mode === AUTOMATIC_READ) view.approval_mode = AUTOMATIC_READ if (withArgs) view.arguments = JSON.parse(row.arguments) if (row.result != null) view.result = row.result return view @@ -334,24 +357,36 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl } const live = (row, now) => (row.status === 'pending' || row.status === 'approved') && row.expires > now - function expireCalls(draft, now) { + function expireCalls(draft, now, limit = MAX_CALLS_KEPT) { for (const row of draft.calls) if ((row.status === 'pending' || row.status === 'approved') && row.expires <= now) row.status = 'expired' - if (draft.calls.length > MAX_CALLS_KEPT) draft.calls = draft.calls.slice(-MAX_CALLS_KEPT) + if (draft.calls.length <= limit) return + let toRemove = draft.calls.length - limit + draft.calls = draft.calls.filter(row => { + if (live(row, now) || (row.status === 'executing' && row.expires > now) || toRemove === 0) return true + toRemove -= 1 + return false + }) } - function propose(name, args) { + function propose(name, args, { automaticReads = false } = {}) { const entry = catalog.get(name) if (!entry) fail(403, 'tool_not_discovered', 'Tool is not connected for this account') if (!isObject(args)) fail(400, 'invalid', 'arguments must be an object') const argumentsText = JSON.stringify(sortKeys(args)) if (Buffer.byteLength(argumentsText) > MAX_ARGS) fail(413, 'invalid', 'Tool arguments exceed bound') + const automatic = automaticReads === true && entry.kind === 'composio' && entry.toolkit === 'github' && GITHUB_READS.has(name) const now = clock() return store.update((draft) => { - expireCalls(draft, now) - // The same tool with the same arguments reuses its open proposal, so the - // agent can call again after the owner approved without a second prompt. - const open = draft.calls.find(row => row.name === name && row.arguments === argumentsText && live(row, now)) + expireCalls(draft, now, MAX_CALLS_KEPT - 1) + // Allow the same account, tool and arguments to resume an approval. + // A private automatic receipt cannot be claimed by another context. + const open = draft.calls.find(row => row.name === name && row.arguments === argumentsText && + row.kind === entry.kind && row.ref === entry.ref && row.version === entry.version && row.revision === entry.revision && + (row.approval_mode === AUTOMATIC_READ) === automatic && live(row, now)) if (open) return open - const row = { id: newId(), name, kind: entry.kind, ref: entry.ref, version: entry.version, revision: entry.revision, arguments: argumentsText, status: 'pending', result: null, created: now, expires: now + APPROVAL_TTL } + if (draft.calls.length >= MAX_CALLS_KEPT) fail(429, 'quota', 'Too many active connected-tool calls') + const row = { id: newId(), name, kind: entry.kind, ref: entry.ref, version: entry.version, revision: entry.revision, arguments: argumentsText, + status: automatic ? 'approved' : 'pending', ...(automatic ? {approval_mode: AUTOMATIC_READ} : {}), + result: null, created: now, expires: now + APPROVAL_TTL } draft.calls.push(row) return row }) @@ -377,7 +412,8 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl noQuery(query) const st = store.update((draft) => { expireCalls(draft, now); return draft }) const key = secretKey() - const items = [...st.calls].sort((a, b) => b.created - a.created || a.id.localeCompare(b.id)).slice(0, 30).map((row) => { + const items = [...st.calls].sort((a, b) => Number(b.status === 'pending') - Number(a.status === 'pending') || + b.created - a.created || a.id.localeCompare(b.id)).slice(0, 30).map((row) => { const view = callView(row, true) if (row.kind === 'composio') { const account = st.connections.find(c => c.id === row.ref) @@ -391,11 +427,12 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl }) return { items } } - async function run(id) { + async function run(id, { automaticReads = false } = {}) { // Consume the approval before any network I/O; 'executing' is terminal. let claimed = false const row = store.update((draft) => { const item = draft.calls.find(c => c.id === id) + if (item?.approval_mode === AUTOMATIC_READ && automaticReads !== true) return null if (!item || item.status !== 'approved' || item.expires <= clock()) return item ? { ...item } : null item.status = 'executing' claimed = true @@ -439,16 +476,17 @@ export function createConnectors({ dir, sealKey, identity, env = process.env, cl return item ? { ...item } : null }) } - // One agent tool call: propose, wait (bounded) for the owner's decision, run once. - async function callTool(name, args, { waitMs = 40_000, pollMs = 500 } = {}) { + // One agent tool call. Verified private reads are ready to run immediately. + // Other tools wait for a bounded period on a one-shot owner decision. + async function callTool(name, args, { automaticReads = false, waitMs = 40_000, pollMs = 500 } = {}) { if (!catalog.has(name)) await discover({ force: true }) - let row = propose(name, args) + let row = propose(name, args, {automaticReads}) const deadline = Date.now() + waitMs while (row && row.status === 'pending' && Date.now() < deadline) { await sleep(pollMs) row = state().calls.find(c => c.id === row.id) } - if (row?.status === 'approved') row = await run(row.id) + if (row?.status === 'approved') row = await run(row.id, {automaticReads}) if (!row) return { error: 'tool_unavailable' } if (row.status === 'pending') return { error: 'tool_pending', approval_id: row.id, note: 'Waiting for the owner to approve in Settings > App connectors; call again with the same arguments after approval. No implicit retry.' } return row.result ?? { error: 'tool_' + row.status, note: 'Await owner approval in Settings > App connectors; no implicit retry.' } diff --git a/runtime/flybot-workspace-web/features/connectors/index.js b/runtime/flybot-workspace-web/features/connectors/index.js index 5ca32426e..f5de9eb45 100644 --- a/runtime/flybot-workspace-web/features/connectors/index.js +++ b/runtime/flybot-workspace-web/features/connectors/index.js @@ -1,5 +1,5 @@ // B4 connectors feature: the user's own Composio key/connections, custom MCP -// servers and per-call owner approvals, executed in this user's DS-Bot and +// servers and owner approval rules, executed in this user's DS-Bot and // exposed to it as the native MCP capability "ot-apps" (loopback, token path). // Endpoints: connectors/ and connectors/v1 (legacy /v1/composio/* and // /v1/mcp/servers* compat). /v1/composio/callback stays on the platform (it is @@ -32,7 +32,7 @@ export default function connectors(host) { pending = setTimeout(() => { pending = null; sync().then((done) => { if (done === false && !host.currentRuntime()?.mainBot) schedule(5000) }).catch(error => { host.log(`apps capability sync failed: ${String(error?.code ?? error?.message ?? 'error').slice(0, 80)}`); schedule(15000) }) }, delay) pending.unref?.() } - const apps = Object.freeze({ connectedToolkits: api.connectedToolkits, sync }) + const apps = Object.freeze({ connectedToolkits: api.connectedToolkits, ownerPrivateToolUrl: tools.ownerPrivateToolUrl, sync }) const attach = runtime => { if (!runtime?.rt) return runtime.rt.flybotWorkspaceApps = apps diff --git a/runtime/flybot-workspace-web/features/connectors/tool-server.js b/runtime/flybot-workspace-web/features/connectors/tool-server.js index 1b7a8925a..6178ed73d 100644 --- a/runtime/flybot-workspace-web/features/connectors/tool-server.js +++ b/runtime/flybot-workspace-web/features/connectors/tool-server.js @@ -1,15 +1,15 @@ // Loopback MCP server (streamable HTTP, JSON responses) that gives this user's // DS-Bot its connected app tools as a native MCP capability ("ot-apps"). // Bound to 127.0.0.1 with a per-boot random path token; requests carrying an -// Origin header (browsers, DNS rebinding) are refused. Every tools/call goes -// through the owner's one-shot approval in the connectors feature. +// Origin header (browsers, DNS rebinding) are refused. A separate path is +// mounted only in the owner's native private chats for automatic reads. import { createServer } from 'node:http' import { randomBytes } from 'node:crypto' export const CAPABILITY = 'ot-apps' const BODY_LIMIT = 1024 * 1024 -export async function handleRpc(connectors, message) { +export async function handleRpc(connectors, message, {automaticReads = false} = {}) { if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return { jsonrpc: '2.0', id: message?.id ?? null, error: { code: -32600, message: 'Invalid Request' } } if (message.id === undefined) return null const ok = result => ({ jsonrpc: '2.0', id: message.id, result }) @@ -17,7 +17,9 @@ export async function handleRpc(connectors, message) { case 'initialize': return ok({ protocolVersion: typeof message.params?.protocolVersion === 'string' ? message.params.protocolVersion : '2025-03-26', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'flybot-workspace-apps', version: '1.0.0' }, - instructions: 'Your owner\'s connected apps (their own Composio connections and MCP servers). Every call waits for the owner to approve it in FlyBot Settings > App connectors.' }) + instructions: automaticReads + ? "Your owner's connected apps. Known read-only Composio queries run automatically in this private chat. Other calls wait for approval in Settings > App connectors." + : "Your owner's connected apps. Calls in this context wait for approval in Settings > App connectors." }) case 'ping': return ok({}) case 'tools/list': @@ -26,7 +28,7 @@ export async function handleRpc(connectors, message) { const args = message.params?.arguments ?? {} if (!args || typeof args !== 'object' || Array.isArray(args)) return { jsonrpc: '2.0', id: message.id, error: { code: -32602, message: 'arguments must be an object' } } try { - const result = await connectors.callTool(String(message.params?.name ?? ''), args) + const result = await connectors.callTool(String(message.params?.name ?? ''), args, {automaticReads}) return ok({ isError: Boolean(result?.error), content: [{ type: 'text', text: JSON.stringify(result).slice(0, 60000) }] }) } catch (error) { return ok({ isError: true, content: [{ type: 'text', text: JSON.stringify({ error: error?.code ?? 'tool_failed', note: 'No automatic retry.' }) }] }) @@ -38,12 +40,13 @@ export async function handleRpc(connectors, message) { } export function startToolServer(connectors, { port = 0, host = '127.0.0.1' } = {}) { - const token = randomBytes(18).toString('hex') - const path = `/mcp/${token}` + const path = `/mcp/${randomBytes(18).toString('hex')}` + const ownerPath = `/mcp/${randomBytes(18).toString('hex')}` const server = createServer(async (req, res) => { const send = (status, value) => { const body = Buffer.from(JSON.stringify(value)); res.writeHead(status, { 'Content-Type': 'application/json', 'Content-Length': body.length, 'Cache-Control': 'no-store' }); res.end(body) } if (req.headers.origin !== undefined) return send(403, { error: 'forbidden' }) - if ((req.url || '').split('?')[0] !== path) return send(404, { error: 'not found' }) + const requestPath = (req.url || '').split('?')[0] + if (requestPath !== path && requestPath !== ownerPath) return send(404, { error: 'not found' }) if (req.method !== 'POST') { res.writeHead(405, { Allow: 'POST' }); return res.end() } const chunks = [] let size = 0 @@ -53,7 +56,7 @@ export function startToolServer(connectors, { port = 0, host = '127.0.0.1' } = { const message = JSON.parse(Buffer.concat(chunks).toString('utf8')) const batch = Array.isArray(message) const replies = [] - for (const item of batch ? message : [message]) { const reply = await handleRpc(connectors, item); if (reply) replies.push(reply) } + for (const item of batch ? message : [message]) { const reply = await handleRpc(connectors, item, {automaticReads:requestPath === ownerPath}); if (reply) replies.push(reply) } if (!replies.length) { res.writeHead(202); return res.end() } send(200, batch ? replies : replies[0]) } catch { if (!res.headersSent) send(400, { error: 'bad request' }) } @@ -63,7 +66,14 @@ export function startToolServer(connectors, { port = 0, host = '127.0.0.1' } = { server.once('error', reject) server.listen(port, host, () => resolve(`http://${host}:${server.address().port}${path}`)) }) - return { server, ready, close: () => new Promise(resolve => server.close(() => resolve())) } + async function ownerPrivateToolUrl(candidate) { + if (typeof candidate !== 'string') return undefined + const normal = await ready + const [base, version] = candidate.split('?') + if (base !== normal) return undefined + return normal.slice(0, -path.length) + ownerPath + (version ? `?${version}` : '') + } + return { server, ready, ownerPrivateToolUrl, close: () => new Promise(resolve => server.close(() => resolve())) } } // Save/attach the capability on the user's Main Bot once the runtime wrapper @@ -76,7 +86,7 @@ export async function syncCapability({ rt, mainBot }, url, version, wanted) { if (attached) await rt.changeCapabilityAttachment('detach', { name: CAPABILITY }, botId).catch(() => {}) return false } - await rt.capabilitySave({ name: CAPABILITY, kind: 'mcp', description: 'Owner\'s connected apps (Composio + MCP servers); every call needs owner approval', transport: 'streamable-http', url: `${url}?v=${version}` }, { ui: true }) + await rt.capabilitySave({ name: CAPABILITY, kind: 'mcp', description: "Owner's connected apps. Known Composio reads run automatically in private chats. Other calls require approval.", transport: 'streamable-http', url: `${url}?v=${version}` }, { ui: true }) if (!attached) await rt.changeCapabilityAttachment('attach', { name: CAPABILITY }, botId) return true } diff --git a/runtime/flybot-workspace-web/test/connector-private-tools.test.js b/runtime/flybot-workspace-web/test/connector-private-tools.test.js new file mode 100644 index 000000000..cac0f075a --- /dev/null +++ b/runtime/flybot-workspace-web/test/connector-private-tools.test.js @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import {startToolServer} from '../features/connectors/tool-server.js' + +test('only the private native MCP endpoint can opt into automatic Composio reads', async t => { + const seen = [] + const tools = startToolServer({ + async callTool(_name, _args, options) { + seen.push(options.automaticReads) + return {success:true} + }, + }) + t.after(tools.close) + const manual = await tools.ready + const owner = await tools.ownerPrivateToolUrl(manual + '?v=7') + assert.notEqual(new URL(owner).pathname, new URL(manual).pathname) + assert.equal(new URL(owner).search, '?v=7') + assert.equal(await tools.ownerPrivateToolUrl('https://example.com/mcp?v=7'), undefined) + + const call = (url, headers = {}) => fetch(url, { + method:'POST', headers:{'Content-Type':'application/json', ...headers}, + body:JSON.stringify({jsonrpc:'2.0', id:1, method:'tools/call', + params:{name:'GITHUB_CHECK_IF_PULL_REQUEST_MERGED', arguments:{pull_number:1}}}), + }) + const ordinary = await call(manual + '?automaticReads=true') + assert.equal(ordinary.status, 200) + const privateChat = await call(owner) + assert.equal(privateChat.status, 200) + const browser = await call(owner, {Origin:'https://botawaken.com'}) + assert.equal(browser.status, 403) + assert.deepEqual(seen, [false,true]) +}) diff --git a/runtime/flybot-workspace-web/test/connectors.test.js b/runtime/flybot-workspace-web/test/connectors.test.js index 47e8afb2c..c12851932 100644 --- a/runtime/flybot-workspace-web/test/connectors.test.js +++ b/runtime/flybot-workspace-web/test/connectors.test.js @@ -14,7 +14,7 @@ const KEY = 'ck_test_' + 'z'.repeat(20) const identity = { instanceId: 'a'.repeat(32) } const USER = 'flybot-workspace-' + 'a'.repeat(32) -function fakeComposio() { +function fakeComposio({ githubTools = ['GITHUB_LIST_REPOS'] } = {}) { const calls = [] const accounts = new Map() const transport = async (method, url, headers, body) => { @@ -31,9 +31,10 @@ function fakeComposio() { if (p.startsWith('/connected_accounts/') && method === 'DELETE') { accounts.delete(decodeURIComponent(p.split('/').pop())); return reply({}) } if (p === '/tools') { const toolkit = u.searchParams.get('toolkit_slug') - const tool = toolkit === 'slack' ? 'SLACK_LIST_CHANNELS' : 'GITHUB_LIST_REPOS' + const tools = toolkit === 'slack' ? ['SLACK_LIST_CHANNELS'] : githubTools return reply({ items: [ - { slug: tool, version: '1.0', toolkit: { slug: toolkit }, description: 'List resources', input_parameters: { type: 'object', properties: {} } }, + ...tools.map(slug => ({ slug, version: '1.0', toolkit: { slug: toolkit }, description: 'Read-only action', + annotations: { readOnlyHint: true }, input_parameters: { type: 'object', properties: {} } })), { slug: 'COMPOSIO_SEARCH', version: '1', toolkit: { slug: toolkit }, input_parameters: {} }, ] }) } @@ -202,7 +203,7 @@ test('custom MCP servers: public HTTPS only, bearer sealed, endpoint change need assert.equal((await v1('DELETE', `/v1/mcp/servers/${id}`)).status, 404) }) -test('every tool call waits for the owner: pending → approve → runs once, scrubbed', async () => { +test('manual tool calls wait for the owner, run once, and scrub credentials', async () => { const { api, v1, composio, mcp } = make() await v1('POST', '/v1/composio/key', { api_key: KEY }) await v1('POST', '/v1/composio/connections', { toolkit: 'github' }) @@ -322,6 +323,66 @@ test('the pending approval view returns only a boolean without writing expired s assert.equal((await v1('GET',path)).body.items[0].status,'expired') }) +test('verified GitHub reads run automatically only for a trusted private call', async () => { + const read = 'GITHUB_CHECK_IF_PULL_REQUEST_MERGED' + const alias = 'GITHUB_CHECK_IF_PULL_REQUEST_HAS_BEEN_MERGED' + const history = 'GITHUB_LIST_REPOS' + const write = 'GITHUB_CREATE_AN_ISSUE' + const unknown = 'GITHUB_GET_UNVERIFIED_ACTION' + const upstream = fakeComposio({githubTools:[read,alias,history,write,unknown]}) + const { api } = make({transport:upstream.transport}) + api.saveKey({api_key: KEY}) + await api.connect({toolkit:'github'}) + await api.syncConnections() + const args = {owner:'fixture',repo:'example',pull_number:5} + + const shared = await api.callTool(read,args,{waitMs:0}) + assert.equal(shared.error,'tool_pending') + const privateReceipt = api.propose(read,args,{automaticReads:true}) + assert.notEqual(privateReceipt.id,shared.approval_id) + assert.equal(await api.run(privateReceipt.id),null) + assert.equal(upstream.calls.filter(call => call.path.includes('/tools/execute/')).length,0) + + for (const name of [read,alias,history]) { + const result = await api.callTool(name,args,{automaticReads:true,waitMs:0}) + assert.equal(result.successful,true) + assert.notEqual(result.data.echo,KEY) + } + for (const name of [write,unknown]) { + assert.equal((await api.callTool(name,args,{automaticReads:true,waitMs:0})).error,'tool_pending') + } + api.saveServer({name:'Remote',url:'https://mcp.example/mcp'}) + const mcpTool = (await api.discover()).find(tool=>tool.description.startsWith('Remote:')) + assert.equal((await api.callTool(mcpTool.name,{}, {automaticReads:true,waitMs:0})).error,'tool_pending') + assert.deepEqual(upstream.calls.filter(call => call.path.includes('/tools/execute/')) + .map(call=>[call.path.split('/').at(-1),call.body.connected_account_id,call.body.user_id]), + [read,alias,history].map(name=>[name,'ca_1',USER])) + const items = api.approvals().items + assert.equal(items.find(row=>row.id===shared.approval_id).status,'pending') + assert.ok(items.slice(0,4).every(row=>row.status==='pending')) + assert.deepEqual(items.filter(row=>row.approval_mode==='automatic_read').map(row=>row.status), + ['succeeded','succeeded','succeeded']) +}) + +test('a burst of automatic read history preserves a write still waiting for approval', async () => { + const read = 'GITHUB_LIST_REPOS' + const write = 'GITHUB_CREATE_AN_ISSUE' + const upstream = fakeComposio({githubTools:[read,write]}) + const { api, tick } = make({transport:upstream.transport}) + api.saveKey({api_key:KEY}) + await api.connect({toolkit:'github'}) + await api.syncConnections() + const pending = await api.callTool(write,{title:'Fixture'},{automaticReads:true,waitMs:0}) + assert.equal(pending.error,'tool_pending') + for (let i = 0; i < 105; i += 1) { + tick(1) + assert.equal((await api.callTool(read,{page:i+1},{automaticReads:true,waitMs:0})).successful,true) + } + assert.equal(api.approvals().items[0].id,pending.approval_id) + assert.equal(api.approvals().items[0].status,'pending') + assert.equal(api.store.read().calls.length,100) +}) + test('MCP endpoint and IP policy', () => { for (const ip of ['8.8.8.8', '2606:4700::1111']) assert.equal(publicIp(ip), true, ip) for (const ip of ['10.0.0.1', '127.0.0.1', '169.254.1.1', '100.64.0.1', '192.168.1.1', '::1', 'fd00::1', '::ffff:8.8.8.8', '2001:db8::1', '2002::1', '64:ff9b::808:808']) assert.equal(publicIp(ip), false, ip) diff --git a/tests/settings_page.test.mjs b/tests/settings_page.test.mjs index d7057c474..56203890d 100644 --- a/tests/settings_page.test.mjs +++ b/tests/settings_page.test.mjs @@ -1084,7 +1084,7 @@ test('connected-tool approvals do not imply a connected account before key setup assert.doesNotMatch(source, /innerHTML/); }); -test('native approvals render without a legacy task id and still require one explicit decision', async () => { +test('verified read activity has no approval buttons and native writes require one explicit decision', async () => { const {doc} = settingsDocument(); let section; doc.getElementById('composio-key-card').after = node => { section = node; }; @@ -1098,23 +1098,29 @@ test('native approvals render without a legacy task id and still require one exp return createElement(tag); }; const id = 'a'.repeat(32); - const item = {id, name: 'GITHUB_LIST_REPOSITORIES', status: 'pending', task_id: null, - arguments: {visibility: 'public'}, account: {toolkit: 'github', account_id: 'fixture'}, prompt: ''}; + const item = {id, name: 'GITHUB_CREATE_ISSUE', status: 'pending', task_id: null, + arguments: {title: 'fixture issue'}, account: {toolkit: 'github', account_id: 'fixture'}, prompt: ''}; + const read = {...item, id: 'c'.repeat(32), name: 'GITHUB_GET_A_PULL_REQUEST', status: 'succeeded', + approval_mode: 'automatic_read', arguments: {pull_number: 17}}; const decisions = []; const view = await mountToolApprovals(doc, async (path, options) => { if (options?.method === 'POST') { decisions.push({path, csrf: options.headers['X-CSRF-Token'], body: JSON.parse(options.body)}); return {ok: true}; } - return {ok: true, json: async () => ({items: [item, {...item, id: 'b'.repeat(32), task_id: 'legacy-1234'}]})}; + return {ok: true, json: async () => ({items: [item, {...item, id: 'b'.repeat(32), task_id: 'legacy-1234'}, read]})}; }, null); const list = section.children[2]; assert.deepEqual(list.children, []); await view.refresh(); - const [native, legacy] = list.children; - assert.equal(native.children[0].textContent, 'GITHUB_LIST_REPOSITORIES · pending'); - assert.match(native.children[2].textContent, /"visibility": "public"/); + const [native, legacy, automatic] = list.children; + assert.match(section.children[1].textContent, /在私聊里.*只读查询.*会自动执行。/); + assert.match(section.children[1].textContent, /其他工具调用需要确认。/); + assert.equal(native.children[0].textContent, 'GITHUB_CREATE_ISSUE · 待确认'); + assert.match(native.children[2].textContent, /"title": "fixture issue"/); assert.match(legacy.children[0].textContent, / · 任务 legacy-1$/); + assert.equal(automatic.children[0].textContent, 'GITHUB_GET_A_PULL_REQUEST · 自动只读 · 已完成'); + assert.equal(automatic.children.some(node => node.tagName === 'button'), false); assert.deepEqual(decisions, []); const approve = native.children.find(node => node.textContent === '允许此调用一次'); await approve.handlers.click[0]();