mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
feat(cloud): sync desktop MCP servers into Orca Cloud VMs on connect; relay agent OAuth loopback callbacks to the host
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import { BrowserWindow, ipcMain } from 'electron'
|
||||
import type { McpSyncStatus } from '../../../shared/agent-mcp-sync/mcp-sync-contract'
|
||||
import { CLOUD_MCP_SYNC_CHANGED_CHANNEL } from '../../../shared/agent-mcp-sync/mcp-sync-preferences'
|
||||
import {
|
||||
createCloudMcpSync,
|
||||
type CloudMcpSync,
|
||||
type CloudMcpSyncPreferences
|
||||
} from './cloud-mcp-sync'
|
||||
|
||||
let instance: CloudMcpSync | null = null
|
||||
|
||||
function environmentIdOf(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= 256 ? value : null
|
||||
}
|
||||
|
||||
function preferencesOf(value: unknown): Partial<CloudMcpSyncPreferences> {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return {}
|
||||
}
|
||||
const raw = value as Record<string, unknown>
|
||||
return {
|
||||
...(typeof raw.autoSync === 'boolean' ? { autoSync: raw.autoSync } : {}),
|
||||
...(Array.isArray(raw.excluded)
|
||||
? {
|
||||
excluded: raw.excluded
|
||||
.filter((key): key is string => typeof key === 'string' && key.length <= 200)
|
||||
.slice(0, 512)
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
/** Orca Cloud builds only; other builds answer null so the renderer hides the affordance. */
|
||||
export function installCloudMcpSync(userDataPath: string): CloudMcpSync {
|
||||
instance ??= createCloudMcpSync({
|
||||
userDataPath,
|
||||
broadcast: (status: McpSyncStatus) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(CLOUD_MCP_SYNC_CHANGED_CHANNEL, status)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
return instance
|
||||
}
|
||||
|
||||
const CHANNELS = [
|
||||
'cloudMcpSync:getStatus',
|
||||
'cloudMcpSync:syncNow',
|
||||
'cloudMcpSync:setPreferences',
|
||||
'cloudMcpSync:getPreferences'
|
||||
] as const
|
||||
|
||||
export function registerCloudMcpSyncHandlers(): void {
|
||||
for (const channel of CHANNELS) {
|
||||
ipcMain.removeHandler(channel)
|
||||
}
|
||||
ipcMain.handle('cloudMcpSync:getStatus', (_event, value: unknown) => {
|
||||
const environmentId = environmentIdOf(value)
|
||||
return environmentId && instance ? instance.getStatus(environmentId) : null
|
||||
})
|
||||
ipcMain.handle('cloudMcpSync:syncNow', (_event, value: unknown) => {
|
||||
const environmentId = environmentIdOf(value)
|
||||
return environmentId && instance ? instance.sync(environmentId, 'manual') : null
|
||||
})
|
||||
ipcMain.handle('cloudMcpSync:setPreferences', (_event, value: unknown) =>
|
||||
instance ? instance.setPreferences(preferencesOf(value)) : null
|
||||
)
|
||||
ipcMain.handle('cloudMcpSync:getPreferences', () => instance?.getPreferences() ?? null)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
AGENT_MCP_SYNC_METHOD,
|
||||
AgentMcpSyncResult,
|
||||
type McpSyncStatus
|
||||
} from '../../../shared/agent-mcp-sync/mcp-sync-contract'
|
||||
import { applyMcpSyncResult, planMcpSync } from '../../../shared/agent-mcp-sync/mcp-sync-plan'
|
||||
import { listEphemeralVmRuntimes } from '../../../shared/ephemeral-vm-runtime-store'
|
||||
import { writeFileAtomically } from '../../filesystem/atomic-file-publication'
|
||||
import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing'
|
||||
import type { CloudMcpSyncPreferences } from '../../../shared/agent-mcp-sync/mcp-sync-preferences'
|
||||
import { readLocalMcpConfig, type LocalMcpConfig } from './local-mcp-config-read'
|
||||
|
||||
const SYNC_TIMEOUT_MS = 30_000
|
||||
|
||||
export type { CloudMcpSyncPreferences }
|
||||
|
||||
const DEFAULT_PREFERENCES: CloudMcpSyncPreferences = { autoSync: true, excluded: [] }
|
||||
|
||||
export type CloudMcpSyncDeps = {
|
||||
userDataPath: string
|
||||
broadcast: (status: McpSyncStatus) => void
|
||||
readLocal?: (repoPath: string | null) => Promise<LocalMcpConfig>
|
||||
call?: (environmentId: string, params: unknown) => Promise<unknown>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
export type CloudMcpSync = {
|
||||
isCloudEnvironment(environmentId: string): boolean
|
||||
getStatus(environmentId: string): Promise<McpSyncStatus | null>
|
||||
sync(environmentId: string, trigger: 'connect' | 'manual'): Promise<McpSyncStatus | null>
|
||||
getPreferences(): CloudMcpSyncPreferences
|
||||
setPreferences(next: Partial<CloudMcpSyncPreferences>): CloudMcpSyncPreferences
|
||||
}
|
||||
|
||||
class RuntimeCallError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly code: string | undefined
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
function errorCode(error: unknown): McpSyncStatus['error'] {
|
||||
const code =
|
||||
typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : ''
|
||||
if (code === 'method_not_found') {
|
||||
return 'host-outdated'
|
||||
}
|
||||
return /unavailable|timeout|unreachable/.test(code) ? 'host-unreachable' : 'failed'
|
||||
}
|
||||
|
||||
/** Mirrors this computer's MCP servers into each Orca Cloud workspace's agent configs. */
|
||||
export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync {
|
||||
const preferencesPath = join(deps.userDataPath, 'cloud-mcp-sync.json')
|
||||
const statuses = new Map<string, McpSyncStatus>()
|
||||
const queues = new Map<string, Promise<unknown>>()
|
||||
const now = deps.now ?? Date.now
|
||||
const readLocal = deps.readLocal ?? ((repoPath) => readLocalMcpConfig(repoPath))
|
||||
const call =
|
||||
deps.call ??
|
||||
(async (environmentId: string, params: unknown) => {
|
||||
const response = await callRuntimeEnvironment(
|
||||
deps.userDataPath,
|
||||
environmentId,
|
||||
AGENT_MCP_SYNC_METHOD,
|
||||
params,
|
||||
SYNC_TIMEOUT_MS
|
||||
)
|
||||
if (response.ok) {
|
||||
return response.result
|
||||
}
|
||||
throw new RuntimeCallError(response.error.message, response.error.code)
|
||||
})
|
||||
|
||||
let preferences: CloudMcpSyncPreferences | null = null
|
||||
function getPreferences(): CloudMcpSyncPreferences {
|
||||
if (!preferences) {
|
||||
try {
|
||||
const parsed = JSON.parse(
|
||||
readFileSync(preferencesPath, 'utf8')
|
||||
) as Partial<CloudMcpSyncPreferences>
|
||||
preferences = {
|
||||
autoSync: parsed.autoSync !== false,
|
||||
excluded: Array.isArray(parsed.excluded)
|
||||
? parsed.excluded.filter((key): key is string => typeof key === 'string')
|
||||
: []
|
||||
}
|
||||
} catch {
|
||||
preferences = { ...DEFAULT_PREFERENCES, excluded: [] }
|
||||
}
|
||||
}
|
||||
return preferences
|
||||
}
|
||||
|
||||
function cloudRuntime(environmentId: string) {
|
||||
return listEphemeralVmRuntimes(deps.userDataPath).find(
|
||||
(runtime) =>
|
||||
runtime.runtimeEnvironmentId === environmentId && runtime.recipe?.provider === 'orca-cloud'
|
||||
)
|
||||
}
|
||||
|
||||
async function plan(environmentId: string) {
|
||||
const runtime = cloudRuntime(environmentId)
|
||||
const local = await readLocal(runtime?.repoPath ?? null)
|
||||
return planMcpSync({
|
||||
servers: local.servers,
|
||||
excluded: new Set(getPreferences().excluded),
|
||||
repoServerNames: local.repoServerNames,
|
||||
homeDir: homedir()
|
||||
})
|
||||
}
|
||||
|
||||
function publish(status: McpSyncStatus): McpSyncStatus {
|
||||
statuses.set(status.environmentId, status)
|
||||
deps.broadcast(status)
|
||||
return status
|
||||
}
|
||||
|
||||
/** What a sync would send, before any host has answered. */
|
||||
async function preview(environmentId: string): Promise<McpSyncStatus> {
|
||||
const { rows } = await plan(environmentId)
|
||||
return {
|
||||
environmentId,
|
||||
autoSync: getPreferences().autoSync,
|
||||
running: false,
|
||||
lastSyncedAt: null,
|
||||
error: null,
|
||||
rows
|
||||
}
|
||||
}
|
||||
|
||||
async function run(environmentId: string): Promise<McpSyncStatus> {
|
||||
const { params, rows } = await plan(environmentId)
|
||||
const previous = statuses.get(environmentId)
|
||||
publish({
|
||||
environmentId,
|
||||
autoSync: getPreferences().autoSync,
|
||||
running: true,
|
||||
lastSyncedAt: previous?.lastSyncedAt ?? null,
|
||||
error: null,
|
||||
rows: previous?.rows.length ? previous.rows : rows
|
||||
})
|
||||
try {
|
||||
const result = AgentMcpSyncResult.parse(await call(environmentId, params))
|
||||
const applied = applyMcpSyncResult(rows, result)
|
||||
const synced = applied.filter((row) => row.state === 'synced').length
|
||||
console.info(
|
||||
`[cloud-mcp-sync] ${environmentId}: ${synced} synced, ${applied.length - synced} skipped`
|
||||
)
|
||||
return publish({
|
||||
environmentId,
|
||||
autoSync: getPreferences().autoSync,
|
||||
running: false,
|
||||
lastSyncedAt: now(),
|
||||
error: null,
|
||||
rows: applied
|
||||
})
|
||||
} catch (error) {
|
||||
const code = errorCode(error)
|
||||
console.warn(`[cloud-mcp-sync] ${environmentId}: sync failed (${code})`)
|
||||
return publish({
|
||||
environmentId,
|
||||
autoSync: getPreferences().autoSync,
|
||||
running: false,
|
||||
lastSyncedAt: previous?.lastSyncedAt ?? null,
|
||||
error: code,
|
||||
rows
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isCloudEnvironment: (environmentId) => cloudRuntime(environmentId) !== undefined,
|
||||
async getStatus(environmentId) {
|
||||
if (!cloudRuntime(environmentId)) {
|
||||
return null
|
||||
}
|
||||
return statuses.get(environmentId) ?? preview(environmentId)
|
||||
},
|
||||
sync(environmentId, trigger) {
|
||||
if (!cloudRuntime(environmentId)) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
if (trigger === 'connect' && !getPreferences().autoSync) {
|
||||
return Promise.resolve(statuses.get(environmentId) ?? null)
|
||||
}
|
||||
// One sync per workspace at a time; a click during an auto-sync runs after it.
|
||||
const next = (queues.get(environmentId) ?? Promise.resolve())
|
||||
.catch(() => {})
|
||||
.then(() => run(environmentId))
|
||||
queues.set(environmentId, next)
|
||||
return next
|
||||
},
|
||||
getPreferences,
|
||||
setPreferences(next) {
|
||||
const merged: CloudMcpSyncPreferences = {
|
||||
autoSync: next.autoSync ?? getPreferences().autoSync,
|
||||
excluded: [...new Set(next.excluded ?? getPreferences().excluded)].sort()
|
||||
}
|
||||
writeFileAtomically(preferencesPath, `${JSON.stringify(merged, null, 2)}\n`)
|
||||
preferences = merged
|
||||
for (const status of statuses.values()) {
|
||||
publish({ ...status, autoSync: merged.autoSync })
|
||||
}
|
||||
return merged
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { parse as parseToml } from 'smol-toml'
|
||||
import type { LocalMcpServer } from '../../../shared/agent-mcp-sync/mcp-sync-plan'
|
||||
import { getSystemCodexHomePath } from '../../codex/configuration/homes/codex-home-paths'
|
||||
|
||||
// ~/.claude.json also holds chat history per project; refuse anything absurd rather than buffer it.
|
||||
const MAX_CONFIG_BYTES = 32 * 1024 * 1024
|
||||
|
||||
export type LocalMcpConfigPaths = {
|
||||
claudeConfig: string
|
||||
codexConfig: string
|
||||
}
|
||||
|
||||
export function defaultLocalMcpConfigPaths(
|
||||
env: NodeJS.ProcessEnv = process.env
|
||||
): LocalMcpConfigPaths {
|
||||
const claudeDir = env.CLAUDE_CONFIG_DIR?.trim()
|
||||
return {
|
||||
claudeConfig: claudeDir ? join(claudeDir, '.claude.json') : join(homedir(), '.claude.json'),
|
||||
codexConfig: join(env.CODEX_HOME?.trim() || getSystemCodexHomePath(), 'config.toml')
|
||||
}
|
||||
}
|
||||
|
||||
async function readBounded(path: string): Promise<string | null> {
|
||||
try {
|
||||
const buffer = await readFile(path)
|
||||
return buffer.byteLength > MAX_CONFIG_BYTES ? null : buffer.toString('utf8')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function entries(value: unknown): [string, unknown][] {
|
||||
return isRecord(value) ? Object.entries(value) : []
|
||||
}
|
||||
|
||||
function parseJson(text: string | null): unknown {
|
||||
if (text === null) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Claude keys projects by the path it was started in; Windows paths may be stored either way.
|
||||
function projectEntry(projects: unknown, repoPath: string): unknown {
|
||||
if (!isRecord(projects)) {
|
||||
return undefined
|
||||
}
|
||||
const wanted = repoPath.replace(/\\/g, '/').replace(/\/+$/, '')
|
||||
for (const [path, entry] of Object.entries(projects)) {
|
||||
if (path.replace(/\\/g, '/').replace(/\/+$/, '') === wanted) {
|
||||
return entry
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export type LocalMcpConfig = {
|
||||
servers: LocalMcpServer[]
|
||||
/** Server names in the repo's own `.mcp.json`, which already travels with the checkout. */
|
||||
repoServerNames: Set<string>
|
||||
}
|
||||
|
||||
/** Read this computer's Claude Code (user + this repo's local scope) and Codex MCP servers. */
|
||||
export async function readLocalMcpConfig(
|
||||
repoPath: string | null,
|
||||
paths: LocalMcpConfigPaths = defaultLocalMcpConfigPaths()
|
||||
): Promise<LocalMcpConfig> {
|
||||
const servers: LocalMcpServer[] = []
|
||||
const claude = parseJson(await readBounded(paths.claudeConfig))
|
||||
if (isRecord(claude)) {
|
||||
for (const [name, config] of entries(claude.mcpServers)) {
|
||||
servers.push({ agent: 'claude', name, source: 'claude-user', config })
|
||||
}
|
||||
const project = repoPath ? projectEntry(claude.projects, repoPath) : undefined
|
||||
for (const [name, config] of entries(isRecord(project) ? project.mcpServers : null)) {
|
||||
servers.push({ agent: 'claude', name, source: 'claude-project', config })
|
||||
}
|
||||
}
|
||||
const codexText = await readBounded(paths.codexConfig)
|
||||
if (codexText !== null) {
|
||||
try {
|
||||
const codex = parseToml(codexText) as Record<string, unknown>
|
||||
for (const [name, config] of entries(codex.mcp_servers)) {
|
||||
servers.push({ agent: 'codex', name, source: 'codex', config })
|
||||
}
|
||||
} catch {
|
||||
// An unloadable config has no servers Codex itself would start either.
|
||||
}
|
||||
}
|
||||
const repoMcp = repoPath ? parseJson(await readBounded(join(repoPath, '.mcp.json'))) : null
|
||||
const repoServerNames = new Set(
|
||||
entries(isRecord(repoMcp) ? repoMcp.mcpServers : null).map(([name]) => name)
|
||||
)
|
||||
return { servers, repoServerNames }
|
||||
}
|
||||
@@ -34,6 +34,10 @@ import {
|
||||
} from './hosted-workspace-runtime'
|
||||
import { callRuntimeEnvironment } from '../ipc/runtime-environments/runtime-environment-transport-routing'
|
||||
import type { HostedSessionRestartResult } from '../../shared/hosted-sandbox/hosted-session-events'
|
||||
import {
|
||||
installCloudMcpSync,
|
||||
registerCloudMcpSyncHandlers
|
||||
} from '../agent-mcp-sync/desktop/cloud-mcp-sync-ipc'
|
||||
|
||||
/** Capability Orca Cloud auth grants per account (stablyai/orca-cloud#689). */
|
||||
export const ORCA_CLOUD_SANDBOX_CAPABILITY = 'sandbox'
|
||||
@@ -54,6 +58,7 @@ export function installHostedSandbox(): void {
|
||||
ipcMain.handle('orcaCloud:restartNow', (_event, args: { workspaceId: string }) =>
|
||||
restartHostedWorkspace(args.workspaceId)
|
||||
)
|
||||
registerCloudMcpSyncHandlers()
|
||||
const userDataPath = app.getPath('userData')
|
||||
const config = getHostedSandboxConfig(
|
||||
userDataPath,
|
||||
@@ -67,6 +72,7 @@ export function installHostedSandbox(): void {
|
||||
const client = createHostedSandboxRecipeClient(config)
|
||||
const base = createHostedSandboxRecipeDriver(config, client)
|
||||
controlPlaneClient = client
|
||||
const mcpSync = installCloudMcpSync(userDataPath)
|
||||
// Dev rehearsals shorten idle sleep; packaged builds always use the provider's default.
|
||||
const idleOverride = app.isPackaged
|
||||
? Number.NaN
|
||||
@@ -77,7 +83,8 @@ export function installHostedSandbox(): void {
|
||||
const registry = createHostedSessionRegistry({
|
||||
userDataPath,
|
||||
driver,
|
||||
windows: () => BrowserWindow.getAllWindows()
|
||||
windows: () => BrowserWindow.getAllWindows(),
|
||||
onConnected: (runtimeEnvironmentId) => void mcpSync.sync(runtimeEnvironmentId, 'connect')
|
||||
})
|
||||
const workspaces = installHostedWorkspaceService({
|
||||
userDataPath,
|
||||
|
||||
@@ -58,6 +58,8 @@ export function createHostedSessionRegistry(deps: {
|
||||
driver: HostedEnvironmentProviderDriver
|
||||
windows: () => readonly BrowserWindow[]
|
||||
log?: (line: string) => void
|
||||
/** Each time a running workspace's orcad is first reached in this app session (including after resume). */
|
||||
onConnected?: (runtimeEnvironmentId: string) => void
|
||||
}): HostedSessionRegistry {
|
||||
const running = new Map<string, Running>()
|
||||
const log = deps.log ?? ((line: string) => console.error(line))
|
||||
@@ -161,6 +163,7 @@ export function createHostedSessionRegistry(deps: {
|
||||
workspaceId: runtime.workspaceId ?? null
|
||||
})
|
||||
scheduler.start()
|
||||
deps.onConnected?.(runtimeEnvironmentId)
|
||||
log(`[orca-cloud] lease scheduler started for ${runtime.workspaceName ?? runtime.id}`)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Validates the untrusted IPC payloads that open or close a sign-in callback forward.
|
||||
import type {
|
||||
AuthCallbackForwardRequest,
|
||||
LoopbackCallbackForwardRequest
|
||||
} from '../../../shared/auth-callback-forward'
|
||||
|
||||
function field(value: unknown, name: string): unknown {
|
||||
return value && typeof value === 'object'
|
||||
? Object.getOwnPropertyDescriptor(value, name)?.value
|
||||
: undefined
|
||||
}
|
||||
|
||||
function callbackPortOf(value: unknown): number | null {
|
||||
const port = field(value, 'port')
|
||||
return typeof port === 'number' && Number.isInteger(port) && port >= 1024 && port <= 65_535
|
||||
? port
|
||||
: null
|
||||
}
|
||||
|
||||
export function flowOf(
|
||||
value: unknown
|
||||
): Pick<AuthCallbackForwardRequest, 'environmentId' | 'flowId'> | null {
|
||||
const environmentId = field(value, 'environmentId')
|
||||
const flowId = field(value, 'flowId')
|
||||
return typeof environmentId === 'string' && typeof flowId === 'string'
|
||||
? { environmentId, flowId }
|
||||
: null
|
||||
}
|
||||
|
||||
export function requestOf(value: unknown): AuthCallbackForwardRequest | null {
|
||||
const flow = flowOf(value)
|
||||
const port = callbackPortOf(value)
|
||||
return flow && port !== null ? { ...flow, port } : null
|
||||
}
|
||||
|
||||
/** An agent's own OAuth callback on the host: no Orca sign-in flow, just the port it listens on. */
|
||||
export function loopbackRequestOf(value: unknown): LoopbackCallbackForwardRequest | null {
|
||||
const environmentId = field(value, 'environmentId')
|
||||
const port = callbackPortOf(value)
|
||||
return typeof environmentId === 'string' && port !== null ? { environmentId, port } : null
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type AuthCallbackForwardRequest,
|
||||
type AuthCallbackForwardResult
|
||||
} from '../../../shared/auth-callback-forward'
|
||||
import { flowOf, loopbackRequestOf, requestOf } from './auth-callback-forward-requests'
|
||||
import { BrowserNetworkTunnelClient } from '../../browser/network/tunnels/browser-network-tunnel-client'
|
||||
import { BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL } from '../../browser/network/tunnels/browser-network-tunnel-stream-state'
|
||||
import { ensureOrcadManagedTunnel } from '../../managed-server/lifecycle/orcad-managed-tunnel'
|
||||
@@ -25,11 +26,17 @@ const ATTACH_TIMEOUT_MS = 20_000
|
||||
export type AuthCallbackTunnel = { client: BrowserNetworkTunnelClient; close: () => void }
|
||||
/** Opens the host end of one sign-in's forward; injectable so tests can wire it in-process. */
|
||||
export type AuthCallbackTunnelOpener = (onClosed: () => void) => Promise<AuthCallbackTunnel>
|
||||
/** A sign-in's callback (flowId) or, without one, any OAuth callback an agent on the host listens for. */
|
||||
export type AuthCallbackForwardTarget = {
|
||||
environmentId: string
|
||||
port: number
|
||||
flowId: string | null
|
||||
}
|
||||
|
||||
/** Opens the host end: a tunnel that reaches only this flow's callback port there. */
|
||||
async function openHostTunnel(
|
||||
userDataPath: string,
|
||||
request: AuthCallbackForwardRequest,
|
||||
request: AuthCallbackForwardTarget,
|
||||
onClosed: () => void
|
||||
): Promise<AuthCallbackTunnel> {
|
||||
await ensureOrcadManagedTunnel(userDataPath, request.environmentId)
|
||||
@@ -45,8 +52,8 @@ async function openHostTunnel(
|
||||
}
|
||||
subscription = await subscribeRemoteRuntimeTransport(
|
||||
connection,
|
||||
'network.authCallbackTunnel',
|
||||
{ flowId: request.flowId },
|
||||
request.flowId === null ? 'network.loopbackCallbackTunnel' : 'network.authCallbackTunnel',
|
||||
request.flowId === null ? { port: request.port } : { flowId: request.flowId },
|
||||
ATTACH_TIMEOUT_MS,
|
||||
{
|
||||
onResponse: (response) => {
|
||||
@@ -129,7 +136,7 @@ export class AuthCallbackForward {
|
||||
private readonly ttl: ReturnType<typeof setTimeout>
|
||||
|
||||
constructor(
|
||||
readonly request: AuthCallbackForwardRequest,
|
||||
readonly request: AuthCallbackForwardTarget,
|
||||
private readonly onClosed: () => void
|
||||
) {
|
||||
this.ttl = setTimeout(() => this.close(), TTL_MS)
|
||||
@@ -235,36 +242,8 @@ export class AuthCallbackForward {
|
||||
}
|
||||
|
||||
const forwards = new Map<string, AuthCallbackForward>()
|
||||
const keyOf = (request: Pick<AuthCallbackForwardRequest, 'environmentId' | 'flowId'>): string =>
|
||||
`${request.environmentId}\u0000${request.flowId}`
|
||||
|
||||
function field(value: unknown, name: string): unknown {
|
||||
return value && typeof value === 'object'
|
||||
? Object.getOwnPropertyDescriptor(value, name)?.value
|
||||
: undefined
|
||||
}
|
||||
|
||||
function flowOf(
|
||||
value: unknown
|
||||
): Pick<AuthCallbackForwardRequest, 'environmentId' | 'flowId'> | null {
|
||||
const environmentId = field(value, 'environmentId')
|
||||
const flowId = field(value, 'flowId')
|
||||
return typeof environmentId === 'string' && typeof flowId === 'string'
|
||||
? { environmentId, flowId }
|
||||
: null
|
||||
}
|
||||
|
||||
function requestOf(value: unknown): AuthCallbackForwardRequest | null {
|
||||
const flow = flowOf(value)
|
||||
const port = field(value, 'port')
|
||||
return flow &&
|
||||
typeof port === 'number' &&
|
||||
Number.isInteger(port) &&
|
||||
port >= 1024 &&
|
||||
port <= 65_535
|
||||
? { ...flow, port }
|
||||
: null
|
||||
}
|
||||
const keyOf = (request: { environmentId: string; flowId: string | null; port?: number }): string =>
|
||||
`${request.environmentId}\u0000${request.flowId ?? `port:${request.port}`}`
|
||||
|
||||
export function closeAuthCallbackForward(
|
||||
request: Pick<AuthCallbackForwardRequest, 'environmentId' | 'flowId'>
|
||||
@@ -274,25 +253,33 @@ export function closeAuthCallbackForward(
|
||||
|
||||
export async function openAuthCallbackForward(
|
||||
userDataPath: string,
|
||||
request: AuthCallbackForwardRequest
|
||||
request: AuthCallbackForwardRequest | AuthCallbackForwardTarget
|
||||
): Promise<AuthCallbackForwardResult> {
|
||||
const target: AuthCallbackForwardTarget = { ...request, flowId: request.flowId ?? null }
|
||||
// A retried sign-in replaces this computer's earlier listener on the same port.
|
||||
for (const existing of forwards.values()) {
|
||||
if (existing.request.port === request.port) {
|
||||
existing.close()
|
||||
}
|
||||
}
|
||||
const key = keyOf(request)
|
||||
const forward = new AuthCallbackForward(request, () => {
|
||||
const key = keyOf(target)
|
||||
const forward = new AuthCallbackForward(target, () => {
|
||||
if (forwards.get(key) === forward) {
|
||||
forwards.delete(key)
|
||||
}
|
||||
})
|
||||
forwards.set(key, forward)
|
||||
return forward.start((onClosed) => openHostTunnel(userDataPath, request, onClosed))
|
||||
return forward.start((onClosed) => openHostTunnel(userDataPath, target, onClosed))
|
||||
}
|
||||
|
||||
export function registerAuthCallbackForwardHandlers(getUserDataPath: () => string): void {
|
||||
// An agent on the host (an MCP server sign-in) waits on its own loopback callback; carry it there.
|
||||
ipcMain.handle('runtimeEnvironments:openLoopbackCallbackForward', (_event, value: unknown) => {
|
||||
const request = loopbackRequestOf(value)
|
||||
return request
|
||||
? openAuthCallbackForward(getUserDataPath(), { ...request, flowId: null })
|
||||
: { ok: false, code: 'listen_failed', message: 'Invalid sign-in forward.' }
|
||||
})
|
||||
ipcMain.handle('runtimeEnvironments:openAuthCallbackForward', (_event, value: unknown) => {
|
||||
const request = requestOf(value)
|
||||
return request
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineMethod, type RpcContext } from '../../core'
|
||||
import type { HostAccountSignInFlows } from '../../../agent-session/environment/host-account-sign-in-flows'
|
||||
import { createAuthCallbackTunnelMethod } from './auth-callback-tunnel'
|
||||
import { loopbackCallbackTunnelMethod } from './loopback-callback-tunnel'
|
||||
import {
|
||||
agentLaunchLoginEnv,
|
||||
createHostAgentSignInStatusChecker,
|
||||
@@ -59,5 +60,6 @@ export const agentSignInMethods = (
|
||||
return checkerFor(runtime).read(true)
|
||||
}
|
||||
}),
|
||||
createAuthCallbackTunnelMethod(flowsFor, ownerOf)
|
||||
createAuthCallbackTunnelMethod(flowsFor, ownerOf),
|
||||
loopbackCallbackTunnelMethod
|
||||
]
|
||||
|
||||
@@ -21,7 +21,8 @@ export function createAuthCallbackDialer(
|
||||
port: number,
|
||||
onExceeded: () => void,
|
||||
dial: (port: number) => Socket = (target) =>
|
||||
netConnect({ host: 'localhost', port: target, autoSelectFamily: true, allowHalfOpen: true })
|
||||
netConnect({ host: 'localhost', port: target, autoSelectFamily: true, allowHalfOpen: true }),
|
||||
onStreamClosed?: () => void
|
||||
): (target: { host: string; port: number }) => BrowserNetworkTunnelSocket {
|
||||
let streams = 0
|
||||
let bytes = 0
|
||||
@@ -42,6 +43,9 @@ export function createAuthCallbackDialer(
|
||||
}
|
||||
streams += 1
|
||||
const socket = dial(port)
|
||||
if (onStreamClosed) {
|
||||
socket.once('close', onStreamClosed)
|
||||
}
|
||||
const wrapper: BrowserNetworkTunnelSocket = {
|
||||
get destroyed() {
|
||||
return socket.destroyed
|
||||
@@ -90,6 +94,83 @@ export function createAuthCallbackDialer(
|
||||
}
|
||||
}
|
||||
|
||||
type CallbackGrant = { port: number; ended: AbortSignal }
|
||||
type TunnelEmit = (event: unknown) => void
|
||||
|
||||
/** Serves one binary tunnel to `grant.port` on loopback until the grant ends, the caller leaves or the TTL. */
|
||||
export async function serveCallbackTunnel(
|
||||
ctx: RpcContext,
|
||||
emit: TunnelEmit,
|
||||
grant: CallbackGrant,
|
||||
subscriptionKey: string,
|
||||
onStreamClosed?: () => void
|
||||
): Promise<void> {
|
||||
const { runtime, connectionId, sendBinary, registerBinaryMessageHandler, signal } = ctx
|
||||
if (!connectionId || !sendBinary || !registerBinaryMessageHandler || signal?.aborted) {
|
||||
return
|
||||
}
|
||||
const closed = Promise.withResolvers<void>()
|
||||
let session: BrowserNetworkTunnelSession | null = null
|
||||
let unregisterBinary = (): void => {}
|
||||
const close = (): void => session?.close()
|
||||
const ttl = setTimeout(close, AUTH_CALLBACK_TUNNEL_TTL_MS)
|
||||
const subscriptionId = JSON.stringify(['auth-callback-tunnel', connectionId, subscriptionKey])
|
||||
let cleaned = false
|
||||
const cleanup = (): void => {
|
||||
if (cleaned) {
|
||||
return
|
||||
}
|
||||
cleaned = true
|
||||
clearTimeout(ttl)
|
||||
grant.ended.removeEventListener('abort', close)
|
||||
signal?.removeEventListener('abort', close)
|
||||
unregisterBinary()
|
||||
close()
|
||||
closed.resolve()
|
||||
}
|
||||
session = new BrowserNetworkTunnelSession({
|
||||
tunnelGeneration: TUNNEL_GENERATION,
|
||||
connect: createAuthCallbackDialer(grant.port, close, undefined, onStreamClosed),
|
||||
sendBinary: (bytes) => sendBinary(bytes) !== false,
|
||||
flowControl: BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL,
|
||||
onClose: () => {
|
||||
try {
|
||||
emit({ type: 'closed', tunnelGeneration: TUNNEL_GENERATION })
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
}
|
||||
})
|
||||
console.info(`[auth-callback-tunnel] opened for port ${grant.port}`)
|
||||
unregisterBinary = registerBinaryMessageHandler((bytes) => session?.handleBinary(bytes))
|
||||
runtime.registerSubscriptionCleanup(subscriptionId, cleanup, connectionId)
|
||||
grant.ended.addEventListener('abort', close, { once: true })
|
||||
signal?.addEventListener('abort', close, { once: true })
|
||||
if (grant.ended.aborted || signal?.aborted) {
|
||||
close()
|
||||
} else {
|
||||
emit({ type: 'ready', tunnelGeneration: TUNNEL_GENERATION })
|
||||
}
|
||||
try {
|
||||
await closed.promise
|
||||
} finally {
|
||||
cleanup()
|
||||
console.info(`[auth-callback-tunnel] closed for port ${grant.port}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** The tunnel needs a desktop runtime client that can carry binary frames. */
|
||||
export function requireCallbackTunnelClient(ctx: RpcContext): void {
|
||||
const { connectionId, clientKind, clientCapabilities, sendBinary, registerBinaryMessageHandler } =
|
||||
ctx
|
||||
if (clientKind !== 'runtime' || !connectionId || !sendBinary || !registerBinaryMessageHandler) {
|
||||
throw new Error('authenticated_binary_auth_callback_tunnel_required')
|
||||
}
|
||||
if (!clientCapabilities?.includes(HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY)) {
|
||||
throw new Error('auth_callback_tunnel_capability_required')
|
||||
}
|
||||
}
|
||||
|
||||
/** Carries a desktop browser's redirect to the localhost callback of a sign-in this caller started here. */
|
||||
export function createAuthCallbackTunnelMethod(
|
||||
flowsFor: (runtime: OrcaRuntimeService) => HostAccountSignInFlows,
|
||||
@@ -100,82 +181,13 @@ export function createAuthCallbackTunnelMethod(
|
||||
permission: 'accounts-admin',
|
||||
params: AuthCallbackTunnelParams,
|
||||
handler: async (params, ctx, emit) => {
|
||||
const {
|
||||
runtime,
|
||||
connectionId,
|
||||
clientKind,
|
||||
clientCapabilities,
|
||||
sendBinary,
|
||||
registerBinaryMessageHandler,
|
||||
signal
|
||||
} = ctx
|
||||
if (
|
||||
clientKind !== 'runtime' ||
|
||||
!connectionId ||
|
||||
!sendBinary ||
|
||||
!registerBinaryMessageHandler
|
||||
) {
|
||||
throw new Error('authenticated_binary_auth_callback_tunnel_required')
|
||||
}
|
||||
if (!clientCapabilities?.includes(HOST_ACCOUNT_SIGN_IN_CALLBACK_RUNTIME_CAPABILITY)) {
|
||||
throw new Error('auth_callback_tunnel_capability_required')
|
||||
}
|
||||
const grant = flowsFor(runtime).callbackTarget(ownerOf(ctx), params.flowId)
|
||||
requireCallbackTunnelClient(ctx)
|
||||
const grant = flowsFor(ctx.runtime).callbackTarget(ownerOf(ctx), params.flowId)
|
||||
if (!grant) {
|
||||
throw new Error('auth_callback_not_waiting')
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
const closed = Promise.withResolvers<void>()
|
||||
let session: BrowserNetworkTunnelSession | null = null
|
||||
let unregisterBinary = (): void => {}
|
||||
const close = (): void => session?.close()
|
||||
const ttl = setTimeout(close, AUTH_CALLBACK_TUNNEL_TTL_MS)
|
||||
const subscriptionId = JSON.stringify(['auth-callback-tunnel', connectionId, params.flowId])
|
||||
let cleaned = false
|
||||
const cleanup = (): void => {
|
||||
if (cleaned) {
|
||||
return
|
||||
}
|
||||
cleaned = true
|
||||
clearTimeout(ttl)
|
||||
grant.ended.removeEventListener('abort', close)
|
||||
signal?.removeEventListener('abort', close)
|
||||
unregisterBinary()
|
||||
close()
|
||||
closed.resolve()
|
||||
}
|
||||
session = new BrowserNetworkTunnelSession({
|
||||
tunnelGeneration: TUNNEL_GENERATION,
|
||||
connect: createAuthCallbackDialer(grant.port, close),
|
||||
sendBinary: (bytes) => sendBinary(bytes) !== false,
|
||||
flowControl: BROWSER_NETWORK_TUNNEL_WINDOW_V2_FLOW_CONTROL,
|
||||
onClose: () => {
|
||||
try {
|
||||
emit({ type: 'closed', tunnelGeneration: TUNNEL_GENERATION })
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
}
|
||||
})
|
||||
console.info(`[auth-callback-tunnel] opened for port ${grant.port}`)
|
||||
unregisterBinary = registerBinaryMessageHandler((bytes) => session?.handleBinary(bytes))
|
||||
runtime.registerSubscriptionCleanup(subscriptionId, cleanup, connectionId)
|
||||
// The grant ends with the login: success, failure, cancel or the owner going silent.
|
||||
grant.ended.addEventListener('abort', close, { once: true })
|
||||
signal?.addEventListener('abort', close, { once: true })
|
||||
if (grant.ended.aborted || signal?.aborted) {
|
||||
close()
|
||||
} else {
|
||||
emit({ type: 'ready', tunnelGeneration: TUNNEL_GENERATION })
|
||||
}
|
||||
try {
|
||||
await closed.promise
|
||||
} finally {
|
||||
cleanup()
|
||||
console.info(`[auth-callback-tunnel] closed for port ${grant.port}`)
|
||||
}
|
||||
await serveCallbackTunnel(ctx, emit, grant, params.flowId)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import { readdir, readFile, readlink } from 'node:fs/promises'
|
||||
import { promisify } from 'node:util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const TCP_LISTEN = '0A'
|
||||
// Little-endian hex as /proc/net/tcp{,6} prints them: 127.0.0.0/8, 0.0.0.0, ::1, ::, ::ffff:127.x.
|
||||
const LOOPBACK_OR_ANY =
|
||||
/^(?:[0-9A-F]{6}7F|00000000|0{24}01000000|0{32}|0{16}FFFF0000[0-9A-F]{6}7F|0{16}FFFF000000000000)$/
|
||||
|
||||
export type ProcNetListener = { inode: string; uid: number }
|
||||
|
||||
/** Listening sockets on `port` reachable from loopback, parsed from /proc/net/tcp or tcp6 text. */
|
||||
export function parseProcNetListeners(text: string, port: number): ProcNetListener[] {
|
||||
const wantedPort = port.toString(16).toUpperCase().padStart(4, '0')
|
||||
const listeners: ProcNetListener[] = []
|
||||
for (const line of text.split('\n').slice(1)) {
|
||||
const fields = line.trim().split(/\s+/)
|
||||
if (fields.length < 10) {
|
||||
continue
|
||||
}
|
||||
const [address, localPort] = (fields[1] ?? '').split(':')
|
||||
if (
|
||||
fields[3] === TCP_LISTEN &&
|
||||
localPort?.toUpperCase() === wantedPort &&
|
||||
LOOPBACK_OR_ANY.test((address ?? '').toUpperCase())
|
||||
) {
|
||||
listeners.push({ uid: Number(fields[7]), inode: fields[9] ?? '' })
|
||||
}
|
||||
}
|
||||
return listeners
|
||||
}
|
||||
|
||||
async function linuxListenerPids(port: number): Promise<number[]> {
|
||||
const uid = process.getuid?.()
|
||||
const inodes = new Set<string>()
|
||||
for (const table of ['/proc/net/tcp', '/proc/net/tcp6']) {
|
||||
const text = await readFile(table, 'utf8').catch(() => '')
|
||||
for (const listener of parseProcNetListeners(text, port)) {
|
||||
// Only this host user's own processes; never another account's service.
|
||||
if (listener.uid === uid && listener.inode !== '0') {
|
||||
inodes.add(`socket:[${listener.inode}]`)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (inodes.size === 0) {
|
||||
return []
|
||||
}
|
||||
const pids: number[] = []
|
||||
for (const entry of await readdir('/proc').catch(() => [])) {
|
||||
if (!/^\d+$/.test(entry)) {
|
||||
continue
|
||||
}
|
||||
const fds = await readdir(`/proc/${entry}/fd`).catch(() => [])
|
||||
for (const fd of fds) {
|
||||
const target = await readlink(`/proc/${entry}/fd/${fd}`).catch(() => '')
|
||||
if (inodes.has(target)) {
|
||||
pids.push(Number(entry))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return pids
|
||||
}
|
||||
|
||||
async function darwinListenerPids(port: number): Promise<number[]> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'lsof',
|
||||
['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-a', '-u', String(process.getuid?.()), '-Fp'],
|
||||
{ timeout: 5_000 }
|
||||
)
|
||||
return stdout
|
||||
.split('\n')
|
||||
.filter((line) => line.startsWith('p'))
|
||||
.map((line) => Number(line.slice(1)))
|
||||
.filter(Number.isInteger)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** Pids of this user's processes, other than orcad itself, listening for loopback on `port`. */
|
||||
export async function loopbackListenerPids(port: number): Promise<number[]> {
|
||||
const pids =
|
||||
process.platform === 'linux'
|
||||
? await linuxListenerPids(port)
|
||||
: process.platform === 'darwin'
|
||||
? await darwinListenerPids(port)
|
||||
: []
|
||||
return pids.filter((pid) => pid !== process.pid)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { LoopbackCallbackTunnelParams } from '../../../../../shared/rpc-contract/accounts-params'
|
||||
import { defineStreamingMethod } from '../../core'
|
||||
import { requireCallbackTunnelClient, serveCallbackTunnel } from './auth-callback-tunnel'
|
||||
import { loopbackListenerPids } from './loopback-callback-listener'
|
||||
|
||||
// An OAuth redirect is one request plus maybe a favicon; close soon after the first one finishes.
|
||||
const ONE_SHOT_GRACE_MS = 3_000
|
||||
const LISTENER_POLL_MS = 1_000
|
||||
|
||||
export type LoopbackCallbackGrantDeps = {
|
||||
listenerPids?: (port: number) => Promise<number[]>
|
||||
pollMs?: number
|
||||
}
|
||||
|
||||
/** A grant to `port` that lasts only while a host process (not orcad) still listens there. */
|
||||
export async function grantLoopbackCallbackPort(
|
||||
port: number,
|
||||
deps: LoopbackCallbackGrantDeps = {}
|
||||
): Promise<{ port: number; ended: AbortSignal; streamClosed: () => void; release: () => void }> {
|
||||
const listenerPids = deps.listenerPids ?? loopbackListenerPids
|
||||
if ((await listenerPids(port)).length === 0) {
|
||||
throw new Error('loopback_callback_not_listening')
|
||||
}
|
||||
const ended = new AbortController()
|
||||
let checking = false
|
||||
const poll = setInterval(() => {
|
||||
if (checking) {
|
||||
return
|
||||
}
|
||||
checking = true
|
||||
void listenerPids(port)
|
||||
.then((pids) => {
|
||||
if (pids.length === 0) {
|
||||
ended.abort()
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
checking = false
|
||||
})
|
||||
}, deps.pollMs ?? LISTENER_POLL_MS)
|
||||
poll.unref?.()
|
||||
let graceTimer: ReturnType<typeof setTimeout> | null = null
|
||||
ended.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
clearInterval(poll)
|
||||
if (graceTimer) {
|
||||
clearTimeout(graceTimer)
|
||||
}
|
||||
},
|
||||
{ once: true }
|
||||
)
|
||||
return {
|
||||
port,
|
||||
ended: ended.signal,
|
||||
streamClosed: () => {
|
||||
graceTimer ??= setTimeout(() => ended.abort(), ONE_SHOT_GRACE_MS)
|
||||
},
|
||||
release: () => ended.abort()
|
||||
}
|
||||
}
|
||||
|
||||
/** Carries a desktop browser's OAuth redirect to a callback an agent on this host is listening for
|
||||
* (an MCP server sign-in, say). Same channel, caps and TTL as account sign-in; the port must have a
|
||||
* live non-orcad listener owned by this host user, and the tunnel closes once the callback is served. */
|
||||
export const loopbackCallbackTunnelMethod = defineStreamingMethod({
|
||||
name: 'network.loopbackCallbackTunnel',
|
||||
permission: 'accounts-admin',
|
||||
params: LoopbackCallbackTunnelParams,
|
||||
handler: async (params, ctx, emit) => {
|
||||
requireCallbackTunnelClient(ctx)
|
||||
const grant = await grantLoopbackCallbackPort(params.port)
|
||||
try {
|
||||
await serveCallbackTunnel(ctx, emit, grant, `port:${params.port}`, grant.streamClosed)
|
||||
} finally {
|
||||
grant.release()
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -5,8 +5,11 @@ import type {
|
||||
} from '../../shared/runtime-port-forwards'
|
||||
import type {
|
||||
AuthCallbackForwardRequest,
|
||||
AuthCallbackForwardResult
|
||||
AuthCallbackForwardResult,
|
||||
LoopbackCallbackForwardRequest
|
||||
} from '../../shared/auth-callback-forward'
|
||||
import type { McpSyncStatus } from '../../shared/agent-mcp-sync/mcp-sync-contract'
|
||||
import type { CloudMcpSyncPreferences } from '../../shared/agent-mcp-sync/mcp-sync-preferences'
|
||||
import type {
|
||||
CrewSubscriptionAttemptArgs,
|
||||
CrewSubscriptionAttemptCallbacks,
|
||||
@@ -116,6 +119,18 @@ export type RuntimeApi = {
|
||||
closePortForward?: (request: { id: string }) => Promise<RuntimePortForward | null>
|
||||
wakePortForwardHost?: (request: { environmentId: string }) => Promise<boolean>
|
||||
onPortForwardsChanged?: (callback: (forwards: RuntimePortForward[]) => void) => () => void
|
||||
// An agent's own OAuth callback on the host (e.g. an MCP server sign-in); desktop only.
|
||||
openLoopbackCallbackForward?: (
|
||||
request: LoopbackCallbackForwardRequest
|
||||
) => Promise<AuthCallbackForwardResult>
|
||||
// Orca Cloud MCP sync; absent in the web client, which has no local agent configs.
|
||||
getMcpSyncStatus?: (environmentId: string) => Promise<McpSyncStatus | null>
|
||||
syncMcpServersNow?: (environmentId: string) => Promise<McpSyncStatus | null>
|
||||
getMcpSyncPreferences?: () => Promise<CloudMcpSyncPreferences | null>
|
||||
setMcpSyncPreferences?: (
|
||||
preferences: Partial<CloudMcpSyncPreferences>
|
||||
) => Promise<CloudMcpSyncPreferences | null>
|
||||
onMcpSyncChanged?: (callback: (status: McpSyncStatus) => void) => () => void
|
||||
getStatusSnapshots: () => Promise<RuntimeHostStatusSnapshot[]>
|
||||
onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void) => () => void
|
||||
// Absent in the web client, whose catalog lives in the browser rather than a CLI-editable file.
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
RuntimePortForwardOpenResult
|
||||
} from '../../shared/runtime-port-forwards'
|
||||
import { RUNTIME_PORT_FORWARDS_CHANGED_CHANNEL } from '../../shared/runtime-port-forward-channels'
|
||||
import { CLOUD_MCP_SYNC_CHANGED_CHANNEL } from '../../shared/agent-mcp-sync/mcp-sync-preferences'
|
||||
import {
|
||||
RUNTIME_HOST_STATUS_CHANNEL,
|
||||
type RuntimeHostStatusSnapshot
|
||||
@@ -32,8 +33,11 @@ import {
|
||||
import type { PreloadApi } from '../api-types'
|
||||
import type {
|
||||
AuthCallbackForwardRequest,
|
||||
AuthCallbackForwardResult
|
||||
AuthCallbackForwardResult,
|
||||
LoopbackCallbackForwardRequest
|
||||
} from '../../shared/auth-callback-forward'
|
||||
import type { McpSyncStatus } from '../../shared/agent-mcp-sync/mcp-sync-contract'
|
||||
import type { CloudMcpSyncPreferences } from '../../shared/agent-mcp-sync/mcp-sync-preferences'
|
||||
import { managedOrcadApi } from './managed-orcad-api'
|
||||
import { getWslHostsApi } from './wsl-hosts-api'
|
||||
|
||||
@@ -63,6 +67,26 @@ export const runtimeEnvironmentsApi = {
|
||||
ipcRenderer.on(RUNTIME_PORT_FORWARDS_CHANGED_CHANNEL, listener)
|
||||
return () => ipcRenderer.removeListener(RUNTIME_PORT_FORWARDS_CHANGED_CHANNEL, listener)
|
||||
},
|
||||
openLoopbackCallbackForward: (
|
||||
request: LoopbackCallbackForwardRequest
|
||||
): Promise<AuthCallbackForwardResult> =>
|
||||
ipcRenderer.invoke('runtimeEnvironments:openLoopbackCallbackForward', request),
|
||||
getMcpSyncStatus: (environmentId: string): Promise<McpSyncStatus | null> =>
|
||||
ipcRenderer.invoke('cloudMcpSync:getStatus', environmentId),
|
||||
syncMcpServersNow: (environmentId: string): Promise<McpSyncStatus | null> =>
|
||||
ipcRenderer.invoke('cloudMcpSync:syncNow', environmentId),
|
||||
getMcpSyncPreferences: (): Promise<CloudMcpSyncPreferences | null> =>
|
||||
ipcRenderer.invoke('cloudMcpSync:getPreferences'),
|
||||
setMcpSyncPreferences: (
|
||||
preferences: Partial<CloudMcpSyncPreferences>
|
||||
): Promise<CloudMcpSyncPreferences | null> =>
|
||||
ipcRenderer.invoke('cloudMcpSync:setPreferences', preferences),
|
||||
onMcpSyncChanged: (callback: (status: McpSyncStatus) => void): (() => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, status: McpSyncStatus): void =>
|
||||
callback(status)
|
||||
ipcRenderer.on(CLOUD_MCP_SYNC_CHANGED_CHANNEL, listener)
|
||||
return () => ipcRenderer.removeListener(CLOUD_MCP_SYNC_CHANGED_CHANNEL, listener)
|
||||
},
|
||||
getStatusSnapshots: (): Promise<RuntimeHostStatusSnapshot[]> =>
|
||||
ipcRenderer.invoke('runtimeEnvironments:getStatusSnapshots'),
|
||||
onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void): (() => void) => {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { translate } from '@/i18n/i18n'
|
||||
import { isFloatingWorkspaceId } from '../../../../../shared/floating-workspace-worktree'
|
||||
import type { GlobalSettings } from '../../../../../shared/global-settings-types'
|
||||
import { toast } from 'sonner'
|
||||
import { relayRemoteOAuthCallback } from './remote-oauth-callback-relay'
|
||||
import type { ExecutionHostId } from '../../../../../shared/execution-host'
|
||||
import { reselectWorkspaceKeepingHost } from '../../workspace/ownership/active-workspace-host'
|
||||
import {
|
||||
@@ -292,7 +293,7 @@ function executeHttpLink(
|
||||
|
||||
const localhostRoute = state ? localhostLabelRouteForHttpLink(url, state, sourceOwner) : null
|
||||
if (!localhostRoute) {
|
||||
void openSystemHttpLink(url)
|
||||
void relayRemoteOAuthCallback(url, sourceOwner).finally(() => openSystemHttpLink(url))
|
||||
return
|
||||
}
|
||||
void openLabeledLocalhostLink(url, localhostRoute, (labeledUrl) => {
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { loopbackOAuthRedirectPort } from '../../../../../shared/loopback-oauth-redirect'
|
||||
import type { HttpLinkSourceOwner } from './http-link-routing'
|
||||
|
||||
/** Before a host's OAuth page opens in this computer's browser, listen on its loopback redirect port
|
||||
* and carry the callback to the host, where the agent (an MCP sign-in, say) is waiting for it. */
|
||||
export async function relayRemoteOAuthCallback(
|
||||
url: string,
|
||||
sourceOwner: HttpLinkSourceOwner | undefined
|
||||
): Promise<void> {
|
||||
if (sourceOwner?.kind !== 'runtime') {
|
||||
return
|
||||
}
|
||||
const port = loopbackOAuthRedirectPort(url)
|
||||
const open = window.api.runtimeEnvironments.openLoopbackCallbackForward
|
||||
if (port === null || !open) {
|
||||
return
|
||||
}
|
||||
const result = await open({ environmentId: sourceOwner.runtimeEnvironmentId, port }).catch(
|
||||
() => null
|
||||
)
|
||||
if (!result?.ok) {
|
||||
toast.warning(
|
||||
translate(
|
||||
'auto.lib.browser.navigation.remoteOAuthCallbackRelay.failed',
|
||||
'Orca could not pass this sign-in back to the remote host, so the browser may show a connection error when it finishes.'
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export const CLOUD_MCP_SYNC_CHANGED_CHANNEL = 'cloudMcpSync:changed'
|
||||
|
||||
export type CloudMcpSyncPreferences = {
|
||||
/** Sync on every connect to an Orca Cloud workspace. */
|
||||
autoSync: boolean
|
||||
/** `agent:name` keys the user turned off. */
|
||||
excluded: string[]
|
||||
}
|
||||
@@ -5,6 +5,12 @@ export type AuthCallbackForwardRequest = {
|
||||
port: number
|
||||
}
|
||||
|
||||
/** An OAuth redirect to `localhost:<port>` that an agent on the host (not Orca's own sign-in) is waiting for. */
|
||||
export type LoopbackCallbackForwardRequest = {
|
||||
environmentId: string
|
||||
port: number
|
||||
}
|
||||
|
||||
export type AuthCallbackForwardResult =
|
||||
| { ok: true }
|
||||
| { ok: false; code: 'port_busy' | 'listen_failed' | 'tunnel_failed'; message: string }
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { loopbackOAuthRedirectPort } from './loopback-oauth-redirect'
|
||||
|
||||
const authorize = (redirect: string, extra = '&client_id=abc&response_type=code'): string =>
|
||||
`https://mcp.example.com/authorize?redirect_uri=${encodeURIComponent(redirect)}${extra}`
|
||||
|
||||
describe('loopbackOAuthRedirectPort', () => {
|
||||
it('returns the port of a loopback http redirect', () => {
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://localhost:53682/callback'))).toBe(53682)
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://127.0.0.1:41000/cb'))).toBe(41000)
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://[::1]:41001/cb'))).toBe(41001)
|
||||
})
|
||||
|
||||
it('ignores non-loopback, https, privileged or portless redirects and non-OAuth links', () => {
|
||||
expect(loopbackOAuthRedirectPort(authorize('https://localhost:53682/cb'))).toBeNull()
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://evil.example:53682/cb'))).toBeNull()
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://localhost:80/cb'))).toBeNull()
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://localhost/cb'))).toBeNull()
|
||||
expect(loopbackOAuthRedirectPort(authorize('http://localhost:53682/cb', ''))).toBeNull()
|
||||
expect(loopbackOAuthRedirectPort('http://localhost:3000/?redirect_uri=x')).toBeNull()
|
||||
expect(loopbackOAuthRedirectPort('not a url')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
|
||||
|
||||
/** The port of an OAuth authorize URL's loopback `redirect_uri` (RFC 8252 native-app flow), else null.
|
||||
* Only http loopback redirects with an explicit unprivileged port qualify. */
|
||||
export function loopbackOAuthRedirectPort(url: string): number | null {
|
||||
let authorize: URL
|
||||
try {
|
||||
authorize = new URL(url)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const params = authorize.searchParams
|
||||
const redirect = params.get('redirect_uri')
|
||||
if (
|
||||
(authorize.protocol !== 'https:' && authorize.protocol !== 'http:') ||
|
||||
!redirect ||
|
||||
(!params.has('client_id') && params.get('response_type') !== 'code')
|
||||
) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const target = new URL(redirect)
|
||||
const port = Number(target.port)
|
||||
return target.protocol === 'http:' &&
|
||||
LOOPBACK.has(target.hostname.toLowerCase()) &&
|
||||
Number.isInteger(port) &&
|
||||
port >= 1024 &&
|
||||
port <= 65_535
|
||||
? port
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,11 @@ export const HostAgentSignOutParams = z.object({ agent: z.enum(['claude', 'codex
|
||||
|
||||
export const AuthCallbackTunnelParams = z.object({ flowId: z.string().min(1).max(64) })
|
||||
|
||||
/** A loopback port an agent on the host listens on for an OAuth redirect (never privileged ports). */
|
||||
export const LoopbackCallbackTunnelParams = z.object({
|
||||
port: z.number().int().min(1024).max(65_535)
|
||||
})
|
||||
|
||||
export const HostAccountSignInWaitParams = z.object({
|
||||
flowId: z.string().min(1).max(64),
|
||||
afterRevision: z.number().int().nonnegative().default(0)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// run `pnpm run generate:rpc-params-catalog`.
|
||||
import type { z } from 'zod'
|
||||
import { HostAccountLaunchEnvParams } from '../agent-launch/startup/host-account-launch-env'
|
||||
import { AgentMcpSyncParams } from '../agent-mcp-sync/mcp-sync-contract'
|
||||
import { AgentSkillShareRequestSchema } from '../agent-skill-sharing-contract'
|
||||
import {
|
||||
AiVaultSearchRequestSchema,
|
||||
@@ -67,6 +68,7 @@ import {
|
||||
HostAgentSignInStatusParams,
|
||||
HostAgentSignOutParams,
|
||||
ListAccountsParams,
|
||||
LoopbackCallbackTunnelParams,
|
||||
RemoveAccountParams,
|
||||
RemoveDataAccountParams,
|
||||
SelectAccountParams,
|
||||
@@ -824,6 +826,7 @@ export const RPC_PARAMS_BY_METHOD = {
|
||||
'agent.launchReplay': AgentLaunchReplay,
|
||||
'agentActivity.clear': AgentActivityClearParams,
|
||||
'agentActivity.setRead': AgentActivitySetReadParams,
|
||||
'agentConfig.syncMcpServers': AgentMcpSyncParams,
|
||||
'agentHooks.prepareCodexForWslPane': PrepareCodexForWslPaneParams,
|
||||
'agentSession.accountUsage': OptionsParams,
|
||||
'agentSession.acknowledgeAttention': AcknowledgeAttentionParams,
|
||||
@@ -1333,6 +1336,7 @@ export const RPC_PARAMS_BY_METHOD = {
|
||||
'nativeChat.unsubscribe': NativeChatUnsubscribe,
|
||||
'network.authCallbackTunnel': AuthCallbackTunnelParams,
|
||||
'network.browserTunnel': BrowserNetworkTunnelAttachParams,
|
||||
'network.loopbackCallbackTunnel': LoopbackCallbackTunnelParams,
|
||||
'notifications.getMissedSince': NotificationGetMissedSinceParams,
|
||||
'notifications.registerPush': NotificationRegisterPushParams,
|
||||
'notifications.reportDesktopPresence': NotificationReportDesktopPresenceParams,
|
||||
|
||||
Reference in New Issue
Block a user