From 30fc4859e2a05d5ac35d446166e5c7eb9c0853ef Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Mon, 29 Jun 2026 19:06:59 -0700 Subject: [PATCH] fix: reject mobile-scope web pairing and surface forbidden runtime errors (#6581) Fixes #5508. Rejects mobile-scope phone-QR pairing in the full web client, keeps runtime browser access links on the instant startup path via advisory pairing scope metadata, and surfaces forbidden runtime scope errors instead of rendering empty workspaces or retry-looping setup checks. Security note: pairing offer scope is UI metadata only. Runtime RPC authorization remains based on the server-side device token registry and mobile allowlist. --- src/main/runtime/device-registry.ts | 3 +- src/main/runtime/runtime-rpc.test.ts | 42 +++++++++++++++ src/main/runtime/runtime-rpc.ts | 29 +++++++++- .../sidebar/SetupScriptPromptCard.tsx | 8 +++ src/renderer/src/i18n/locales/en.json | 7 ++- src/renderer/src/i18n/locales/es.json | 7 ++- src/renderer/src/i18n/locales/ja.json | 7 ++- src/renderer/src/i18n/locales/ko.json | 7 ++- src/renderer/src/i18n/locales/zh.json | 7 ++- .../src/lib/setup-script-prompt.test.ts | 23 ++++++++ src/renderer/src/lib/setup-script-prompt.ts | 11 ++++ .../src/runtime/runtime-rpc-client.ts | 7 +++ .../src/store/slices/worktrees.test.ts | 34 ++++++++++++ src/renderer/src/store/slices/worktrees.ts | 33 ++++++++++++ src/renderer/src/web/WebConnect.tsx | 36 ++++++++++++- src/renderer/src/web/main.tsx | 33 ++++++++---- src/renderer/src/web/web-pairing.test.ts | 54 +++++++++++++++++-- src/renderer/src/web/web-pairing.ts | 32 ++++++++++- src/shared/pairing.test.ts | 5 ++ src/shared/pairing.ts | 6 ++- src/shared/runtime-types.ts | 7 +++ 21 files changed, 370 insertions(+), 28 deletions(-) diff --git a/src/main/runtime/device-registry.ts b/src/main/runtime/device-registry.ts index b55188072..287ac20a1 100644 --- a/src/main/runtime/device-registry.ts +++ b/src/main/runtime/device-registry.ts @@ -6,9 +6,10 @@ import { randomBytes, randomUUID } from 'crypto' import { existsSync, readFileSync } from 'fs' import { join } from 'path' import { hardenExistingSecureFile, writeSecureJsonFile } from '../../shared/secure-file' +import type { DeviceScope } from '../../shared/runtime-types' import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files' -export type DeviceScope = 'mobile' | 'runtime' +export type { DeviceScope } export type DeviceEntry = { deviceId: string diff --git a/src/main/runtime/runtime-rpc.test.ts b/src/main/runtime/runtime-rpc.test.ts index 2be7b1a90..a4b12bd2f 100644 --- a/src/main/runtime/runtime-rpc.test.ts +++ b/src/main/runtime/runtime-rpc.test.ts @@ -351,6 +351,7 @@ describe('OrcaRuntimeRpcServer', () => { expect(parsed?.endpoint).toBe(offer.endpoint) expect(parsed?.deviceToken).toBeTruthy() expect(parsed?.publicKeyB64).toBeTruthy() + expect(parsed?.scope).toBe('runtime') expect(server.getDeviceRegistry()?.getDevice(offer.deviceId)?.scope).toBe('runtime') } @@ -2049,6 +2050,46 @@ describe('OrcaRuntimeRpcServer', () => { await server.stop() }) + it('stamps the authenticated device scope onto status.get for WebSocket clients', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) + const runtime = new OrcaRuntimeService() + const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false }) + server['deviceRegistry'] = new DeviceRegistry(userDataPath) + const mobile = server['deviceRegistry']!.addDevice('phone', 'mobile') + const runtimeDevice = server['deviceRegistry']!.addDevice('browser', 'runtime') + + const sendStatus = async (token: string): Promise> => { + const replies: Record[] = [] + await server['handleWebSocketMessage']( + JSON.stringify({ id: 'req_status', method: 'status.get', deviceToken: token }), + (response) => replies.push(JSON.parse(response) as Record), + () => {} + ) + return replies[0]! + } + + const mobileReply = await sendStatus(mobile.token) + expect(mobileReply).toMatchObject({ id: 'req_status', ok: true }) + // Why: the mobile-scope web client reads this to refuse the full app. + expect((mobileReply.result as { deviceScope?: string }).deviceScope).toBe('mobile') + + const runtimeReply = await sendStatus(runtimeDevice.token) + expect((runtimeReply.result as { deviceScope?: string }).deviceScope).toBe('runtime') + + // Other methods stay unmodified — only status.get carries the scope. + const replies: Record[] = [] + await server['handleWebSocketMessage']( + JSON.stringify({ id: 'req_forbidden', method: 'files.delete', deviceToken: mobile.token }), + (response) => replies.push(JSON.parse(response) as Record), + () => {} + ) + expect(replies[0]).toMatchObject({ + id: 'req_forbidden', + ok: false, + error: { code: 'forbidden' } + }) + }) + it('rejects requests with the wrong auth token', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService() @@ -2608,6 +2649,7 @@ describe('OrcaRuntimeRpcServer', () => { if (!phoneOffer.available) { throw new Error('WebSocket pairing unavailable') } + expect(parsePairingCode(phoneOffer.pairingUrl)?.scope).toBe('mobile') const phone = await authenticateMobileWsSession(phoneOffer.pairingUrl) const phoneResponses = createEncryptedWsResponseReader(phone) const metadata = readRuntimeMetadata(userDataPath) diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 154f09261..d7824dfda 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -365,6 +365,23 @@ function isLongPollRequest(request: RpcRequest): boolean { return false } +// Why: stamp the authenticated connection's scope onto the status.get success +// envelope. status.get has no per-connection context inside the dispatcher, so +// the scope is added here at the transport boundary where the device is known. +// Failures fall back to the untouched reply rather than dropping the response. +function injectDeviceScope(response: string, scope: DeviceScope): string { + try { + const parsed = JSON.parse(response) as RpcResponse + if (parsed.ok !== true || typeof parsed.result !== 'object' || parsed.result === null) { + return response + } + ;(parsed.result as Record).deviceScope = scope + return JSON.stringify(parsed) + } catch { + return response + } +} + export class OrcaRuntimeRpcServer { private readonly runtime: OrcaRuntimeService private readonly dispatcher: RpcDispatcher @@ -495,7 +512,8 @@ export class OrcaRuntimeRpcServer { v: PAIRING_OFFER_VERSION, endpoint, deviceToken: device.token, - publicKeyB64 + publicKeyB64, + scope }) return { available: true, @@ -969,9 +987,16 @@ export class OrcaRuntimeRpcServer { this.activeLongPolls += 1 } + // Why: older/saved WebSocket pairings may not carry scope metadata, so + // stamp the authenticated scope onto the one method that probes the runtime. + const replyForRequest = + request.method === 'status.get' + ? (response: string): void => reply(injectDeviceScope(response, device.scope)) + : reply + const connectionId = ws ? this.wsConnectionIds.get(ws) : undefined try { - await this.dispatcher.dispatchStreaming(request, reply, { + await this.dispatcher.dispatchStreaming(request, replyForRequest, { connectionId, clientId: token, // Why: gates the mobile-only payload diet (native-chat char clipping) so diff --git a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx index cfec68165..3631fd81c 100644 --- a/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx +++ b/src/renderer/src/components/sidebar/SetupScriptPromptCard.tsx @@ -357,6 +357,14 @@ function SetupScriptPromptCard(): React.JSX.Element | null { return null } + // Why: a forbidden (mobile-scope) inspection is permanent, so suppress the + // retry-able card entirely — the global scope-mismatch banner explains it and + // a retry would just re-fire repo.hooksCheck on every repo focus. + if (renderedPromptState.status === 'forbidden') { + lastVisiblePromptRef.current = null + return null + } + if ( renderedPromptState.status === 'ok' && !renderedPromptState.hasEffectiveSetup && diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index d4ba5dab0..63f33efd0 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -133,7 +133,8 @@ "7a566540de": "Pairing URL or code", "cb4d287238": "Server name", "3affe7de3a": "Paste a pairing URL from an Orca server that this browser can reach.", - "e3bcd082ac": "Connect to Orca" + "e3bcd082ac": "Connect to Orca", + "mobileScopeRejected": "This QR code grants limited (mobile) access. To use the full web app, open the browser access link from Settings → Runtime Environments → Share this Orca server → New Link." }, "web": { "preload": { @@ -228,7 +229,9 @@ "2e17f825d4": "Worktree deleted, branch kept", "78e08cd877": "Git could not safely delete branch \"{{value0}}\", so Orca kept it to avoid losing local commits.", "3b57982bf6": "Git could not safely delete branch \"{{value0}}\" after deleting workspace \"{{value1}}\", so Orca kept it to avoid losing local commits.", - "81f13f48d2": "Git could not safely delete branch \"{{value0}}\" after deleting worktree \"{{value1}}\", so Orca kept it to avoid losing local commits." + "81f13f48d2": "Git could not safely delete branch \"{{value0}}\" after deleting worktree \"{{value1}}\", so Orca kept it to avoid losing local commits.", + "runtimeScopeForbiddenTitle": "This connection has limited (mobile) access", + "runtimeScopeForbiddenDescription": "Workspaces are unavailable on a mobile-scope pairing. Reconnect using the browser access link from Settings → Runtime Environments → Share this Orca server." }, "repos": { "2975400634": "Update Orca server to open non-Git folders on this runtime.", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 627437313..44d9fc80f 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -133,7 +133,8 @@ "7a566540de": "URL o código de emparejamiento", "cb4d287238": "Nombre del servidor", "3affe7de3a": "Pegue una URL de emparejamiento de un servidor Orca al que este navegador pueda acceder.", - "e3bcd082ac": "Conéctate a Orca" + "e3bcd082ac": "Conéctate a Orca", + "mobileScopeRejected": "Este código QR concede acceso limitado (móvil). Para usar la app web completa, abre el enlace del navegador desde Ajustes → Servidores remotos de Orca → Comparte este servidor Orca → Nuevo enlace." }, "web": { "preload": { @@ -228,7 +229,9 @@ "2e17f825d4": "Árbol de trabajo eliminado, rama conservada", "78e08cd877": "Git no pudo eliminar de forma segura la rama \"{{value0}}\", por lo que Orca la conservó para evitar perder commits locales.", "3b57982bf6": "Git no pudo eliminar de forma segura la rama \"{{value0}}\" después de eliminar el espacio de trabajo \"{{value1}}\", por lo que Orca la conservó para evitar perder commits locales.", - "81f13f48d2": "Git no pudo eliminar de forma segura la rama \"{{value0}}\" después de eliminar el árbol de trabajo \"{{value1}}\", por lo que Orca la conservó para evitar perder commits locales." + "81f13f48d2": "Git no pudo eliminar de forma segura la rama \"{{value0}}\" después de eliminar el árbol de trabajo \"{{value1}}\", por lo que Orca la conservó para evitar perder commits locales.", + "runtimeScopeForbiddenTitle": "Esta conexión tiene acceso limitado (móvil)", + "runtimeScopeForbiddenDescription": "Los espacios de trabajo no están disponibles con un emparejamiento de acceso móvil. Vuelve a conectarte con el enlace del navegador desde Ajustes → Servidores remotos de Orca → Comparte este servidor Orca." }, "repos": { "2975400634": "Update Orca server to open non-Git folders on this runtime.", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index b186718dd..c4bef5669 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -133,7 +133,8 @@ "7a566540de": "ペアリング URL またはコード", "cb4d287238": "サーバー名", "3affe7de3a": "このブラウザが到達できる Orca サーバーからペアリング URL を貼り付けます。", - "e3bcd082ac": "Orca に接続" + "e3bcd082ac": "Orca に接続", + "mobileScopeRejected": "この QR コードは制限付き(モバイル)アクセスを許可します。完全な Web アプリを使うには、設定 → リモート Orca サーバー → この Orca サーバーを共有する → 新規リンク からブラウザー用アクセスリンクを開いてください。" }, "web": { "preload": { @@ -228,7 +229,9 @@ "2e17f825d4": "ワークツリーを削除しました、ブランチは保持されました", "78e08cd877": "Git はブランチ\"{{value0}}\"を安全に削除できなかったため、Orca はローカルコミットを失わないように保持しました。", "3b57982bf6": "ワークスペース\"{{value1}}\"を削除した後、Git はブランチ\"{{value0}}\"を安全に削除できなかったため、Orca はローカルコミットを失わないように保持しました。", - "81f13f48d2": "ワークツリー\"{{value1}}\"を削除した後、Git はブランチ\"{{value0}}\"を安全に削除できなかったため、Orca はローカルコミットを失わないように保持しました。" + "81f13f48d2": "ワークツリー\"{{value1}}\"を削除した後、Git はブランチ\"{{value0}}\"を安全に削除できなかったため、Orca はローカルコミットを失わないように保持しました。", + "runtimeScopeForbiddenTitle": "この接続は制限付き(モバイル)アクセスです", + "runtimeScopeForbiddenDescription": "モバイル範囲のペアリングではワークスペースを使用できません。設定 → リモート Orca サーバー → この Orca サーバーを共有する からブラウザー用リンクで再接続してください。" }, "repos": { "2975400634": "Update Orca server to open non-Git folders on this runtime.", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 33abe64b7..c054decca 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -133,7 +133,8 @@ "7a566540de": "페어링 URL 또는 코드", "cb4d287238": "서버 이름", "3affe7de3a": "이 브라우저가 연결할 수 있는 Orca 서버의 페어링 URL을 붙여넣습니다.", - "e3bcd082ac": "Orca에 연결" + "e3bcd082ac": "Orca에 연결", + "mobileScopeRejected": "이 QR 코드는 제한된(모바일) 액세스 권한만 제공합니다. 전체 웹 앱을 사용하려면 설정 → 원격 Orca 서버 → 이 Orca 서버 공유 → 새 링크에서 브라우저 액세스 링크를 여세요." }, "web": { "preload": { @@ -228,7 +229,9 @@ "2e17f825d4": "워크트리가 삭제되었고 브랜치는 유지되었습니다", "78e08cd877": "Git이 \"{{value0}}\" 브랜치를 안전하게 삭제할 수 없어 Orca가 로컬 커밋 손실을 방지하기 위해 유지했습니다.", "3b57982bf6": "\"{{value1}}\" 워크스페이스를 삭제한 후 Git이 \"{{value0}}\" 브랜치를 안전하게 삭제할 수 없어 Orca가 로컬 커밋 손실을 방지하기 위해 유지했습니다.", - "81f13f48d2": "\"{{value1}}\" 워크트리를 삭제한 후 Git이 \"{{value0}}\" 브랜치를 안전하게 삭제할 수 없어 Orca가 로컬 커밋 손실을 방지하기 위해 유지했습니다." + "81f13f48d2": "\"{{value1}}\" 워크트리를 삭제한 후 Git이 \"{{value0}}\" 브랜치를 안전하게 삭제할 수 없어 Orca가 로컬 커밋 손실을 방지하기 위해 유지했습니다.", + "runtimeScopeForbiddenTitle": "이 연결은 제한된(모바일) 액세스입니다", + "runtimeScopeForbiddenDescription": "모바일 범위 페어링에서는 워크스페이스를 사용할 수 없습니다. 설정 → 원격 Orca 서버 → 이 Orca 서버 공유에서 브라우저 액세스 링크로 다시 연결하세요." }, "repos": { "2975400634": "Update Orca server to open non-Git folders on this runtime.", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index a7588b277..13d169c17 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -133,7 +133,8 @@ "7a566540de": "配对 URL 或代码", "cb4d287238": "服务器名称", "3affe7de3a": "粘贴来自该浏览器可以访问的 Orca 服务器的配对 URL。", - "e3bcd082ac": "连接到 Orca" + "e3bcd082ac": "连接到 Orca", + "mobileScopeRejected": "此二维码仅授予受限(移动端)访问权限。若要使用完整 Web 应用,请从设置 → 远程 Orca 服务器 → 分享此 Orca 服务器 → 新链接打开浏览器访问链接。" }, "web": { "preload": { @@ -228,7 +229,9 @@ "2e17f825d4": "工作树已删除,分支已保留", "78e08cd877": "Git 无法安全删除分支\"{{value0}}\",因此 Orca 将其保留以避免丢失本地提交。", "3b57982bf6": "删除工作区\"{{value1}}\"后,Git 无法安全删除分支\"{{value0}}\",因此 Orca 将其保留以避免丢失本地提交。", - "81f13f48d2": "删除工作树\"{{value1}}\"后,Git 无法安全删除分支\"{{value0}}\",因此 Orca 将其保留以避免丢失本地提交。" + "81f13f48d2": "删除工作树\"{{value1}}\"后,Git 无法安全删除分支\"{{value0}}\",因此 Orca 将其保留以避免丢失本地提交。", + "runtimeScopeForbiddenTitle": "此连接具有受限(移动端)访问权限", + "runtimeScopeForbiddenDescription": "移动端范围的配对无法使用工作区。请通过设置 → 远程 Orca 服务器 → 分享此 Orca 服务器中的浏览器访问链接重新连接。" }, "repos": { "2975400634": "Update Orca server to open non-Git folders on this runtime.", diff --git a/src/renderer/src/lib/setup-script-prompt.test.ts b/src/renderer/src/lib/setup-script-prompt.test.ts index dd58a769a..e59285632 100644 --- a/src/renderer/src/lib/setup-script-prompt.test.ts +++ b/src/renderer/src/lib/setup-script-prompt.test.ts @@ -10,6 +10,7 @@ import { inspectSetupScriptPromptState, isSetupScriptPromptDismissed } from './setup-script-prompt' +import { RuntimeRpcCallError } from '@/runtime/runtime-rpc-client' function makeRepo(overrides: Partial = {}): Repo { return { @@ -87,6 +88,28 @@ describe('setup script prompt inspection', () => { warn.mockRestore() }) + it('returns forbidden status (not retry-able error) when the runtime scope denies the check', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await expect( + inspectSetupScriptPromptState({ + repo: makeRepo(), + checkHooks: vi.fn().mockRejectedValue( + new RuntimeRpcCallError({ + id: 'req', + ok: false, + error: { code: 'forbidden', message: "Method 'repo.hooksCheck' is not available" } + }) + ), + inspectImports: vi.fn() + }) + ).resolves.toEqual({ status: 'forbidden', repoId: 'repo-1' }) + + // Why: a permanent scope failure must not log as a transient inspection warning. + expect(warn).not.toHaveBeenCalled() + warn.mockRestore() + }) + it('returns error status when hook inspection reports an SSH read failure', async () => { await expect( inspectSetupScriptPromptState({ diff --git a/src/renderer/src/lib/setup-script-prompt.ts b/src/renderer/src/lib/setup-script-prompt.ts index fda95b687..b3cffcb5e 100644 --- a/src/renderer/src/lib/setup-script-prompt.ts +++ b/src/renderer/src/lib/setup-script-prompt.ts @@ -3,6 +3,7 @@ import { resolveHookCommandSourcePolicy } from '../../../shared/hook-command-sou import type { SetupScriptImportCandidate } from '../../../shared/setup-script-imports' import type { Repo, RepoHookSettings } from '../../../shared/types' import type { HookCheckResult } from '@/runtime/runtime-hooks-client' +import { isRuntimeScopeForbiddenError } from '@/runtime/runtime-rpc-client' const SETUP_SCRIPT_PROMPT_DISMISSAL_PREFIX = 'generation-v1:' @@ -18,6 +19,13 @@ export type SetupScriptPromptInspection = status: 'error' repoId: string } + // Why: a forbidden (mobile-scope) failure is permanent, not transient — the + // card must not offer a retry that re-fires repo.hooksCheck on every focus. + // The global scope-mismatch banner already explains the cause. + | { + status: 'forbidden' + repoId: string + } export async function inspectSetupScriptPromptState({ repo, @@ -53,6 +61,9 @@ export async function inspectSetupScriptPromptState({ candidate: candidates[0] ?? null } } catch (error) { + if (isRuntimeScopeForbiddenError(error)) { + return { status: 'forbidden', repoId: repo.id } + } console.warn('[setup-script-prompt] Failed to inspect setup scripts:', error) return { status: 'error', repoId: repo.id } } diff --git a/src/renderer/src/runtime/runtime-rpc-client.ts b/src/renderer/src/runtime/runtime-rpc-client.ts index 74183cce2..9d9c90295 100644 --- a/src/renderer/src/runtime/runtime-rpc-client.ts +++ b/src/renderer/src/runtime/runtime-rpc-client.ts @@ -22,6 +22,13 @@ export class RuntimeRpcCallError extends Error { } } +// Why: mobile-scope device tokens are denied non-allowlisted runtime methods +// with code 'forbidden'. Callers use this to surface one scope-mismatch banner +// instead of silently swallowing the failure into empty/retry-looping UI. +export function isRuntimeScopeForbiddenError(error: unknown): boolean { + return error instanceof RuntimeRpcCallError && error.code === 'forbidden' +} + export function getActiveRuntimeTarget( settings: Pick | null | undefined ): RuntimeClientTarget { diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 40ee2b907..a744f1515 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -1187,6 +1187,40 @@ describe('fetchWorktrees', () => { }) }) + it('surfaces one deduped scope-mismatch toast when a mobile pairing forbids worktree RPCs', async () => { + const store = createTestStore() + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + repos: [ + { id: 'repo1', path: '/r1', displayName: 'R1', badgeColor: '#000', addedAt: 0 }, + { id: 'repo2', path: '/r2', displayName: 'R2', badgeColor: '#000', addedAt: 0 } + ] + } as Partial) + // Why: a mobile-scope device token is denied non-allowlisted runtime RPCs. + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-1', + ok: false, + error: { + code: 'forbidden', + message: "Method 'worktree.detectedList' is not available to mobile clients" + }, + _meta: { runtimeId: 'runtime-remote' } + }) + + const repo1Result = await store.getState().fetchWorktrees('repo1') + const repo2Result = await store.getState().fetchWorktrees('repo2') + await store.getState().fetchDetectedWorktrees('repo1') + + expect(repo1Result).toBe(false) + expect(repo2Result).toBe(false) + expect(store.getState().worktreesByRepo.repo1).toBeUndefined() + // Why: per-repo failures must collapse to a single stable-id toast, not spam. + expect(toast.error).toHaveBeenCalledTimes(3) + for (const call of (toast.error as ReturnType).mock.calls) { + expect(call[1]).toMatchObject({ id: 'runtime-scope-forbidden' }) + } + }) + it('updates remote worktree records when only lineage changes', async () => { const store = createTestStore() const initial = makeWorktree({ diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 9bd7038ea..00fb6c964 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -30,6 +30,7 @@ import { tabHasLivePty } from '@/lib/tab-has-live-pty' import { callRuntimeRpc, getActiveRuntimeTarget, + isRuntimeScopeForbiddenError, RuntimeRpcCallError } from '../../runtime/runtime-rpc-client' import { toRuntimeWorktreeSelector } from '../../runtime/runtime-worktree-selector' @@ -525,6 +526,32 @@ function isRuntimeMethodNotFoundError(error: unknown): boolean { return error instanceof RuntimeRpcCallError && error.code === 'method_not_found' } +// Why: a mobile-scope web pairing is denied worktree/repo RPCs, which would +// otherwise be swallowed into empty workspaces on every repo. Surface one +// deduped, actionable toast (stable id) instead of spamming per-repo, steering +// the user to re-pair via the full-access browser link. +const RUNTIME_SCOPE_FORBIDDEN_TOAST_ID = 'runtime-scope-forbidden' + +function notifyRuntimeScopeForbiddenIfNeeded(error: unknown): boolean { + if (!isRuntimeScopeForbiddenError(error)) { + return false + } + toast.error( + translate( + 'auto.store.slices.worktrees.runtimeScopeForbiddenTitle', + 'This connection has limited (mobile) access' + ), + { + id: RUNTIME_SCOPE_FORBIDDEN_TOAST_ID, + description: translate( + 'auto.store.slices.worktrees.runtimeScopeForbiddenDescription', + 'Workspaces are unavailable on a mobile-scope pairing. Reconnect using the browser access link from Settings → Runtime Environments → Share this Orca server.' + ) + } + ) + return true +} + function applyDetectedWorktreeUpdates( detectedWorktreesByRepo: AppState['detectedWorktreesByRepo'], worktreeId: string, @@ -2005,6 +2032,9 @@ export const createWorktreeSlice: StateCreator }) return result } catch (err) { + if (notifyRuntimeScopeForbiddenIfNeeded(err)) { + return null + } console.error(`Failed to fetch detected worktrees for repo ${repoId}:`, err) return null } @@ -2131,6 +2161,9 @@ export const createWorktreeSlice: StateCreator await refreshRemoteWorktreeLineageBestEffort(settings, set) return detected.authoritative } catch (err) { + if (notifyRuntimeScopeForbiddenIfNeeded(err)) { + return false + } console.error(`Failed to fetch worktrees for repo ${repoId}:`, err) return false } diff --git a/src/renderer/src/web/WebConnect.tsx b/src/renderer/src/web/WebConnect.tsx index 46eb3f6bc..3de4a5dcb 100644 --- a/src/renderer/src/web/WebConnect.tsx +++ b/src/renderer/src/web/WebConnect.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { Cable, Loader2, Server, Trash2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' @@ -12,6 +12,7 @@ import { } from './web-runtime-environment' import { parseWebPairingInput } from './web-pairing' import { WebRuntimeClient } from './web-runtime-client' +import type { RuntimeStatus } from '../../../shared/runtime-types' import { translate } from '@/i18n/i18n' type WebConnectProps = { @@ -29,6 +30,7 @@ export default function WebConnect({ const [error, setError] = useState(null) const [connecting, setConnecting] = useState(false) const parsedOffer = useMemo(() => parseWebPairingInput(pairingCode), [pairingCode]) + const autoConnectAttempted = useRef(false) const connect = async (): Promise => { setError(null) @@ -36,6 +38,15 @@ export default function WebConnect({ setError('Enter a valid Orca pairing URL or pairing code.') return } + if (parsedOffer.scope === 'mobile') { + setError( + translate( + 'auto.web.WebConnect.mobileScopeRejected', + 'This QR code grants limited (mobile) access. To use the full web app, open the browser access link from Settings → Runtime Environments → Share this Orca server → New Link.' + ) + ) + return + } if (isMixedContentWebSocket(parsedOffer.endpoint)) { setError( 'This HTTPS page cannot connect to a plain ws:// Orca server. Open the web client over HTTP or pair with a wss:// endpoint.' @@ -50,6 +61,17 @@ export default function WebConnect({ if (!response.ok) { throw new Error(response.error.message) } + // Why: older pairing offers may not carry scope metadata. The server + // stamps it onto status.get so those links still fail before app entry. + if ((response.result as RuntimeStatus | null)?.deviceScope === 'mobile') { + setError( + translate( + 'auto.web.WebConnect.mobileScopeRejected', + 'This QR code grants limited (mobile) access. To use the full web app, open the browser access link from Settings → Runtime Environments → Share this Orca server → New Link.' + ) + ) + return + } saveStoredWebRuntimeEnvironment({ ...environment, runtimeId: response._meta.runtimeId, @@ -64,6 +86,18 @@ export default function WebConnect({ } } + // Why: a deep-linked offer that reaches this screen either has mobile scope + // or unknown legacy scope; run the same connect path to reject/probe it. + useEffect(() => { + if (autoConnectAttempted.current || !initialPairingInput || !parsedOffer) { + return + } + autoConnectAttempted.current = true + void connect() + // Why: run once for the deep-linked offer; connect() reads current refs/state. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [initialPairingInput, parsedOffer]) + const clear = (): void => { clearStoredWebRuntimeEnvironment() setPairingCode('') diff --git a/src/renderer/src/web/main.tsx b/src/renderer/src/web/main.tsx index da0cda067..185b95acf 100644 --- a/src/renderer/src/web/main.tsx +++ b/src/renderer/src/web/main.tsx @@ -8,7 +8,7 @@ import WebConnect from './WebConnect' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' import { clearPairingInputFromAddressBar, - parseWebPairingInput, + decideWebPairingStartup, readPairingInputFromLocation } from './web-pairing' import { @@ -24,22 +24,37 @@ const App = lazy(() => import('../App')) function WebRoot(): React.JSX.Element { const initialPairingInput = useMemo(() => readPairingInputFromLocation(window.location), []) - const [hasEnvironment, setHasEnvironment] = useState(() => { - const offer = initialPairingInput ? parseWebPairingInput(initialPairingInput) : null - if (offer) { - saveStoredWebRuntimeEnvironment( - createStoredWebRuntimeEnvironment({ name: 'Orca Server', offer }) - ) + // Why: current runtime links carry scope metadata. Runtime-scope offers keep + // the instant save path; mobile/legacy-unknown offers must be shown/probed. + const startupDecision = useMemo(() => { + const decision = decideWebPairingStartup({ + initialPairingInput, + hasStoredEnvironment: readStoredWebRuntimeEnvironment() !== null + }) + if ( + decision.kind === 'auto-save-runtime-offer' || + (decision.kind === 'show-connect' && decision.initialPairingInput !== null) + ) { clearPairingInputFromAddressBar() + } + return decision + }, [initialPairingInput]) + const [hasEnvironment, setHasEnvironment] = useState(() => { + if (startupDecision.kind === 'auto-save-runtime-offer') { + saveStoredWebRuntimeEnvironment( + createStoredWebRuntimeEnvironment({ name: 'Orca Server', offer: startupDecision.offer }) + ) return true } - return readStoredWebRuntimeEnvironment() !== null + return startupDecision.kind === 'use-stored-environment' }) if (!hasEnvironment) { return ( setHasEnvironment(true)} /> ) diff --git a/src/renderer/src/web/web-pairing.test.ts b/src/renderer/src/web/web-pairing.test.ts index 8283d5ba5..f692dcb86 100644 --- a/src/renderer/src/web/web-pairing.test.ts +++ b/src/renderer/src/web/web-pairing.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { parseWebPairingInput, type WebPairingOffer } from './web-pairing' +import { decideWebPairingStartup, parseWebPairingInput, type WebPairingOffer } from './web-pairing' describe('web pairing input', () => { const offer: WebPairingOffer = { @@ -9,8 +9,8 @@ describe('web pairing input', () => { publicKeyB64: 'public-key' } - function encodeOffer() { - return Buffer.from(JSON.stringify(offer), 'utf-8') + function encodeOffer(overrides: Record = {}) { + return Buffer.from(JSON.stringify({ ...offer, ...overrides }), 'utf-8') .toString('base64') .replace(/\+/g, '-') .replace(/\//g, '_') @@ -25,8 +25,56 @@ describe('web pairing input', () => { expect(parseWebPairingInput(`orca://pair#${encodeOffer()}`)).toEqual(offer) }) + it('preserves optional device scope metadata', () => { + expect(parseWebPairingInput(`orca://pair?code=${encodeOffer({ scope: 'mobile' })}`)).toEqual({ + ...offer, + scope: 'mobile' + }) + }) + + it('treats invalid device scope metadata as unknown', () => { + expect(parseWebPairingInput(`orca://pair?code=${encodeOffer({ scope: 'admin' })}`)).toEqual( + offer + ) + }) + it('rejects orca URLs outside the exact pairing route', () => { expect(parseWebPairingInput(`orca://pairing?code=${encodeOffer()}`)).toBeNull() expect(parseWebPairingInput(`orca://pair-extra?code=${encodeOffer()}`)).toBeNull() }) + + it('auto-saves scoped runtime offers during web startup', () => { + const input = `orca://pair?code=${encodeOffer({ scope: 'runtime' })}` + expect( + decideWebPairingStartup({ initialPairingInput: input, hasStoredEnvironment: false }) + ).toEqual({ + kind: 'auto-save-runtime-offer', + offer: { ...offer, scope: 'runtime' } + }) + }) + + it('shows the connect screen for mobile-scope and legacy unknown-scope offers', () => { + const mobileInput = `orca://pair?code=${encodeOffer({ scope: 'mobile' })}` + const legacyInput = `orca://pair?code=${encodeOffer()}` + + expect( + decideWebPairingStartup({ initialPairingInput: mobileInput, hasStoredEnvironment: true }) + ).toEqual({ kind: 'show-connect', initialPairingInput: mobileInput }) + expect( + decideWebPairingStartup({ initialPairingInput: legacyInput, hasStoredEnvironment: true }) + ).toEqual({ kind: 'show-connect', initialPairingInput: legacyInput }) + }) + + it('uses a stored environment when no fresh valid pairing offer is present', () => { + expect( + decideWebPairingStartup({ initialPairingInput: null, hasStoredEnvironment: true }) + ).toEqual({ + kind: 'use-stored-environment' + }) + expect( + decideWebPairingStartup({ initialPairingInput: 'not a code', hasStoredEnvironment: true }) + ).toEqual({ + kind: 'use-stored-environment' + }) + }) }) diff --git a/src/renderer/src/web/web-pairing.ts b/src/renderer/src/web/web-pairing.ts index dc59b362f..f29465cc8 100644 --- a/src/renderer/src/web/web-pairing.ts +++ b/src/renderer/src/web/web-pairing.ts @@ -1,3 +1,5 @@ +import type { DeviceScope } from '../../../shared/runtime-types' + const PAIRING_OFFER_VERSION = 2 export type WebPairingOffer = { @@ -5,8 +7,14 @@ export type WebPairingOffer = { endpoint: string deviceToken: string publicKeyB64: string + scope?: DeviceScope } +export type WebPairingStartupDecision = + | { kind: 'auto-save-runtime-offer'; offer: WebPairingOffer } + | { kind: 'show-connect'; initialPairingInput: string | null } + | { kind: 'use-stored-environment' } + export function parseWebPairingInput(input: string): WebPairingOffer | null { const trimmed = input.trim() if (!trimmed) { @@ -50,6 +58,22 @@ export function readPairingInputFromLocation(location: Location): string | null return hash } +export function decideWebPairingStartup(args: { + initialPairingInput: string | null + hasStoredEnvironment: boolean +}): WebPairingStartupDecision { + const offer = args.initialPairingInput ? parseWebPairingInput(args.initialPairingInput) : null + if (offer?.scope === 'runtime') { + return { kind: 'auto-save-runtime-offer', offer } + } + if (offer) { + return { kind: 'show-connect', initialPairingInput: args.initialPairingInput } + } + return args.hasStoredEnvironment + ? { kind: 'use-stored-environment' } + : { kind: 'show-connect', initialPairingInput: null } +} + export function clearPairingInputFromAddressBar(): void { if (!window.location.hash && !window.location.search) { return @@ -74,14 +98,20 @@ function decodePairingPayload(base64url: string): WebPairingOffer | null { ) { return null } + const scope = parseWebPairingScope(parsed.scope) return { v: PAIRING_OFFER_VERSION, endpoint: normalizeWebSocketEndpoint(parsed.endpoint), deviceToken: parsed.deviceToken, - publicKeyB64: parsed.publicKeyB64 + publicKeyB64: parsed.publicKeyB64, + ...(scope ? { scope } : {}) } } +function parseWebPairingScope(value: unknown): DeviceScope | null { + return value === 'mobile' || value === 'runtime' ? value : null +} + function extractPairingCodeFromUrl(url: string): string | null { let parsed: URL try { diff --git a/src/shared/pairing.test.ts b/src/shared/pairing.test.ts index e0761df7a..298bc2046 100644 --- a/src/shared/pairing.test.ts +++ b/src/shared/pairing.test.ts @@ -22,6 +22,11 @@ describe('pairing offer', () => { expect(decoded).toEqual(offer) }) + it('preserves optional device scope metadata', () => { + const scopedOffer: PairingOffer = { ...offer, scope: 'mobile' } + expect(decodePairingOffer(encodePairingOffer(scopedOffer))).toEqual(scopedOffer) + }) + it('encoded URL uses base64url (no +, /, or = characters)', () => { const url = encodePairingOffer(offer) const code = new URLSearchParams(url.slice(url.indexOf('?') + 1)).get('code')! diff --git a/src/shared/pairing.ts b/src/shared/pairing.ts index d24df0783..9d8364c47 100644 --- a/src/shared/pairing.ts +++ b/src/shared/pairing.ts @@ -1,6 +1,7 @@ import { z } from 'zod' export const PAIRING_OFFER_VERSION = 2 +const PairingScopeSchema = z.enum(['mobile', 'runtime']) export const PairingOfferSchema = z.object({ v: z.literal(PAIRING_OFFER_VERSION), @@ -8,7 +9,10 @@ export const PairingOfferSchema = z.object({ deviceToken: z.string().min(1), // Why: the desktop's Curve25519 public key, base64-encoded. The mobile client // uses this to derive a shared secret via ECDH for end-to-end encryption. - publicKeyB64: z.string().min(1) + publicKeyB64: z.string().min(1), + // Why: advisory UI metadata lets the web client reject phone-QR offers before + // opening a socket; the runtime still authorizes solely from deviceToken. + scope: PairingScopeSchema.optional() }) export type PairingOffer = z.infer diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index 89bd26fad..351574019 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -34,6 +34,10 @@ export type { RuntimeMarkdownReadTabResult, RuntimeMarkdownSaveTabResult } export type RuntimeGraphStatus = 'ready' | 'reloading' | 'unavailable' +// Why: the access scope a paired device token grants. Lives in shared so +// pairing offers, status.get, and the device registry use one vocabulary. +export type DeviceScope = 'mobile' | 'runtime' + // Why: presence-lock driver state crosses main/preload/renderer IPC. Keep one // checked source so future variants cannot drift silently across layers. export type RuntimeTerminalDriverState = @@ -57,6 +61,9 @@ export type RuntimeStatus = { capabilities?: RuntimeCapability[] remoteControl?: RemoteRuntimeSharedConnectionDiagnostics | null hostPlatform?: NodeJS.Platform + // Why: legacy or saved WebSocket pairings may not carry scope metadata, so + // the server stamps the authenticated token scope here for status.get only. + deviceScope?: DeviceScope // COMPAT(runtimeStatusMobileAliases): added 2026-05-15 for mobile builds // that still read these names; new desktop/CLI code uses the fields above. protocolVersion?: number