feat(mobile): surface pairing-auth failures on desktop and mobile (#9782)

* feat(mobile-pairing): surface unpaired-device auth failures instead of silent 4001 loops

Desktop: when a phone repeatedly fails direct-transport E2EE auth with a
token missing from the device registry (pre-v1.4.106 pairing-path bug left
desktops that regenerated their registry rejecting paired phones forever),
throttle to one notification per session and show an actionable toast
pointing at Settings -> Mobile to re-pair.

Mobile: map a bare 4001 close onto the existing auth retry budget (the
encrypted e2ee_error is undecryptable when the desktop keypair changed, so
the close code is the only surviving signal) instead of looping the generic
reconnect forever, and make the auth-failed verdict say 'Pairing invalid -
re-pair with your desktop' instead of a bare 'Auth failed'.

* fix(mobile-pairing): handle stale keys and startup notification races

* fix(mobile-pairing): isolate auth notification failures

* fix(mobile-pairing): keep recovery alert actionable
This commit is contained in:
Brennan Benson
2026-07-22 14:05:37 -07:00
committed by GitHub
parent 8f40419800
commit d6c9fcd537
26 changed files with 702 additions and 19 deletions
@@ -7,7 +7,7 @@ export const MOBILE_SESSION_STATUS_LABELS: Record<ConnectionState, string> = {
connected: 'Connected',
disconnected: 'Disconnected',
reconnecting: 'Reconnecting',
'auth-failed': 'Auth failed'
'auth-failed': 'Pairing invalid'
}
export const TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY = 64
@@ -1,6 +1,19 @@
import { describe, expect, it } from 'vitest'
import { classifyConnection, verdictDisplayLabel } from './connection-health'
describe('classifyConnection auth-failed verdict', () => {
it('tells the user to re-pair instead of showing a generic auth error', () => {
const verdict = classifyConnection({
state: 'auth-failed',
reconnectAttempts: 0,
lastConnectedAt: null,
nowMs: 1_000_000
})
expect(verdict.kind).toBe('auth-failed')
expect(verdictDisplayLabel(verdict)).toBe('Pairing invalid — re-pair with your desktop')
})
})
describe('classifyConnection Tailscale hint', () => {
const base = {
state: 'reconnecting' as const,
+3 -1
View File
@@ -55,8 +55,10 @@ export function classifyConnection(args: {
const now = args.nowMs ?? Date.now()
const hint = isTailscaleEndpoint(args.endpoint) ? TAILSCALE_HINT : undefined
// Why: auth-failed means the desktop no longer recognizes this pairing (e.g. it
// lost its device registry) — retrying can't fix it, only re-pairing can, so say so.
if (state === 'auth-failed') {
return { kind: 'auth-failed', label: 'Auth failed' }
return { kind: 'auth-failed', label: 'Pairing invalid — re-pair with your desktop' }
}
// Connected / connecting / handshaking are normal.
@@ -0,0 +1,169 @@
// Why: separate from rpc-client.test.ts — that file sits at its max-lines cap,
// and the silent-4001 mapping (desktop lost its device registry / regenerated
// its keypair, so the encrypted e2ee_error never decrypts) is its own scenario.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { connect } from './rpc-client'
vi.mock('./e2ee', () => ({
generateKeyPair: () => ({
publicKey: new Uint8Array(32),
secretKey: new Uint8Array(32)
}),
deriveSharedKey: () => new Uint8Array(32),
publicKeyFromBase64: () => new Uint8Array(32),
publicKeyToBase64: () => 'client-public-key',
encrypt: (plaintext: string) => `encrypted:${plaintext}`,
decrypt: (raw: string) => (raw === 'undecryptable' ? null : raw.replace(/^encrypted:/, '')),
decryptBytes: (bytes: Uint8Array) => bytes
}))
class MockWebSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
readonly CONNECTING = MockWebSocket.CONNECTING
readonly OPEN = MockWebSocket.OPEN
readonly CLOSING = MockWebSocket.CLOSING
readonly CLOSED = MockWebSocket.CLOSED
readyState = MockWebSocket.CONNECTING
onopen: (() => void) | null = null
onclose: ((event?: { code?: number; reason?: string; wasClean?: boolean }) => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onerror: (() => void) | null = null
sent: string[] = []
close = vi.fn(() => {
if (this.readyState === MockWebSocket.CLOSED) {
return
}
this.readyState = MockWebSocket.CLOSED
this.onclose?.()
})
constructor(readonly endpoint: string) {
mockSockets.push(this)
}
send(payload: string): void {
this.sent.push(payload)
}
open(): void {
this.readyState = MockWebSocket.OPEN
this.onopen?.()
}
receive(payload: unknown): void {
this.onmessage?.({ data: payload })
}
serverClose(code: number, reason = ''): void {
this.readyState = MockWebSocket.CLOSED
this.onclose?.({ code, reason, wasClean: true })
}
}
const mockSockets: MockWebSocket[] = []
const originalWebSocket = globalThis.WebSocket
function lastSocket(): MockWebSocket {
return mockSockets[mockSockets.length - 1]!
}
describe('unauthorized close-code mapping (silent 4001)', () => {
beforeEach(() => {
vi.useFakeTimers()
mockSockets.length = 0
globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket
})
afterEach(() => {
vi.useRealTimers()
globalThis.WebSocket = originalWebSocket
})
it('counts a bare 4001 close against the auth retry budget and latches auth-failed', async () => {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
// A desktop with a regenerated keypair can't send a decryptable e2ee_error —
// the phone only ever sees the 4001 close. Three of those must latch.
for (let i = 0; i < 3; i++) {
if (i > 0) {
await vi.advanceTimersByTimeAsync(500)
}
const socket = lastSocket()
socket.open()
socket.receive(JSON.stringify({ type: 'e2ee_ready' }))
socket.serverClose(4001, 'Unauthorized')
}
expect(client.getState()).toBe('auth-failed')
expect(mockSockets).toHaveLength(3)
expect(vi.getTimerCount()).toBe(0)
await vi.advanceTimersByTimeAsync(10 * 60_000)
expect(mockSockets).toHaveLength(3)
client.close()
})
it('recovers when a 4001 close was transient and the next handshake succeeds', async () => {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
const first = mockSockets[0]!
first.open()
first.receive(JSON.stringify({ type: 'e2ee_ready' }))
first.serverClose(4001, 'Unauthorized')
expect(client.getState()).toBe('reconnecting')
await vi.advanceTimersByTimeAsync(500)
const next = lastSocket()
next.open()
next.receive(JSON.stringify({ type: 'e2ee_ready' }))
next.receive('encrypted:{"type":"e2ee_authenticated"}')
expect(client.getState()).toBe('connected')
client.close()
})
it('shares one budget between decrypted e2ee_error rejections and 4001 closes', async () => {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
for (let i = 0; i < 3; i++) {
if (i > 0) {
await vi.advanceTimersByTimeAsync(500)
}
const socket = lastSocket()
socket.open()
socket.receive(JSON.stringify({ type: 'e2ee_ready' }))
if (i < 2) {
socket.receive('encrypted:{"type":"e2ee_error","error":{"code":"unauthorized"}}')
} else {
socket.serverClose(4001, 'Unauthorized')
}
}
expect(client.getState()).toBe('auth-failed')
client.close()
})
it('keeps the generic reconnect loop for non-4001 closes', async () => {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
for (let i = 0; i < 5; i++) {
if (i > 0) {
await vi.advanceTimersByTimeAsync(60_000)
}
const socket = lastSocket()
socket.open()
socket.receive(JSON.stringify({ type: 'e2ee_ready' }))
socket.serverClose(1006)
}
expect(client.getState()).toBe('reconnecting')
client.close()
})
})
+17 -2
View File
@@ -98,6 +98,8 @@ const GIVE_UP_AFTER_ATTEMPTS = 12
const TRICKLE_RECONNECT_DELAY_MS = 90_000
// Why: one unauthorized isn't proof the pairing is dead (issue #5200) — retry the handshake this many times before latching auth-failed.
const AUTH_RETRY_BUDGET = 3
// Why: a desktop that regenerated its E2EE keypair sends an e2ee_error we can't decrypt — the 4001 close code is the only surviving auth-failure signal.
const UNAUTHORIZED_CLOSE_CODE = 4001
const REQUEST_TIMEOUT_MS = 30_000
const CONNECT_TIMEOUT_MS = 12_000
const HANDSHAKE_TIMEOUT_MS = 5_000
@@ -603,7 +605,7 @@ export function connect(
})
lastWsClosedAt = closeAt
currentWsOpenedAt = null
handleSocketClosed(openingWs)
handleSocketClosed(openingWs, { closeCode: e?.code })
}
ws.onerror = (event) => {
@@ -623,7 +625,10 @@ export function connect(
}
}
function handleSocketClosed(closedWs: WebSocket, opts: { timedOut?: boolean } = {}) {
function handleSocketClosed(
closedWs: WebSocket,
opts: { timedOut?: boolean; closeCode?: number } = {}
) {
if (ws !== closedWs) {
console.log('[net] handleSocketClosed STALE — ignoring (ws already swapped)', {
state,
@@ -648,6 +653,16 @@ export function connect(
rejectAllPending('Connection closed', { deliveryUnknown: true })
return
}
// Why: a bare 4001 close means the desktop rejected our pairing but the encrypted
// e2ee_error never arrived (or was undecryptable) — count it against the auth
// retry budget instead of looping the generic reconnect forever.
if (opts.closeCode === UNAUTHORIZED_CLOSE_CODE) {
console.log('[net] handleSocketClosed — unauthorized close code', {
attempt: reconnectAttempt
})
handleAuthRejection('Unauthorized — pairing may be revoked')
return
}
console.log('[net] handleSocketClosed → reconnect', {
timedOut: !!opts.timedOut,
pendingCount: pending.size,
+24 -1
View File
@@ -253,6 +253,7 @@ let runtimeRpc: OrcaRuntimeRpcServer | null = null
const serveReadinessPublisher = new ServeReadinessPublisher()
let desktopRelayService: DesktopRelayService | null = null
let desktopRelayStatus: RelayBrokerStatus = 'offline'
let pendingUnpairedDeviceAuthFailure = false
// Why: gates whether headless serve installs the offscreen browser backend (and advertises browser pane support).
let headlessBrowserDisplayAvailable = false
@@ -2281,7 +2282,29 @@ app.whenReady().then(async () => {
: {}),
webClientRoot: getBundledWebClientRoot()
})
registerMobileHandlers(runtimeRpc, { getRelayStatus: () => desktopRelayStatus })
registerMobileHandlers(runtimeRpc, {
getRelayStatus: () => desktopRelayStatus,
consumePendingUnpairedDeviceAuthFailure: (webContentsId) => {
if (
!mainWindow ||
mainWindow.isDestroyed() ||
mainWindow.webContents.id !== webContentsId ||
!pendingUnpairedDeviceAuthFailure
) {
return false
}
pendingUnpairedDeviceAuthFailure = false
return true
}
})
// Why: repeated direct auth failures otherwise look like a client that never connects; point users to re-pairing.
runtimeRpc.setOnUnpairedDeviceAuthFailure(() => {
// Why: runtime startup races renderer mount; retain the one-shot until the listener consumes it.
pendingUnpairedDeviceAuthFailure = true
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.webContents.send('mobile:unpairedDeviceAuthFailure')
}
})
startTerminalRuntimeStartupServices()
app.on('activate', requestDesktopActivation)
+19
View File
@@ -273,6 +273,25 @@ describe('registerMobileHandlers', () => {
expect(handlers.get('mobile:getRelayStatus')?.()).toEqual({ status: 'registered' })
})
it('consumes a pending auth-failure notification only from a window renderer', () => {
const consumePendingUnpairedDeviceAuthFailure = vi.fn(() => true)
registerMobileHandlers({} as never, { consumePendingUnpairedDeviceAuthFailure })
expect(
handlers.get('mobile:consumePendingUnpairedDeviceAuthFailure')?.({
sender: { id: 42, isDestroyed: () => false, getType: () => 'window' }
})
).toBe(true)
expect(consumePendingUnpairedDeviceAuthFailure).toHaveBeenCalledWith(42)
expect(
handlers.get('mobile:consumePendingUnpairedDeviceAuthFailure')?.({
sender: { id: 99, isDestroyed: () => false, getType: () => 'webview' }
})
).toBe(false)
expect(consumePendingUnpairedDeviceAuthFailure).toHaveBeenCalledOnce()
})
it('inspects and repairs the current packaged Windows websocket port', async () => {
const runPowerShell = vi
.fn()
+8
View File
@@ -63,6 +63,7 @@ export type MobileHandlerDependencies = {
firewallEnvironment?: WindowsMobileFirewallEnvironment
openWindowsNetworkSettings?: () => Promise<void>
getRelayStatus?: () => RelayBrokerStatus
consumePendingUnpairedDeviceAuthFailure?: (webContentsId: number) => boolean
}
export function registerMobileHandlers(
@@ -252,6 +253,13 @@ export function registerMobileHandlers(
ipcMain.handle('mobile:getRelayStatus', () => ({
status: dependencies.getRelayStatus?.() ?? 'offline'
}))
ipcMain.handle('mobile:consumePendingUnpairedDeviceAuthFailure', (event) => {
if (!isWindowRenderer(event)) {
return false
}
return dependencies.consumePendingUnpairedDeviceAuthFailure?.(event.sender.id) ?? false
})
}
function isWindowRenderer(event: IpcMainInvokeEvent): boolean {
+20
View File
@@ -113,6 +113,26 @@ describe('E2EEChannel', () => {
expect(ctx.onReady).not.toHaveBeenCalled()
})
it('rejects an auth frame encrypted to a stale desktop key', () => {
const ctx = setup()
ctx.channel.handleRawMessage(
JSON.stringify({
type: 'e2ee_hello',
publicKeyB64: publicKeyToBase64(ctx.clientKeys.publicKey)
})
)
const staleServer = generateKeyPair()
const staleSharedKey = deriveSharedKey(ctx.clientKeys.secretKey, staleServer.publicKey)
ctx.channel.handleRawMessage(
encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), staleSharedKey)
)
expect(ctx.onError).toHaveBeenCalledOnce()
expect(ctx.onError).toHaveBeenCalledWith(4001, 'Unauthorized')
expect(ctx.onReady).not.toHaveBeenCalled()
})
it('rejects malformed JSON', () => {
const ctx = setup()
ctx.channel.handleRawMessage('not json')
+6 -8
View File
@@ -1,6 +1,4 @@
// Why: the E2EE channel sits between the WebSocket transport and the RPC handler.
// It owns the handshake state machine and transparent encrypt/decrypt so the RPC
// handler only sees plaintext JSON, identical to the Unix socket path.
// Why: this channel keeps E2EE framing out of RPC handlers, which consume plaintext across transports.
import type { WebSocket } from 'ws'
import { deriveSharedKey, encrypt, decrypt, encryptBytes, decryptBytes } from './e2ee-crypto'
import {
@@ -53,9 +51,7 @@ export class E2EEChannel {
private readonly requireV2: boolean
private v2Session: DesktopMobileE2EEV2Session | null = null
private v2OutboundQueue: WsOutboundBackpressureQueue<V2OutboundItem> | null = null
// Why: the RPC handler is set after the channel is ready, so the channel
// can forward decrypted messages. Kept as a callback rather than constructor
// param because the handler needs the encrypt function for replies.
// Why: the handler is set after readiness because its reply closure needs this channel's encryption state.
private messageHandler:
| ((
plaintext: string,
@@ -173,8 +169,10 @@ export class E2EEChannel {
}
private trackDecryptFailure(): void {
this.consecutiveFailures++
if (this.consecutiveFailures >= MAX_CONSECUTIVE_DECRYPT_FAILURES) {
// Why: a wrong key cannot recover on this socket; close so the client uses its bounded auth retry budget.
if (this.state === 'awaiting_auth') {
this.onError(4001, 'Unauthorized')
} else if (++this.consecutiveFailures >= MAX_CONSECUTIVE_DECRYPT_FAILURES) {
this.onError(4003, 'Too many decryption failures')
}
}
@@ -139,6 +139,97 @@ describe('MobileSocketWiring', () => {
expect(wiring.connectionCount).toBe(0)
})
it('closes an unknown-token socket even when reporting the failure throws', () => {
const desktop = generateKeyPair()
const phone = generateKeyPair()
const ws = new FakeSocket()
const transport = new FakeTransport()
const notificationError = new Error('renderer exited')
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const onUnpairedDeviceAuthFailure = vi.fn(() => {
throw notificationError
})
const wiring = new MobileSocketWiring({
deviceRegistry: registryFor('device-1', 'valid-token'),
e2eeKeypair: {
publicKey: desktop.publicKey,
secretKey: desktop.secretKey,
publicKeyB64: Buffer.from(desktop.publicKey).toString('base64')
},
onText: vi.fn(),
onBinary: vi.fn(),
onClose: vi.fn(),
onUnpairedDeviceAuthFailure
})
wiring.attachTransport(transport)
transport.receive(
ws,
JSON.stringify({
type: 'e2ee_hello',
publicKeyB64: Buffer.from(phone.publicKey).toString('base64')
})
)
const sharedKey = deriveSharedKey(phone.secretKey, desktop.publicKey)
expect(() =>
transport.receive(
ws,
encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'stale-token' }), sharedKey)
)
).not.toThrow()
expect(onUnpairedDeviceAuthFailure).toHaveBeenCalledOnce()
expect(onUnpairedDeviceAuthFailure).toHaveBeenCalledWith({ transport: 'direct' })
expect(consoleError).toHaveBeenCalledWith(
'[mobile] Failed to report unpaired-device auth failure:',
notificationError
)
expect(transport.setClientId).not.toHaveBeenCalled()
expect(ws.close).toHaveBeenCalledWith(4001, 'Unauthorized')
expect(wiring.channelCount).toBe(0)
consoleError.mockRestore()
})
it('reports auth encrypted to a stale desktop key on the direct path', () => {
const currentDesktop = generateKeyPair()
const staleDesktop = generateKeyPair()
const phone = generateKeyPair()
const ws = new FakeSocket()
const transport = new FakeTransport()
const onUnpairedDeviceAuthFailure = vi.fn()
const wiring = new MobileSocketWiring({
deviceRegistry: registryFor('device-1', 'valid-token'),
e2eeKeypair: {
publicKey: currentDesktop.publicKey,
secretKey: currentDesktop.secretKey,
publicKeyB64: Buffer.from(currentDesktop.publicKey).toString('base64')
},
onText: vi.fn(),
onBinary: vi.fn(),
onClose: vi.fn(),
onUnpairedDeviceAuthFailure
})
wiring.attachTransport(transport)
transport.receive(
ws,
JSON.stringify({
type: 'e2ee_hello',
publicKeyB64: Buffer.from(phone.publicKey).toString('base64')
})
)
const staleSharedKey = deriveSharedKey(phone.secretKey, staleDesktop.publicKey)
transport.receive(
ws,
encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: 'valid-token' }), staleSharedKey)
)
expect(onUnpairedDeviceAuthFailure).toHaveBeenCalledOnce()
expect(onUnpairedDeviceAuthFailure).toHaveBeenCalledWith({ transport: 'direct' })
expect(transport.setClientId).not.toHaveBeenCalled()
expect(ws.close).toHaveBeenCalledWith(4001, 'Unauthorized')
})
it('rejects a relay socket whose immutable relayDeviceId differs from E2EE identity', () => {
const desktop = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(1))
const phone = nacl.box.keyPair.fromSecretKey(new Uint8Array(32).fill(2))
@@ -50,6 +50,8 @@ type MobileSocketWiringOptions = {
onBinary: (socket: AuthenticatedMobileSocket, bytes: Uint8Array<ArrayBufferLike>) => void
onClose: (socket: AuthenticatedMobileSocket | null, hasOtherConnections: boolean) => void
onReady?: (socket: AuthenticatedMobileSocket) => void
// Why: stale keys and missing registry entries both fail before RPC can explain the re-pair action.
onUnpairedDeviceAuthFailure?: (metadata: MobileSocketTransportMetadata) => void
}
function toAuthenticatedDevice(device: DeviceEntry): E2EEAuthenticatedDevice {
@@ -67,6 +69,7 @@ export class MobileSocketWiring {
private readonly onBinary: MobileSocketWiringOptions['onBinary']
private readonly onClose: MobileSocketWiringOptions['onClose']
private readonly onReady: MobileSocketWiringOptions['onReady']
private readonly onUnpairedDeviceAuthFailure: MobileSocketWiringOptions['onUnpairedDeviceAuthFailure']
private readonly channels = new Map<WebSocket, E2EEChannel>()
private readonly connectionIds = new Map<WebSocket, string>()
private readonly authenticatedSockets = new Map<WebSocket, AuthenticatedMobileSocket>()
@@ -79,6 +82,7 @@ export class MobileSocketWiring {
this.onBinary = options.onBinary
this.onClose = options.onClose
this.onReady = options.onReady
this.onUnpairedDeviceAuthFailure = options.onUnpairedDeviceAuthFailure
}
attachTransport(
@@ -151,9 +155,18 @@ export class MobileSocketWiring {
this.onReady?.(socket)
},
onError: (code, reason) => {
const reportUnpairedDevice = code === 4001 && reason === 'Unauthorized'
this.channels.get(ws)?.destroy()
this.channels.delete(ws)
ws.close(code, reason)
if (reportUnpairedDevice) {
try {
this.onUnpairedDeviceAuthFailure?.(metadata)
} catch (error) {
// Why: renderer teardown can make UI delivery throw; auth cleanup must remain authoritative.
console.error('[mobile] Failed to report unpaired-device auth failure:', error)
}
}
}
})
channel.onMessage((plaintext, reply, sendBinary) => {
@@ -0,0 +1,63 @@
import { describe, expect, it, vi } from 'vitest'
import { UnpairedDeviceAuthThrottle } from './unpaired-device-auth-throttle'
function throttleAt(clock: { time: number }, onTrigger = vi.fn()) {
const throttle = new UnpairedDeviceAuthThrottle({
onTrigger,
failureThreshold: 3,
windowMs: 60_000,
now: () => clock.time
})
return { throttle, onTrigger }
}
describe('UnpairedDeviceAuthThrottle', () => {
it('stays silent below the failure threshold', () => {
const clock = { time: 0 }
const { throttle, onTrigger } = throttleAt(clock)
throttle.recordFailure()
clock.time += 1000
throttle.recordFailure()
expect(onTrigger).not.toHaveBeenCalled()
})
it('fires once when the threshold is reached inside the window', () => {
const clock = { time: 0 }
const { throttle, onTrigger } = throttleAt(clock)
for (let i = 0; i < 3; i++) {
throttle.recordFailure()
clock.time += 500
}
expect(onTrigger).toHaveBeenCalledOnce()
})
it('never fires twice in one session even as failures continue', () => {
const clock = { time: 0 }
const { throttle, onTrigger } = throttleAt(clock)
for (let i = 0; i < 20; i++) {
throttle.recordFailure()
clock.time += 500
}
expect(onTrigger).toHaveBeenCalledOnce()
})
it('ignores failures that fall outside the window', () => {
const clock = { time: 0 }
const { throttle, onTrigger } = throttleAt(clock)
throttle.recordFailure()
clock.time += 61_000
throttle.recordFailure()
clock.time += 61_000
throttle.recordFailure()
expect(onTrigger).not.toHaveBeenCalled()
// A real retry burst after the stray singles still triggers.
clock.time += 61_000
throttle.recordFailure()
clock.time += 100
throttle.recordFailure()
clock.time += 100
throttle.recordFailure()
expect(onTrigger).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,47 @@
// Why: a desktop that lost its device registry (pre-v1.4.106 pairing-path bug)
// rejects previously-paired phones with 4001 forever while both ends stay
// silent. This gate turns that repeated failure pattern into ONE user-facing
// signal per runtime session, without firing on a single stray probe.
const DEFAULT_FAILURE_THRESHOLD = 3
const DEFAULT_WINDOW_MS = 60_000
export type UnpairedDeviceAuthThrottleOptions = {
onTrigger: () => void
// Failures within windowMs needed before onTrigger fires (default 3 in 60s).
failureThreshold?: number
windowMs?: number
now?: () => number
}
export class UnpairedDeviceAuthThrottle {
private readonly onTrigger: () => void
private readonly failureThreshold: number
private readonly windowMs: number
private readonly now: () => number
private readonly failureTimestamps: number[] = []
private triggered = false
constructor(options: UnpairedDeviceAuthThrottleOptions) {
this.onTrigger = options.onTrigger
this.failureThreshold = options.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD
this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS
this.now = options.now ?? Date.now
}
recordFailure(): void {
if (this.triggered) {
return
}
const now = this.now()
this.failureTimestamps.push(now)
while (this.failureTimestamps.length > 0 && now - this.failureTimestamps[0]! > this.windowMs) {
this.failureTimestamps.shift()
}
if (this.failureTimestamps.length >= this.failureThreshold) {
this.triggered = true
this.failureTimestamps.length = 0
this.onTrigger()
}
}
}
+18
View File
@@ -16,6 +16,7 @@ import { readWsFallbackPort, writeWsFallbackPort } from './rpc/ws-fallback-port-
import type { WebSocket } from 'ws'
import { DeviceRegistry, type DeviceEntry, type DeviceScope } from './device-registry'
import { loadOrCreateE2EEKeypair, type E2EEKeypair } from './e2ee-keypair'
import { UnpairedDeviceAuthThrottle } from './rpc/unpaired-device-auth-throttle'
import {
MobileSocketWiring,
type AuthenticatedMobileSocket,
@@ -437,6 +438,8 @@ export class OrcaRuntimeRpcServer {
private transports: RuntimeTransportMetadata[] = []
private mobileSocketWiring: MobileSocketWiring | null = null
private mobileRelayPairingProvider: MobileRelayPairingProvider | null = null
private onUnpairedDeviceAuthFailure: (() => void) | null = null
private unpairedDeviceAuthThrottle: UnpairedDeviceAuthThrottle | null = null
private readonly binaryStreamHandlers = new Map<
string,
Map<number, (frame: TerminalStreamFrame) => void>
@@ -521,6 +524,11 @@ export class OrcaRuntimeRpcServer {
return updated
}
// Why: only the desktop shell can surface UI; headless serve leaves this unset.
setOnUnpairedDeviceAuthFailure(callback: (() => void) | null): void {
this.onUnpairedDeviceAuthFailure = callback
}
setMobileRelayPairingProvider(provider: MobileRelayPairingProvider | null): void {
this.mobileRelayPairingProvider = provider
}
@@ -888,6 +896,10 @@ export class OrcaRuntimeRpcServer {
...(this.wsPort !== 0 ? { fallbackPort: readWsFallbackPort(this.userDataPath) } : {}),
...(this.preferPinnedWsPort ? { preferPinnedPort: true } : {})
})
// Why: session-scoped (recreated per start) so each desktop launch may notify once.
this.unpairedDeviceAuthThrottle = new UnpairedDeviceAuthThrottle({
onTrigger: () => this.onUnpairedDeviceAuthFailure?.()
})
const mobileSocketWiring = new MobileSocketWiring({
deviceRegistry: pairingIdentity.deviceRegistry,
e2eeKeypair: pairingIdentity.e2eeKeypair,
@@ -924,6 +936,12 @@ export class OrcaRuntimeRpcServer {
if (!hasOtherConnections) {
this.runtime.onClientDisconnected(socket.device.deviceToken)
}
},
// Why: relay attempts are authorized upstream; only direct failures should prompt local re-pairing.
onUnpairedDeviceAuthFailure: (metadata) => {
if (metadata.transport === 'direct') {
this.unpairedDeviceAuthThrottle?.recordFailure()
}
}
})
mobileSocketWiring.attachTransport(wsTransport)
+4
View File
@@ -3279,6 +3279,10 @@ export type PreloadApi = {
isWebSocketReady: () => Promise<{ ready: boolean; endpoint: string | null }>
getRelayStatus: () => Promise<{ status: MobileRelayStatus }>
onRelayStatusChanged: (callback: (status: MobileRelayStatus) => void) => () => void
/** Consumes an auth-failure notification that arrived before the renderer listener mounted. */
consumePendingUnpairedDeviceAuthFailure?: () => Promise<boolean>
/** Fires (throttled, once per session) when an unpaired phone repeatedly fails direct-transport auth. */
onUnpairedDeviceAuthFailure?: (callback: () => void) => () => void
}
speech: {
getCatalog: () => Promise<SpeechModelManifest[]>
+10
View File
@@ -4368,6 +4368,16 @@ const api = {
callback(status)
ipcRenderer.on('mobile:relayStatusChanged', listener)
return () => ipcRenderer.removeListener('mobile:relayStatusChanged', listener)
},
consumePendingUnpairedDeviceAuthFailure: (): Promise<boolean> =>
ipcRenderer.invoke('mobile:consumePendingUnpairedDeviceAuthFailure'),
/** Fires (throttled, once per session) when an unpaired phone repeatedly fails direct-transport auth. */
onUnpairedDeviceAuthFailure: (callback: () => void): (() => void) => {
const listener = () => callback()
ipcRenderer.on('mobile:unpairedDeviceAuthFailure', listener)
return () => ipcRenderer.removeListener('mobile:unpairedDeviceAuthFailure', listener)
}
},
@@ -0,0 +1,85 @@
import { describe, expect, it, vi } from 'vitest'
import { subscribeToUnpairedDeviceAuthNotification } from './unpaired-device-auth-notification'
describe('subscribeToUnpairedDeviceAuthNotification', () => {
it('delivers a notification retained before the renderer subscribed', async () => {
const onNotification = vi.fn()
const unsubscribe = subscribeToUnpairedDeviceAuthNotification(
{
consumePendingUnpairedDeviceAuthFailure: vi.fn().mockResolvedValue(true),
onUnpairedDeviceAuthFailure: vi.fn(() => vi.fn())
},
onNotification
)
await Promise.resolve()
expect(onNotification).toHaveBeenCalledOnce()
unsubscribe()
})
it('consumes concurrent mount and live signals only once', async () => {
const onNotification = vi.fn()
const listenerState: { liveListener?: () => void } = {}
const consumePendingUnpairedDeviceAuthFailure = vi
.fn()
.mockResolvedValueOnce(true)
.mockResolvedValue(false)
const unsubscribe = subscribeToUnpairedDeviceAuthNotification(
{
consumePendingUnpairedDeviceAuthFailure,
onUnpairedDeviceAuthFailure: (listener) => {
listenerState.liveListener = listener
return vi.fn()
}
},
onNotification
)
listenerState.liveListener?.()
await Promise.resolve()
expect(consumePendingUnpairedDeviceAuthFailure).toHaveBeenCalledTimes(2)
expect(onNotification).toHaveBeenCalledOnce()
unsubscribe()
})
it('keeps live delivery with an older preload that has no consume API', () => {
const onNotification = vi.fn()
const listenerState: { liveListener?: () => void } = {}
const unsubscribe = subscribeToUnpairedDeviceAuthNotification(
{
onUnpairedDeviceAuthFailure: (listener) => {
listenerState.liveListener = listener
return vi.fn()
}
},
onNotification
)
expect(onNotification).not.toHaveBeenCalled()
listenerState.liveListener?.()
expect(onNotification).toHaveBeenCalledOnce()
unsubscribe()
})
it('finishes an in-flight one-shot claim across StrictMode cleanup', async () => {
const pendingState: { resolve?: (pending: boolean) => void } = {}
const onNotification = vi.fn()
const unsubscribe = subscribeToUnpairedDeviceAuthNotification(
{
consumePendingUnpairedDeviceAuthFailure: () =>
new Promise((resolve) => {
pendingState.resolve = resolve
})
},
onNotification
)
unsubscribe()
pendingState.resolve?.(true)
await Promise.resolve()
expect(onNotification).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,37 @@
type UnpairedDeviceAuthNotificationApi = {
consumePendingUnpairedDeviceAuthFailure?: () => Promise<boolean>
onUnpairedDeviceAuthFailure?: (callback: () => void) => () => void
}
export function subscribeToUnpairedDeviceAuthNotification(
api: UnpairedDeviceAuthNotificationApi | undefined,
onNotification: () => void
): () => void {
const consume = (notifyIfUnavailable: boolean): void => {
if (!api?.consumePendingUnpairedDeviceAuthFailure) {
if (notifyIfUnavailable) {
onNotification()
}
return
}
void api
.consumePendingUnpairedDeviceAuthFailure()
.then((pending) => {
if (pending) {
onNotification()
}
})
.catch(() => {
if (notifyIfUnavailable) {
onNotification()
}
})
}
const unsubscribe = api?.onUnpairedDeviceAuthFailure?.(() => consume(true)) ?? (() => {})
// Why: main may reach the throttle while the renderer is still mounting; pull that retained one-shot after subscribing.
consume(false)
// Why: an in-flight true result has already consumed main's one-shot, so cleanup detaches events but lets that claim finish (including StrictMode remounts).
return unsubscribe
}
+31
View File
@@ -87,6 +87,7 @@ import { attachMobileMarkdownBridge } from '@/runtime/mobile-markdown-bridge'
import { closeMobileSessionTabInStore } from '@/runtime/mobile-session-tab-close'
import { createWorktreeChangeRefreshQueue } from './worktree-change-refresh-queue'
import { subscribeRuntimeClientEvents } from '@/runtime/runtime-client-events'
import { subscribeToUnpairedDeviceAuthNotification } from './unpaired-device-auth-notification'
import {
applyRuntimeEnvironmentSshStateChanged,
hydrateRuntimeEnvironmentSshState
@@ -1177,6 +1178,36 @@ export function useIpcEvents(): void {
}) ?? (() => {})
)
// Why: a phone stuck in a silent 4001 auth loop (lost device registry) reads as
// "phone won't connect" with no clue on either end; main throttles to once per session.
unsubs.push(
subscribeToUnpairedDeviceAuthNotification(window.api.mobile, () => {
toast.warning(
translate(
'auto.hooks.useIpcEvents.ef223fbb6b',
'A device tried to connect but is not paired'
),
{
id: 'unpaired-device-auth-failure',
description: translate(
'auto.hooks.useIpcEvents.11992d0337',
'If this was your phone or another Orca client, re-pair it from Settings → Mobile.'
),
// Why: main emits this recovery path once per session, so it must remain visible until acted on or dismissed.
duration: Infinity,
action: {
label: translate('auto.hooks.useIpcEvents.6573cfe955', 'Open Mobile Settings'),
onClick: () => {
const store = useAppStore.getState()
store.openSettingsTarget({ pane: 'mobile', repoId: null })
store.openSettingsPage()
}
}
}
)
})
)
unsubs.push(
window.api.ui.onOpenFeatureTour(() => {
useAppStore.getState().openModal('feature-wall', { source: 'help_menu' })
+4 -1
View File
@@ -679,7 +679,10 @@
"2fe88c2e06": "Remote workspace sync unavailable",
"2ec42e1c52": "No remote workspace yet",
"88214a785b": "Workspace sync waited for local session hydration and timed out",
"4f78ba5885": "Workspace synced"
"4f78ba5885": "Workspace synced",
"ef223fbb6b": "A device tried to connect but is not paired",
"11992d0337": "If this was your phone or another Orca client, re-pair it from Settings → Mobile.",
"6573cfe955": "Open Mobile Settings"
},
"useSettingsNavigationMetadata": {
"4a728cd56b": "New features that are still taking shape. Give them a try.",
+4 -1
View File
@@ -656,7 +656,10 @@
"2fe88c2e06": "La sincronización del espacio de trabajo remoto no está disponible",
"2ec42e1c52": "Aún no hay espacio de trabajo remoto",
"88214a785b": "La sincronización del espacio de trabajo esperó a que la sesión local terminara de cargarse y agotó el tiempo de espera",
"4f78ba5885": "Espacio de trabajo sincronizado"
"4f78ba5885": "Espacio de trabajo sincronizado",
"ef223fbb6b": "A device tried to connect but is not paired",
"11992d0337": "If this was your phone or another Orca client, re-pair it from Settings → Mobile.",
"6573cfe955": "Open Mobile Settings"
},
"useSettingsNavigationMetadata": {
"4a728cd56b": "Nuevas funciones que aún están tomando forma. Pruébalas.",
+4 -1
View File
@@ -656,7 +656,10 @@
"2fe88c2e06": "リモートワークスペースの同期は利用できません",
"2ec42e1c52": "リモートワークスペースはまだありません",
"88214a785b": "ワークスペースの同期はローカル セッションのハイドレーションを待機し、タイムアウトになりました",
"4f78ba5885": "ワークスペースが同期されました"
"4f78ba5885": "ワークスペースが同期されました",
"ef223fbb6b": "A device tried to connect but is not paired",
"11992d0337": "If this was your phone or another Orca client, re-pair it from Settings → Mobile.",
"6573cfe955": "Open Mobile Settings"
},
"useSettingsNavigationMetadata": {
"4a728cd56b": "まだ形になりつつある新機能。試してみてください。",
+4 -1
View File
@@ -656,7 +656,10 @@
"2fe88c2e06": "원격 워크스페이스 동기화를 사용할 수 없습니다.",
"2ec42e1c52": "아직 원격 워크스페이스가 없습니다.",
"88214a785b": "워크스페이스 동기화가 로컬 세션 하이드레이션을 기다렸다가 시간 초과되었습니다.",
"4f78ba5885": "워크스페이스가 동기화되었습니다."
"4f78ba5885": "워크스페이스가 동기화되었습니다.",
"ef223fbb6b": "A device tried to connect but is not paired",
"11992d0337": "If this was your phone or another Orca client, re-pair it from Settings → Mobile.",
"6573cfe955": "Open Mobile Settings"
},
"useSettingsNavigationMetadata": {
"4a728cd56b": "아직 구체화되고 있는 새로운 기능입니다. 한번 시도해 보세요.",
+4 -1
View File
@@ -656,7 +656,10 @@
"2fe88c2e06": "远程工作区同步不可用",
"2ec42e1c52": "还没有远程工作区",
"88214a785b": "工作区同步等待本地会话恢复(hydration)并超时",
"4f78ba5885": "工作区已同步"
"4f78ba5885": "工作区已同步",
"ef223fbb6b": "A device tried to connect but is not paired",
"11992d0337": "If this was your phone or another Orca client, re-pair it from Settings → Mobile.",
"6573cfe955": "Open Mobile Settings"
},
"useSettingsNavigationMetadata": {
"4a728cd56b": "仍在完善中的新功能。尝试一下。",
+3 -1
View File
@@ -799,7 +799,9 @@ function createWebPreloadApi(): Partial<PreloadApi> {
isWebSocketReady: () =>
Promise.resolve({ ready: Boolean(activeEnvironment), endpoint: null }),
getRelayStatus: () => Promise.resolve({ status: 'offline' as const }),
onRelayStatusChanged: () => noopUnsubscribe
onRelayStatusChanged: () => noopUnsubscribe,
consumePendingUnpairedDeviceAuthFailure: () => Promise.resolve(false),
onUnpairedDeviceAuthFailure: () => noopUnsubscribe
},
telemetryTrack: () => Promise.resolve(),
telemetrySetOptIn: () => Promise.resolve(),