Refactor runtime app architecture (#1878)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -251,6 +251,9 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
experimentalPet: false,
|
||||
experimentalActivity: true,
|
||||
experimentalWorktreeSymlinks: false,
|
||||
// Why: local desktop remains the default server until the user explicitly
|
||||
// selects a saved runtime environment.
|
||||
activeRuntimeEnvironmentId: null,
|
||||
// Why: hydrate an empty default so the renderer's optional-chained reads
|
||||
// (`settings?.githubProjects?.activeProject`) land on a stable shape
|
||||
// instead of `undefined`. Upgraded profiles inherit this via the
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isPathInsideOrEqual, relativePathInsideRoot } from './cross-platform-path'
|
||||
|
||||
describe('cross-platform path containment', () => {
|
||||
it('keeps POSIX sibling prefixes outside the root', () => {
|
||||
expect(isPathInsideOrEqual('/repo/app', '/repo/app')).toBe(true)
|
||||
expect(isPathInsideOrEqual('/repo/app', '/repo/app/src/index.ts')).toBe(true)
|
||||
expect(isPathInsideOrEqual('/repo/app', '/repo/application/src/index.ts')).toBe(false)
|
||||
expect(relativePathInsideRoot('/repo/app/', '/repo/app/src/index.ts')).toBe('src/index.ts')
|
||||
})
|
||||
|
||||
it('handles Windows drive roots and sibling drives case-insensitively', () => {
|
||||
expect(isPathInsideOrEqual('C:\\Repo', 'c:\\repo\\src\\index.ts')).toBe(true)
|
||||
expect(relativePathInsideRoot('C:\\Repo', 'c:\\repo\\src\\index.ts')).toBe('src/index.ts')
|
||||
expect(isPathInsideOrEqual('C:\\Repo', 'D:\\Repo\\src\\index.ts')).toBe(false)
|
||||
expect(relativePathInsideRoot('C:\\', 'c:\\repo\\src\\index.ts')).toBe('repo/src/index.ts')
|
||||
})
|
||||
|
||||
it('handles UNC roots, trailing slashes, mixed separators, and case', () => {
|
||||
expect(isPathInsideOrEqual('\\\\Server\\Share\\Repo\\', '//server/share/repo/src')).toBe(true)
|
||||
expect(relativePathInsideRoot('\\\\Server\\Share\\Repo\\', '//server/share/repo/src')).toBe(
|
||||
'src'
|
||||
)
|
||||
expect(isPathInsideOrEqual('\\\\Server\\Share\\Repo', '\\\\server\\share\\repo2')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
export function isWindowsAbsolutePathLike(value: string): boolean {
|
||||
return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('\\\\') || value.startsWith('//')
|
||||
}
|
||||
|
||||
export function normalizeRuntimePathSeparators(value: string): string {
|
||||
const normalized = value.replace(/\\/g, '/').replace(/\/+/g, '/')
|
||||
if (value.startsWith('\\\\') || value.startsWith('//')) {
|
||||
return `//${normalized.replace(/^\/+/, '')}`
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function normalizeRuntimePathForComparison(value: string): string {
|
||||
const normalized = trimRuntimePathTrailingSlash(normalizeRuntimePathSeparators(value))
|
||||
return isWindowsAbsolutePathLike(value) ? normalized.toLowerCase() : normalized
|
||||
}
|
||||
|
||||
export function isPathInsideOrEqual(rootPath: string, candidatePath: string): boolean {
|
||||
const root = normalizeRuntimePathForComparison(rootPath)
|
||||
const candidate = normalizeRuntimePathForComparison(candidatePath)
|
||||
if (candidate === root) {
|
||||
return true
|
||||
}
|
||||
const rootWithBoundary =
|
||||
root === '/' || /^[a-z]:\/$/i.test(root) ? root : `${root.replace(/\/+$/, '')}/`
|
||||
return candidate.startsWith(rootWithBoundary)
|
||||
}
|
||||
|
||||
export function relativePathInsideRoot(rootPath: string, candidatePath: string): string | null {
|
||||
const normalizedRoot = trimRuntimePathTrailingSlash(normalizeRuntimePathSeparators(rootPath))
|
||||
const normalizedCandidate = trimRuntimePathTrailingSlash(
|
||||
normalizeRuntimePathSeparators(candidatePath)
|
||||
)
|
||||
const comparisonRoot = isWindowsAbsolutePathLike(rootPath)
|
||||
? normalizedRoot.toLowerCase()
|
||||
: normalizedRoot
|
||||
const comparisonCandidate = isWindowsAbsolutePathLike(rootPath)
|
||||
? normalizedCandidate.toLowerCase()
|
||||
: normalizedCandidate
|
||||
|
||||
if (comparisonCandidate === comparisonRoot) {
|
||||
return ''
|
||||
}
|
||||
const isRoot = comparisonRoot === '/' || /^[a-z]:\/$/i.test(comparisonRoot)
|
||||
const comparisonPrefix = isRoot ? comparisonRoot : `${comparisonRoot}/`
|
||||
if (!comparisonCandidate.startsWith(comparisonPrefix)) {
|
||||
return null
|
||||
}
|
||||
return normalizedCandidate.slice(comparisonPrefix.length)
|
||||
}
|
||||
|
||||
function trimRuntimePathTrailingSlash(value: string): string {
|
||||
if (value === '/' || /^[A-Za-z]:\/$/.test(value)) {
|
||||
return value
|
||||
}
|
||||
return value.replace(/\/+$/, '')
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Why: Orca's remote runtime transports share one NaCl box format across
|
||||
// desktop, CLI, and mobile pairing. Keeping the Node-compatible primitives in
|
||||
// shared code prevents the CLI from importing main-process modules.
|
||||
import nacl from 'tweetnacl'
|
||||
|
||||
export function generateKeyPair(): nacl.BoxKeyPair {
|
||||
return nacl.box.keyPair()
|
||||
}
|
||||
|
||||
export function deriveSharedKey(ourSecretKey: Uint8Array, peerPublicKey: Uint8Array): Uint8Array {
|
||||
return nacl.box.before(peerPublicKey, ourSecretKey)
|
||||
}
|
||||
|
||||
export function publicKeyFromBase64(b64: string): Uint8Array {
|
||||
const key = Uint8Array.from(Buffer.from(b64, 'base64'))
|
||||
if (key.length !== 32) {
|
||||
throw new Error(`Invalid public key: expected 32 bytes, got ${key.length}`)
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
export function publicKeyToBase64(key: Uint8Array): string {
|
||||
return Buffer.from(key).toString('base64')
|
||||
}
|
||||
|
||||
export function encrypt(plaintext: string, sharedKey: Uint8Array): string {
|
||||
const messageBytes = new TextEncoder().encode(plaintext)
|
||||
return Buffer.from(encryptBytes(messageBytes, sharedKey)).toString('base64')
|
||||
}
|
||||
|
||||
export function decrypt(encrypted: string, sharedKey: Uint8Array): string | null {
|
||||
const bundle = Uint8Array.from(Buffer.from(encrypted, 'base64'))
|
||||
const plaintext = decryptBytes(bundle, sharedKey)
|
||||
return plaintext ? new TextDecoder().decode(plaintext) : null
|
||||
}
|
||||
|
||||
export function encryptBytes(
|
||||
plaintext: Uint8Array<ArrayBufferLike>,
|
||||
sharedKey: Uint8Array
|
||||
): Uint8Array {
|
||||
const nonce = nacl.randomBytes(nacl.box.nonceLength)
|
||||
const ciphertext = nacl.box.after(plaintext, nonce, sharedKey)
|
||||
|
||||
const bundle = new Uint8Array(nonce.length + ciphertext.length)
|
||||
bundle.set(nonce)
|
||||
bundle.set(ciphertext, nonce.length)
|
||||
|
||||
return bundle
|
||||
}
|
||||
|
||||
export function decryptBytes(bundle: Uint8Array, sharedKey: Uint8Array): Uint8Array | null {
|
||||
if (bundle.length < nacl.box.nonceLength + nacl.box.overheadLength) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nonce = bundle.slice(0, nacl.box.nonceLength)
|
||||
const ciphertext = bundle.slice(nacl.box.nonceLength)
|
||||
const plaintext = nacl.box.open.after(ciphertext, nonce, sharedKey)
|
||||
|
||||
if (!plaintext) {
|
||||
return null
|
||||
}
|
||||
|
||||
return plaintext
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { evaluateCompat } from './protocol-compat'
|
||||
import { DESKTOP_PROTOCOL_VERSION, MIN_COMPATIBLE_MOBILE_VERSION } from './protocol-version'
|
||||
import {
|
||||
describeRuntimeCompatBlock,
|
||||
evaluateCompat,
|
||||
evaluateRuntimeCompat
|
||||
} from './protocol-compat'
|
||||
import {
|
||||
DESKTOP_PROTOCOL_VERSION,
|
||||
MIN_COMPATIBLE_MOBILE_VERSION,
|
||||
MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION,
|
||||
MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
|
||||
RUNTIME_PROTOCOL_VERSION
|
||||
} from './protocol-version'
|
||||
|
||||
const MOBILE_V = 1
|
||||
|
||||
@@ -122,3 +132,74 @@ describe('evaluateCompat', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('evaluateRuntimeCompat', () => {
|
||||
it('keeps the current client and current server self-compatible', () => {
|
||||
const verdict = evaluateRuntimeCompat({
|
||||
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
|
||||
serverProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
serverMinCompatibleClientProtocolVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
|
||||
})
|
||||
|
||||
expect(verdict).toMatchObject({ kind: 'ok' })
|
||||
})
|
||||
|
||||
it('allows client and server app versions to skew when protocol ranges overlap', () => {
|
||||
const verdict = evaluateRuntimeCompat({
|
||||
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
|
||||
serverProtocolVersion: RUNTIME_PROTOCOL_VERSION + 3,
|
||||
serverMinCompatibleClientProtocolVersion: RUNTIME_PROTOCOL_VERSION - 1
|
||||
})
|
||||
|
||||
expect(verdict).toMatchObject({ kind: 'ok' })
|
||||
})
|
||||
|
||||
it('blocks when the server requires a newer client protocol', () => {
|
||||
const verdict = evaluateRuntimeCompat({
|
||||
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleServerProtocolVersion: MIN_COMPATIBLE_RUNTIME_SERVER_VERSION,
|
||||
serverProtocolVersion: RUNTIME_PROTOCOL_VERSION + 1,
|
||||
serverMinCompatibleClientProtocolVersion: RUNTIME_PROTOCOL_VERSION + 1
|
||||
})
|
||||
|
||||
expect(verdict).toMatchObject({
|
||||
kind: 'blocked',
|
||||
reason: 'client-too-old',
|
||||
requiredClientProtocolVersion: RUNTIME_PROTOCOL_VERSION + 1
|
||||
})
|
||||
expect(describeRuntimeCompatBlock(verdict)).toContain('client is too old')
|
||||
})
|
||||
|
||||
it('blocks when the server protocol is below the client minimum', () => {
|
||||
const verdict = evaluateRuntimeCompat({
|
||||
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleServerProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
serverProtocolVersion: RUNTIME_PROTOCOL_VERSION - 1,
|
||||
serverMinCompatibleClientProtocolVersion: 0
|
||||
})
|
||||
|
||||
expect(verdict).toMatchObject({
|
||||
kind: 'blocked',
|
||||
reason: 'server-too-old',
|
||||
requiredServerProtocolVersion: RUNTIME_PROTOCOL_VERSION
|
||||
})
|
||||
expect(describeRuntimeCompatBlock(verdict)).toContain('server is too old')
|
||||
})
|
||||
|
||||
it('treats missing server fields as protocol 0', () => {
|
||||
const verdict = evaluateRuntimeCompat({
|
||||
clientProtocolVersion: RUNTIME_PROTOCOL_VERSION,
|
||||
minCompatibleServerProtocolVersion: 1,
|
||||
serverProtocolVersion: undefined,
|
||||
serverMinCompatibleClientProtocolVersion: undefined
|
||||
})
|
||||
|
||||
expect(verdict).toMatchObject({
|
||||
kind: 'blocked',
|
||||
reason: 'server-too-old',
|
||||
serverProtocolVersion: 0
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,67 @@
|
||||
// Why: pure compat evaluator shared between desktop tests and mobile
|
||||
// runtime. Mobile imports a thin wrapper (`mobile/src/transport/protocol-compat.ts`)
|
||||
// that injects the mobile-side constants; desktop tests import this
|
||||
// directly so the function is covered by the root vitest suite.
|
||||
// All four numbers are passed in to keep the function dependency-free.
|
||||
// Why: pure compat evaluators shared between desktop tests, renderer runtime
|
||||
// switching, and the mobile mirror. All version numbers are passed in to keep
|
||||
// the logic dependency-free and easy to duplicate in Expo.
|
||||
|
||||
export type RuntimeCompatVerdict =
|
||||
| {
|
||||
kind: 'ok'
|
||||
clientProtocolVersion: number
|
||||
serverProtocolVersion: number
|
||||
}
|
||||
| {
|
||||
kind: 'blocked'
|
||||
reason: 'client-too-old' | 'server-too-old'
|
||||
clientProtocolVersion: number
|
||||
serverProtocolVersion: number
|
||||
requiredClientProtocolVersion?: number
|
||||
requiredServerProtocolVersion?: number
|
||||
}
|
||||
|
||||
export function evaluateRuntimeCompat(input: {
|
||||
clientProtocolVersion: number
|
||||
minCompatibleServerProtocolVersion: number
|
||||
serverProtocolVersion: number | undefined
|
||||
serverMinCompatibleClientProtocolVersion: number | undefined
|
||||
}): RuntimeCompatVerdict {
|
||||
// Why: absent fields are protocol 0. New clients can give old servers a
|
||||
// clear "update server" error instead of attempting partially-supported RPCs.
|
||||
const serverProtocolVersion = input.serverProtocolVersion ?? 0
|
||||
const requiredClientProtocolVersion = input.serverMinCompatibleClientProtocolVersion ?? 0
|
||||
|
||||
if (input.clientProtocolVersion < requiredClientProtocolVersion) {
|
||||
return {
|
||||
kind: 'blocked',
|
||||
reason: 'client-too-old',
|
||||
clientProtocolVersion: input.clientProtocolVersion,
|
||||
serverProtocolVersion,
|
||||
requiredClientProtocolVersion
|
||||
}
|
||||
}
|
||||
if (serverProtocolVersion < input.minCompatibleServerProtocolVersion) {
|
||||
return {
|
||||
kind: 'blocked',
|
||||
reason: 'server-too-old',
|
||||
clientProtocolVersion: input.clientProtocolVersion,
|
||||
serverProtocolVersion,
|
||||
requiredServerProtocolVersion: input.minCompatibleServerProtocolVersion
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: 'ok',
|
||||
clientProtocolVersion: input.clientProtocolVersion,
|
||||
serverProtocolVersion
|
||||
}
|
||||
}
|
||||
|
||||
export function describeRuntimeCompatBlock(verdict: RuntimeCompatVerdict): string {
|
||||
if (verdict.kind === 'ok') {
|
||||
return 'Runtime client and server are compatible.'
|
||||
}
|
||||
if (verdict.reason === 'client-too-old') {
|
||||
return `This Orca client is too old for the selected server. Update Orca on this machine. Client protocol ${verdict.clientProtocolVersion}, server requires client protocol ${verdict.requiredClientProtocolVersion}.`
|
||||
}
|
||||
return `The selected Orca server is too old for this client. Update Orca on the server. Server protocol ${verdict.serverProtocolVersion}, client requires server protocol ${verdict.requiredServerProtocolVersion}.`
|
||||
}
|
||||
|
||||
export type CompatVerdict =
|
||||
| { kind: 'ok' }
|
||||
|
||||
@@ -1,23 +1,36 @@
|
||||
// Why: declares the desktop's mobile-pairing protocol version so mobile
|
||||
// builds can detect declared-incompatible combos and hard-block at pair
|
||||
// time. Today's values are wide-open (mobile=any, desktop=any), so
|
||||
// nothing actually blocks; the wire format is ready for the day we
|
||||
// ship a genuinely-breaking change.
|
||||
// Why: declares the Orca runtime RPC compatibility contract. Desktop,
|
||||
// headless server, CLI, and mobile builds may drift in app version, but
|
||||
// they must agree on this protocol range before runtime RPCs are allowed.
|
||||
//
|
||||
// Bump DESKTOP_PROTOCOL_VERSION when:
|
||||
// - You remove an RPC method or required parameter that mobile uses.
|
||||
// Bump RUNTIME_PROTOCOL_VERSION when:
|
||||
// - You remove an RPC method or required parameter that clients use.
|
||||
// - You change the meaning (units, nullability) of an existing field
|
||||
// mobile reads.
|
||||
// - You change encryption, framing, or the auth handshake.
|
||||
// clients read.
|
||||
// - You change encrypted framing, terminal stream framing, or auth.
|
||||
// Do NOT bump for:
|
||||
// - Adding new RPC methods.
|
||||
// - Adding new optional fields on existing methods.
|
||||
// - Adding new event types in `terminal.subscribe`.
|
||||
// - Adding new ignorable event types.
|
||||
//
|
||||
// Bump MIN_COMPATIBLE_MOBILE_VERSION when desktop ships a change that
|
||||
// requires a minimum mobile version to function safely. This is the
|
||||
// "kill switch": desktop can refuse old mobile builds without needing
|
||||
// a desktop release of mobile.
|
||||
// Bump MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION when a runtime server must
|
||||
// refuse older clients. Bump MIN_COMPATIBLE_RUNTIME_SERVER_VERSION when
|
||||
// this client build requires a newer server. Exact app-version equality is
|
||||
// never required; these numbers define the supported compatibility window.
|
||||
|
||||
export const DESKTOP_PROTOCOL_VERSION = 2
|
||||
export const MIN_COMPATIBLE_MOBILE_VERSION = 2
|
||||
export const RUNTIME_PROTOCOL_VERSION = 2
|
||||
export const MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION = 2
|
||||
export const MIN_COMPATIBLE_RUNTIME_SERVER_VERSION = 2
|
||||
|
||||
export const RUNTIME_CAPABILITIES = [
|
||||
'runtime.status.compat.v1',
|
||||
'runtime.environments.v1',
|
||||
'terminal.binary-stream.v1',
|
||||
'terminal.multiplex.v1'
|
||||
] as const
|
||||
|
||||
export type RuntimeCapability = (typeof RUNTIME_CAPABILITIES)[number] | (string & {})
|
||||
|
||||
// COMPAT(mobileProtocolAliases): added 2026-05-15 for mobile builds that
|
||||
// still read desktop/mobile names; remove once mobile reads runtime names.
|
||||
export const DESKTOP_PROTOCOL_VERSION = RUNTIME_PROTOCOL_VERSION
|
||||
export const MIN_COMPATIBLE_MOBILE_VERSION = MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { AddressInfo } from 'net'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
import { encodePairingOffer, parsePairingCode, type PairingOffer } from './pairing'
|
||||
import {
|
||||
decrypt,
|
||||
decryptBytes,
|
||||
deriveSharedKey,
|
||||
encrypt,
|
||||
generateKeyPair,
|
||||
publicKeyFromBase64,
|
||||
publicKeyToBase64
|
||||
} from './e2ee-crypto'
|
||||
import { subscribeRemoteRuntimeRequest } from './remote-runtime-client'
|
||||
|
||||
const servers: WebSocketServer[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
for (const client of server.clients) {
|
||||
client.close()
|
||||
}
|
||||
server.close(() => resolve())
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
describe('subscribeRemoteRuntimeRequest', () => {
|
||||
it('sends encrypted binary frames on an established subscription socket', async () => {
|
||||
const server = await createSubscriptionServer()
|
||||
const onResponse = vi.fn()
|
||||
const onError = vi.fn()
|
||||
|
||||
const subscription = await subscribeRemoteRuntimeRequest(
|
||||
server.pairing,
|
||||
'terminal.subscribe',
|
||||
{ terminal: 't1' },
|
||||
1000,
|
||||
{
|
||||
onResponse,
|
||||
onError
|
||||
}
|
||||
)
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(onResponse).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ok: true, result: { type: 'subscribed' } })
|
||||
)
|
||||
)
|
||||
const bytes = new Uint8Array([1, 2, 3])
|
||||
expect(subscription.sendBinary(bytes)).toBe(true)
|
||||
await expect(server.nextBinary).resolves.toEqual(bytes)
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
subscription.close()
|
||||
})
|
||||
})
|
||||
|
||||
async function createSubscriptionServer(): Promise<{
|
||||
pairing: PairingOffer
|
||||
nextBinary: Promise<Uint8Array>
|
||||
}> {
|
||||
const serverKeyPair = generateKeyPair()
|
||||
let resolveBinary: (bytes: Uint8Array) => void = () => {}
|
||||
const nextBinary = new Promise<Uint8Array>((resolve) => {
|
||||
resolveBinary = resolve
|
||||
})
|
||||
const wss = new WebSocketServer({ port: 0 })
|
||||
servers.push(wss)
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
let sharedKey: Uint8Array | null = null
|
||||
let authenticated = false
|
||||
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary) {
|
||||
if (!sharedKey) {
|
||||
return
|
||||
}
|
||||
const plaintext = decryptBytes(new Uint8Array(data as Buffer), sharedKey)
|
||||
if (plaintext) {
|
||||
resolveBinary(plaintext)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const frame = data.toString()
|
||||
if (!sharedKey) {
|
||||
const hello = JSON.parse(frame) as { publicKeyB64: string }
|
||||
sharedKey = deriveSharedKey(
|
||||
serverKeyPair.secretKey,
|
||||
publicKeyFromBase64(hello.publicKeyB64)
|
||||
)
|
||||
ws.send(JSON.stringify({ type: 'e2ee_ready' }))
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(frame, sharedKey)
|
||||
if (!plaintext) {
|
||||
return
|
||||
}
|
||||
if (!authenticated) {
|
||||
authenticated = true
|
||||
sendEncrypted(ws, sharedKey, { type: 'e2ee_authenticated' })
|
||||
return
|
||||
}
|
||||
|
||||
const request = JSON.parse(plaintext) as { id: string }
|
||||
sendEncrypted(ws, sharedKey, {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
streaming: true,
|
||||
result: { type: 'subscribed' },
|
||||
_meta: { runtimeId: 'runtime-test' }
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve) => wss.once('listening', resolve))
|
||||
const address = wss.address() as AddressInfo
|
||||
const pairing = parsePairingCode(
|
||||
encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint: `ws://127.0.0.1:${address.port}`,
|
||||
deviceToken: 'device-token',
|
||||
publicKeyB64: publicKeyToBase64(serverKeyPair.publicKey)
|
||||
})
|
||||
)
|
||||
if (!pairing) {
|
||||
throw new Error('Failed to create test pairing')
|
||||
}
|
||||
return { pairing, nextBinary }
|
||||
}
|
||||
|
||||
function sendEncrypted(ws: WebSocket, sharedKey: Uint8Array, message: unknown): void {
|
||||
ws.send(encrypt(JSON.stringify(message), sharedKey))
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
/* oxlint-disable max-lines -- Why: one-shot and streaming remote clients share the
|
||||
* same E2EE handshake and response validation state; keep them together until
|
||||
* the terminal transport is fully migrated and a stable shared connection
|
||||
* abstraction emerges. */
|
||||
import { randomUUID } from 'crypto'
|
||||
import WebSocket from 'ws'
|
||||
import type { PairingOffer } from './pairing'
|
||||
import {
|
||||
decrypt,
|
||||
decryptBytes,
|
||||
deriveSharedKey,
|
||||
encrypt,
|
||||
encryptBytes,
|
||||
generateKeyPair,
|
||||
publicKeyFromBase64,
|
||||
publicKeyToBase64
|
||||
} from './e2ee-crypto'
|
||||
import { RuntimeRpcEnvelopeSchema, type RuntimeRpcResponse } from './runtime-rpc-envelope'
|
||||
|
||||
type HandshakeState = 'awaiting_ready' | 'awaiting_authenticated' | 'ready'
|
||||
|
||||
export class RemoteRuntimeClientError extends Error {
|
||||
readonly code: string
|
||||
|
||||
constructor(code: string, message: string) {
|
||||
super(message)
|
||||
this.name = 'RemoteRuntimeClientError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export type RemoteRuntimeSubscription = {
|
||||
requestId: string
|
||||
close: () => void
|
||||
sendBinary: (bytes: Uint8Array<ArrayBufferLike>) => boolean
|
||||
}
|
||||
|
||||
export type RemoteRuntimeSubscriptionCallbacks<TResult = unknown> = {
|
||||
onResponse: (response: RuntimeRpcResponse<TResult>) => void
|
||||
onBinary?: (bytes: Uint8Array<ArrayBufferLike>) => void
|
||||
onError: (error: RemoteRuntimeClientError) => void
|
||||
onClose?: () => void
|
||||
}
|
||||
|
||||
export async function sendRemoteRuntimeRequest<TResult>(
|
||||
pairing: PairingOffer,
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number
|
||||
): Promise<RuntimeRpcResponse<TResult>> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const requestId = randomUUID()
|
||||
const keyPair = generateKeyPair()
|
||||
const serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64)
|
||||
const sharedKey = deriveSharedKey(keyPair.secretKey, serverPublicKey)
|
||||
let state: HandshakeState = 'awaiting_ready'
|
||||
let settled = false
|
||||
let ws: WebSocket | null = null
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'runtime_timeout',
|
||||
'Timed out waiting for the remote Orca runtime to respond.'
|
||||
)
|
||||
})
|
||||
}, timeoutMs)
|
||||
|
||||
const finish = (
|
||||
result: { ok: true; response: RuntimeRpcResponse<TResult> } | { ok: false; error: Error }
|
||||
): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
try {
|
||||
ws?.close()
|
||||
} catch {
|
||||
// ignore best-effort close
|
||||
}
|
||||
if (result.ok === false) {
|
||||
reject(result.error)
|
||||
} else {
|
||||
resolve(result.response)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
ws = new WebSocket(pairing.endpoint)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_argument',
|
||||
`Invalid remote endpoint: ${message}`
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
ws.once('open', () => {
|
||||
ws?.send(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(keyPair.publicKey)
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
ws.once('error', () => {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'remote_runtime_unavailable',
|
||||
'Could not connect to the remote Orca runtime.'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
ws.on('close', () => {
|
||||
if (!settled) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'remote_runtime_unavailable',
|
||||
'Remote Orca runtime closed the connection.'
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
if (isBinary) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an unexpected binary frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const frame = data.toString()
|
||||
if (state === 'awaiting_ready') {
|
||||
handleReadyFrame(frame)
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(frame, sharedKey)
|
||||
if (plaintext === null) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an undecryptable frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (state === 'awaiting_authenticated') {
|
||||
handleAuthenticatedFrame(plaintext)
|
||||
return
|
||||
}
|
||||
|
||||
handleRpcFrame(plaintext)
|
||||
})
|
||||
|
||||
function handleReadyFrame(frame: string): void {
|
||||
let ready: unknown
|
||||
try {
|
||||
ready = JSON.parse(frame)
|
||||
} catch {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid E2EE handshake frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
if (
|
||||
typeof ready !== 'object' ||
|
||||
ready === null ||
|
||||
(ready as { type?: unknown }).type !== 'e2ee_ready'
|
||||
) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an unexpected E2EE handshake frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
state = 'awaiting_authenticated'
|
||||
ws?.send(
|
||||
encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: pairing.deviceToken }), sharedKey)
|
||||
)
|
||||
}
|
||||
|
||||
function handleAuthenticatedFrame(plaintext: string): void {
|
||||
let authenticated: unknown
|
||||
try {
|
||||
authenticated = JSON.parse(plaintext)
|
||||
} catch {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid E2EE auth frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
const type = (authenticated as { type?: unknown }).type
|
||||
if (type !== 'e2ee_authenticated') {
|
||||
const code =
|
||||
typeof authenticated === 'object' &&
|
||||
authenticated !== null &&
|
||||
(authenticated as { error?: { code?: unknown } }).error?.code === 'unauthorized'
|
||||
? 'unauthorized'
|
||||
: 'invalid_runtime_response'
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
code,
|
||||
'Remote Orca runtime rejected the pairing token.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
state = 'ready'
|
||||
ws?.send(
|
||||
encrypt(
|
||||
JSON.stringify({
|
||||
id: requestId,
|
||||
deviceToken: pairing.deviceToken,
|
||||
method,
|
||||
params
|
||||
}),
|
||||
sharedKey
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function handleRpcFrame(plaintext: string): void {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(plaintext)
|
||||
} catch {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid response frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
const parsed = RuntimeRpcEnvelopeSchema.safeParse(raw)
|
||||
if (!parsed.success || '_keepalive' in parsed.data) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid response frame.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
const response = parsed.data as RuntimeRpcResponse<TResult>
|
||||
if (response.id !== requestId) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned a mismatched response id.'
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
finish({ ok: true, response })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function subscribeRemoteRuntimeRequest<TResult>(
|
||||
pairing: PairingOffer,
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number,
|
||||
callbacks: RemoteRuntimeSubscriptionCallbacks<TResult>
|
||||
): Promise<RemoteRuntimeSubscription> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const requestId = randomUUID()
|
||||
const keyPair = generateKeyPair()
|
||||
const serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64)
|
||||
const sharedKey = deriveSharedKey(keyPair.secretKey, serverPublicKey)
|
||||
let state: HandshakeState = 'awaiting_ready'
|
||||
let settled = false
|
||||
let ws: WebSocket | null = null
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'runtime_timeout',
|
||||
'Timed out waiting for the remote Orca runtime subscription to start.'
|
||||
)
|
||||
)
|
||||
}, timeoutMs)
|
||||
|
||||
const close = (): void => {
|
||||
try {
|
||||
ws?.close()
|
||||
} catch {
|
||||
// ignore best-effort close
|
||||
}
|
||||
}
|
||||
|
||||
const sendBinary = (bytes: Uint8Array<ArrayBufferLike>): boolean => {
|
||||
if (state !== 'ready' || !ws || ws.readyState !== WebSocket.OPEN) {
|
||||
return false
|
||||
}
|
||||
ws.send(Buffer.from(encryptBytes(bytes, sharedKey)), { binary: true })
|
||||
return true
|
||||
}
|
||||
|
||||
const succeed = (): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
resolve({ requestId, close, sendBinary })
|
||||
}
|
||||
|
||||
const fail = (error: RemoteRuntimeClientError): void => {
|
||||
if (!settled) {
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
close()
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
callbacks.onError(error)
|
||||
}
|
||||
|
||||
try {
|
||||
ws = new WebSocket(pairing.endpoint)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
fail(new RemoteRuntimeClientError('invalid_argument', `Invalid remote endpoint: ${message}`))
|
||||
return
|
||||
}
|
||||
|
||||
ws.once('open', () => {
|
||||
ws?.send(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(keyPair.publicKey)
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
ws.once('error', () => {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'remote_runtime_unavailable',
|
||||
'Could not connect to the remote Orca runtime.'
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
ws.on('close', () => {
|
||||
clearTimeout(timeout)
|
||||
if (!settled) {
|
||||
reject(
|
||||
new RemoteRuntimeClientError(
|
||||
'remote_runtime_unavailable',
|
||||
'Remote Orca runtime closed the connection.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
callbacks.onClose?.()
|
||||
})
|
||||
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary) {
|
||||
handleBinaryFrame(new Uint8Array(data as Buffer))
|
||||
return
|
||||
}
|
||||
|
||||
const frame = data.toString()
|
||||
if (state === 'awaiting_ready') {
|
||||
handleReadyFrame(frame)
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(frame, sharedKey)
|
||||
if (plaintext === null) {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an undecryptable frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (state === 'awaiting_authenticated') {
|
||||
handleAuthenticatedFrame(plaintext)
|
||||
return
|
||||
}
|
||||
|
||||
handleRpcFrame(plaintext)
|
||||
})
|
||||
|
||||
function handleReadyFrame(frame: string): void {
|
||||
let ready: unknown
|
||||
try {
|
||||
ready = JSON.parse(frame)
|
||||
} catch {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid E2EE handshake frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
if (
|
||||
typeof ready !== 'object' ||
|
||||
ready === null ||
|
||||
(ready as { type?: unknown }).type !== 'e2ee_ready'
|
||||
) {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an unexpected E2EE handshake frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
state = 'awaiting_authenticated'
|
||||
ws?.send(
|
||||
encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: pairing.deviceToken }), sharedKey)
|
||||
)
|
||||
}
|
||||
|
||||
function handleAuthenticatedFrame(plaintext: string): void {
|
||||
let authenticated: unknown
|
||||
try {
|
||||
authenticated = JSON.parse(plaintext)
|
||||
} catch {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid E2EE auth frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
const type = (authenticated as { type?: unknown }).type
|
||||
if (type !== 'e2ee_authenticated') {
|
||||
const code =
|
||||
typeof authenticated === 'object' &&
|
||||
authenticated !== null &&
|
||||
(authenticated as { error?: { code?: unknown } }).error?.code === 'unauthorized'
|
||||
? 'unauthorized'
|
||||
: 'invalid_runtime_response'
|
||||
fail(new RemoteRuntimeClientError(code, 'Remote Orca runtime rejected the pairing token.'))
|
||||
return
|
||||
}
|
||||
state = 'ready'
|
||||
ws?.send(
|
||||
encrypt(
|
||||
JSON.stringify({
|
||||
id: requestId,
|
||||
deviceToken: pairing.deviceToken,
|
||||
method,
|
||||
params
|
||||
}),
|
||||
sharedKey
|
||||
)
|
||||
)
|
||||
succeed()
|
||||
}
|
||||
|
||||
function handleRpcFrame(plaintext: string): void {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(plaintext)
|
||||
} catch {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an invalid response frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
const parsed = RuntimeRpcEnvelopeSchema.safeParse(raw)
|
||||
if (!parsed.success || '_keepalive' in parsed.data) {
|
||||
return
|
||||
}
|
||||
const response = parsed.data as RuntimeRpcResponse<TResult>
|
||||
if (response.id !== requestId) {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned a mismatched response id.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
callbacks.onResponse(response)
|
||||
}
|
||||
|
||||
function handleBinaryFrame(frame: Uint8Array<ArrayBufferLike>): void {
|
||||
if (state !== 'ready') {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned binary data before authentication.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
const plaintext = decryptBytes(frame, sharedKey)
|
||||
if (plaintext === null) {
|
||||
fail(
|
||||
new RemoteRuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
'Remote Orca runtime returned an undecryptable binary frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
callbacks.onBinary?.(plaintext)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import WebSocket from 'ws'
|
||||
import type { PairingOffer } from './pairing'
|
||||
import { decrypt, encrypt } from './e2ee-crypto'
|
||||
import type { RemoteRuntimeWebSocketCallbacks } from './remote-runtime-request-websocket'
|
||||
|
||||
const opens: FakeOpenedSocket[] = []
|
||||
|
||||
vi.mock('./remote-runtime-request-websocket', () => ({
|
||||
openRemoteRuntimeWebSocket: (
|
||||
_pairing: PairingOffer,
|
||||
callbacks: RemoteRuntimeWebSocketCallbacks
|
||||
) => {
|
||||
const socket = createFakeOpenedSocket(callbacks)
|
||||
opens.push(socket)
|
||||
return { ok: true, socket: { ws: socket.ws, sharedKey: socket.sharedKey } }
|
||||
}
|
||||
}))
|
||||
|
||||
type FakeOpenedSocket = {
|
||||
ws: WebSocket
|
||||
sharedKey: Uint8Array
|
||||
sent: string[]
|
||||
callbacks: RemoteRuntimeWebSocketCallbacks
|
||||
}
|
||||
|
||||
function createFakeOpenedSocket(callbacks: RemoteRuntimeWebSocketCallbacks): FakeOpenedSocket {
|
||||
const sent: string[] = []
|
||||
const ws = {
|
||||
readyState: WebSocket.OPEN,
|
||||
send: (frame: string) => {
|
||||
sent.push(frame)
|
||||
},
|
||||
close: vi.fn()
|
||||
} as unknown as WebSocket
|
||||
return {
|
||||
ws,
|
||||
sharedKey: new Uint8Array(32).fill(opens.length + 1),
|
||||
sent,
|
||||
callbacks
|
||||
}
|
||||
}
|
||||
|
||||
function authenticate(socket: FakeOpenedSocket): void {
|
||||
socket.callbacks.onTextFrame(socket.ws, JSON.stringify({ type: 'e2ee_ready' }))
|
||||
socket.callbacks.onTextFrame(
|
||||
socket.ws,
|
||||
encrypt(JSON.stringify({ type: 'e2ee_authenticated' }), socket.sharedKey)
|
||||
)
|
||||
}
|
||||
|
||||
function latestRequestId(socket: FakeOpenedSocket): string {
|
||||
const plaintext = decrypt(socket.sent.at(-1) ?? '', socket.sharedKey)
|
||||
if (plaintext === null) {
|
||||
throw new Error('missing encrypted request')
|
||||
}
|
||||
return (JSON.parse(plaintext) as { id: string }).id
|
||||
}
|
||||
|
||||
describe('RemoteRuntimeRequestConnection stale socket callbacks', () => {
|
||||
beforeEach(() => {
|
||||
opens.splice(0)
|
||||
})
|
||||
|
||||
it('ignores stale socket errors and text frames after a replacement socket opens', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const { RemoteRuntimeRequestConnection } =
|
||||
await import('./remote-runtime-request-connection.js')
|
||||
const connection = new RemoteRuntimeRequestConnection({
|
||||
v: 2,
|
||||
endpoint: 'ws://127.0.0.1:6768',
|
||||
deviceToken: 'device-token',
|
||||
publicKeyB64: Buffer.from(new Uint8Array(32).fill(9)).toString('base64')
|
||||
})
|
||||
|
||||
const first = connection.request('slow.method', undefined, 10)
|
||||
authenticate(opens[0]!)
|
||||
const firstRejected = expect(first).rejects.toThrow('Timed out')
|
||||
await vi.advanceTimersByTimeAsync(11)
|
||||
await firstRejected
|
||||
|
||||
const second = connection.request('status.get', undefined, 1000)
|
||||
authenticate(opens[1]!)
|
||||
await vi.waitFor(() => expect(opens[1]!.sent.length).toBeGreaterThan(1))
|
||||
|
||||
opens[0]!.callbacks.onError(opens[0]!.ws, new Error('stale socket error') as never)
|
||||
opens[0]!.callbacks.onTextFrame(
|
||||
opens[0]!.ws,
|
||||
encrypt(JSON.stringify({ id: 'stale', ok: true, result: {} }), opens[0]!.sharedKey)
|
||||
)
|
||||
|
||||
const requestId = latestRequestId(opens[1]!)
|
||||
opens[1]!.callbacks.onTextFrame(
|
||||
opens[1]!.ws,
|
||||
encrypt(
|
||||
JSON.stringify({
|
||||
id: requestId,
|
||||
ok: true,
|
||||
result: { state: 'ok' },
|
||||
_meta: { runtimeId: 'runtime-2' }
|
||||
}),
|
||||
opens[1]!.sharedKey
|
||||
)
|
||||
)
|
||||
|
||||
await expect(second).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { state: 'ok' }
|
||||
})
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { AddressInfo } from 'net'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
import { encodePairingOffer, parsePairingCode, type PairingOffer } from './pairing'
|
||||
import {
|
||||
decrypt,
|
||||
deriveSharedKey,
|
||||
encrypt,
|
||||
generateKeyPair,
|
||||
publicKeyFromBase64,
|
||||
publicKeyToBase64
|
||||
} from './e2ee-crypto'
|
||||
import { RemoteRuntimeRequestConnection } from './remote-runtime-request-connection'
|
||||
|
||||
type TestServer = {
|
||||
wss: WebSocketServer
|
||||
pairing: PairingOffer
|
||||
requests: unknown[]
|
||||
connectionCount: () => number
|
||||
}
|
||||
|
||||
const servers: WebSocketServer[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
servers.splice(0).map(
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
for (const client of server.clients) {
|
||||
client.close()
|
||||
}
|
||||
server.close(() => resolve())
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
describe('RemoteRuntimeRequestConnection', () => {
|
||||
it('reuses one encrypted WebSocket for multiple one-shot RPCs', async () => {
|
||||
const server = await createServer()
|
||||
const connection = new RemoteRuntimeRequestConnection(server.pairing)
|
||||
|
||||
const first = await connection.request('status.get', undefined, 1000)
|
||||
const second = await connection.request('terminal.send', { terminal: 't1', text: 'ab' }, 1000)
|
||||
|
||||
expect(first).toMatchObject({
|
||||
ok: true,
|
||||
result: { method: 'status.get' },
|
||||
_meta: { runtimeId: 'runtime-test' }
|
||||
})
|
||||
expect(second).toMatchObject({
|
||||
ok: true,
|
||||
result: { method: 'terminal.send' },
|
||||
_meta: { runtimeId: 'runtime-test' }
|
||||
})
|
||||
expect(server.connectionCount()).toBe(1)
|
||||
expect(server.requests).toMatchObject([
|
||||
{ method: 'status.get' },
|
||||
{ method: 'terminal.send', params: { terminal: 't1', text: 'ab' } }
|
||||
])
|
||||
|
||||
connection.close()
|
||||
})
|
||||
})
|
||||
|
||||
async function createServer(): Promise<TestServer> {
|
||||
const serverKeyPair = generateKeyPair()
|
||||
const requests: unknown[] = []
|
||||
let connectionCount = 0
|
||||
const wss = new WebSocketServer({ port: 0 })
|
||||
servers.push(wss)
|
||||
|
||||
wss.on('connection', (ws) => {
|
||||
connectionCount += 1
|
||||
let sharedKey: Uint8Array | null = null
|
||||
let authenticated = false
|
||||
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary) {
|
||||
return
|
||||
}
|
||||
const frame = data.toString()
|
||||
if (!sharedKey) {
|
||||
const hello = JSON.parse(frame) as { type: string; publicKeyB64: string }
|
||||
const clientPublicKey = publicKeyFromBase64(hello.publicKeyB64)
|
||||
sharedKey = deriveSharedKey(serverKeyPair.secretKey, clientPublicKey)
|
||||
ws.send(JSON.stringify({ type: 'e2ee_ready' }))
|
||||
return
|
||||
}
|
||||
|
||||
const plaintext = decrypt(frame, sharedKey)
|
||||
if (plaintext === null) {
|
||||
return
|
||||
}
|
||||
if (!authenticated) {
|
||||
const auth = JSON.parse(plaintext) as { type: string; deviceToken: string }
|
||||
expect(auth).toEqual({ type: 'e2ee_auth', deviceToken: 'device-token' })
|
||||
authenticated = true
|
||||
sendEncrypted(ws, sharedKey, { type: 'e2ee_authenticated' })
|
||||
return
|
||||
}
|
||||
|
||||
const request = JSON.parse(plaintext) as {
|
||||
id: string
|
||||
method: string
|
||||
params?: unknown
|
||||
}
|
||||
requests.push(request)
|
||||
sendEncrypted(ws, sharedKey, {
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: { method: request.method },
|
||||
_meta: { runtimeId: 'runtime-test' }
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve) => wss.once('listening', resolve))
|
||||
const address = wss.address() as AddressInfo
|
||||
const pairing = parsePairingCode(
|
||||
encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint: `ws://127.0.0.1:${address.port}`,
|
||||
deviceToken: 'device-token',
|
||||
publicKeyB64: publicKeyToBase64(serverKeyPair.publicKey)
|
||||
})
|
||||
)
|
||||
if (!pairing) {
|
||||
throw new Error('Failed to create test pairing')
|
||||
}
|
||||
|
||||
return {
|
||||
wss,
|
||||
pairing,
|
||||
requests,
|
||||
connectionCount: () => connectionCount
|
||||
}
|
||||
}
|
||||
|
||||
function sendEncrypted(ws: WebSocket, sharedKey: Uint8Array, message: unknown): void {
|
||||
ws.send(encrypt(JSON.stringify(message), sharedKey))
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import WebSocket from 'ws'
|
||||
import type { PairingOffer } from './pairing'
|
||||
import { decrypt, encrypt } from './e2ee-crypto'
|
||||
import type { RuntimeRpcResponse } from './runtime-rpc-envelope'
|
||||
import { RemoteRuntimeClientError } from './remote-runtime-client'
|
||||
import {
|
||||
invalidRemoteRuntimeResponseError,
|
||||
parseAuthenticatedFrame,
|
||||
parseReadyFrame,
|
||||
parseRemoteRuntimeRpcFrame,
|
||||
remoteRuntimeTimeoutError,
|
||||
remoteRuntimeUnavailableError
|
||||
} from './remote-runtime-request-frames'
|
||||
import { openRemoteRuntimeWebSocket } from './remote-runtime-request-websocket'
|
||||
|
||||
type ConnectionState = 'closed' | 'awaiting_ready' | 'awaiting_authenticated' | 'ready'
|
||||
|
||||
type PendingRequest<TResult> = {
|
||||
resolve: (response: RuntimeRpcResponse<TResult>) => void
|
||||
reject: (error: Error) => void
|
||||
timeout: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
type ReadyWaiter = {
|
||||
resolve: () => void
|
||||
reject: (error: Error) => void
|
||||
}
|
||||
|
||||
const IDLE_CLOSE_MS = 60_000
|
||||
|
||||
export class RemoteRuntimeRequestConnection {
|
||||
private readonly pairing: PairingOffer
|
||||
private state: ConnectionState = 'closed'
|
||||
private ws: WebSocket | null = null
|
||||
private sharedKey: Uint8Array | null = null
|
||||
private readonly pendingRequests = new Map<string, PendingRequest<unknown>>()
|
||||
private readonly readyWaiters: ReadyWaiter[] = []
|
||||
private idleCloseTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
constructor(pairing: PairingOffer) {
|
||||
this.pairing = pairing
|
||||
}
|
||||
|
||||
request<TResult>(
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs: number
|
||||
): Promise<RuntimeRpcResponse<TResult>> {
|
||||
this.clearIdleCloseTimer()
|
||||
const requestId = randomUUID()
|
||||
return new Promise<RuntimeRpcResponse<TResult>>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
const pending = this.pendingRequests.get(requestId)
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
this.pendingRequests.delete(requestId)
|
||||
const error = remoteRuntimeTimeoutError()
|
||||
pending.reject(error)
|
||||
this.close(error)
|
||||
}, timeoutMs)
|
||||
this.pendingRequests.set(requestId, {
|
||||
resolve: resolve as (response: RuntimeRpcResponse<unknown>) => void,
|
||||
reject,
|
||||
timeout
|
||||
})
|
||||
|
||||
void this.ensureReady().then(
|
||||
() => this.sendRequest(requestId, method, params),
|
||||
(error) => this.rejectPendingRequest(requestId, toClientError(error))
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
close(error?: Error): void {
|
||||
const ws = this.ws
|
||||
this.ws = null
|
||||
this.sharedKey = null
|
||||
this.state = 'closed'
|
||||
this.clearIdleCloseTimer()
|
||||
|
||||
const closeError = error ?? remoteRuntimeUnavailableError()
|
||||
this.rejectReadyWaiters(closeError)
|
||||
for (const [requestId, pending] of this.pendingRequests) {
|
||||
clearTimeout(pending.timeout)
|
||||
this.pendingRequests.delete(requestId)
|
||||
pending.reject(closeError)
|
||||
}
|
||||
|
||||
try {
|
||||
ws?.close()
|
||||
} catch {
|
||||
// Best-effort shutdown for a cached remote control connection.
|
||||
}
|
||||
}
|
||||
|
||||
private ensureReady(): Promise<void> {
|
||||
const ws = this.ws
|
||||
if (this.state === 'ready' && ws?.readyState === WebSocket.OPEN && this.sharedKey) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
const promise = new Promise<void>((resolve, reject) => {
|
||||
this.readyWaiters.push({ resolve, reject })
|
||||
})
|
||||
|
||||
if (!ws || ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) {
|
||||
this.open()
|
||||
}
|
||||
|
||||
return promise
|
||||
}
|
||||
|
||||
private open(): void {
|
||||
const opened = openRemoteRuntimeWebSocket(this.pairing, {
|
||||
onClose: (ws) => {
|
||||
if (this.ws === ws) {
|
||||
this.close()
|
||||
}
|
||||
},
|
||||
onError: (ws, error) => {
|
||||
if (this.ws === ws) {
|
||||
this.close(error)
|
||||
}
|
||||
},
|
||||
onTextFrame: (ws, frame) => {
|
||||
if (this.ws === ws) {
|
||||
this.handleTextFrame(frame)
|
||||
}
|
||||
}
|
||||
})
|
||||
if (!opened.ok) {
|
||||
this.close(opened.error)
|
||||
return
|
||||
}
|
||||
this.ws = opened.socket.ws
|
||||
this.sharedKey = opened.socket.sharedKey
|
||||
this.state = 'awaiting_ready'
|
||||
}
|
||||
|
||||
private handleTextFrame(frame: string): void {
|
||||
if (this.state === 'awaiting_ready') {
|
||||
this.handleReadyFrame(frame)
|
||||
return
|
||||
}
|
||||
|
||||
const sharedKey = this.sharedKey
|
||||
if (!sharedKey) {
|
||||
return
|
||||
}
|
||||
const plaintext = decrypt(frame, sharedKey)
|
||||
if (plaintext === null) {
|
||||
this.close(
|
||||
invalidRemoteRuntimeResponseError('Remote Orca runtime returned an undecryptable frame.')
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (this.state === 'awaiting_authenticated') {
|
||||
this.handleAuthenticatedFrame(plaintext)
|
||||
return
|
||||
}
|
||||
|
||||
this.handleRpcFrame(plaintext)
|
||||
}
|
||||
|
||||
private handleReadyFrame(frame: string): void {
|
||||
const error = parseReadyFrame(frame)
|
||||
if (error) {
|
||||
this.close(error)
|
||||
return
|
||||
}
|
||||
this.state = 'awaiting_authenticated'
|
||||
const sharedKey = this.sharedKey
|
||||
if (!sharedKey) {
|
||||
return
|
||||
}
|
||||
this.ws?.send(
|
||||
encrypt(
|
||||
JSON.stringify({ type: 'e2ee_auth', deviceToken: this.pairing.deviceToken }),
|
||||
sharedKey
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private handleAuthenticatedFrame(plaintext: string): void {
|
||||
const error = parseAuthenticatedFrame(plaintext)
|
||||
if (error) {
|
||||
this.close(error)
|
||||
return
|
||||
}
|
||||
this.state = 'ready'
|
||||
this.resolveReadyWaiters()
|
||||
this.scheduleIdleCloseIfUnused()
|
||||
}
|
||||
|
||||
private handleRpcFrame(plaintext: string): void {
|
||||
const parsed = parseRemoteRuntimeRpcFrame(plaintext)
|
||||
if (parsed.type === 'keepalive') {
|
||||
return
|
||||
}
|
||||
if (parsed.type === 'error') {
|
||||
this.close(parsed.error)
|
||||
return
|
||||
}
|
||||
|
||||
const response = parsed.response
|
||||
const pending = this.pendingRequests.get(response.id)
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
this.pendingRequests.delete(response.id)
|
||||
clearTimeout(pending.timeout)
|
||||
pending.resolve(response)
|
||||
this.scheduleIdleCloseIfUnused()
|
||||
}
|
||||
|
||||
private sendRequest(requestId: string, method: string, params: unknown): void {
|
||||
const pending = this.pendingRequests.get(requestId)
|
||||
const ws = this.ws
|
||||
const sharedKey = this.sharedKey
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
if (this.state !== 'ready' || !ws || ws.readyState !== WebSocket.OPEN || !sharedKey) {
|
||||
this.rejectPendingRequest(requestId, remoteRuntimeUnavailableError())
|
||||
return
|
||||
}
|
||||
ws.send(
|
||||
encrypt(
|
||||
JSON.stringify({
|
||||
id: requestId,
|
||||
deviceToken: this.pairing.deviceToken,
|
||||
method,
|
||||
params
|
||||
}),
|
||||
sharedKey
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private rejectPendingRequest(requestId: string, error: Error): void {
|
||||
const pending = this.pendingRequests.get(requestId)
|
||||
if (!pending) {
|
||||
return
|
||||
}
|
||||
this.pendingRequests.delete(requestId)
|
||||
clearTimeout(pending.timeout)
|
||||
pending.reject(error)
|
||||
this.scheduleIdleCloseIfUnused()
|
||||
}
|
||||
|
||||
private resolveReadyWaiters(): void {
|
||||
const waiters = this.readyWaiters.splice(0)
|
||||
for (const waiter of waiters) {
|
||||
waiter.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
private rejectReadyWaiters(error: Error): void {
|
||||
const waiters = this.readyWaiters.splice(0)
|
||||
for (const waiter of waiters) {
|
||||
waiter.reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleIdleCloseIfUnused(): void {
|
||||
if (this.pendingRequests.size > 0 || this.readyWaiters.length > 0 || this.state !== 'ready') {
|
||||
return
|
||||
}
|
||||
this.clearIdleCloseTimer()
|
||||
this.idleCloseTimer = setTimeout(() => this.close(), IDLE_CLOSE_MS)
|
||||
if (typeof this.idleCloseTimer.unref === 'function') {
|
||||
this.idleCloseTimer.unref()
|
||||
}
|
||||
}
|
||||
|
||||
private clearIdleCloseTimer(): void {
|
||||
if (this.idleCloseTimer) {
|
||||
clearTimeout(this.idleCloseTimer)
|
||||
this.idleCloseTimer = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toClientError(error: unknown): Error {
|
||||
if (error instanceof Error) {
|
||||
return error
|
||||
}
|
||||
return new RemoteRuntimeClientError('runtime_error', String(error))
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
RuntimeRpcEnvelopeSchema,
|
||||
type RuntimeRpcResponse,
|
||||
isKeepaliveFrame
|
||||
} from './runtime-rpc-envelope'
|
||||
import { RemoteRuntimeClientError } from './remote-runtime-client'
|
||||
|
||||
export type ParsedRemoteRuntimeFrame =
|
||||
| { type: 'keepalive' }
|
||||
| { type: 'response'; response: RuntimeRpcResponse<unknown> }
|
||||
| { type: 'error'; error: RemoteRuntimeClientError }
|
||||
|
||||
export function remoteRuntimeUnavailableError(
|
||||
message = 'Remote Orca runtime closed the connection.'
|
||||
): RemoteRuntimeClientError {
|
||||
return new RemoteRuntimeClientError('remote_runtime_unavailable', message)
|
||||
}
|
||||
|
||||
export function remoteRuntimeTimeoutError(): RemoteRuntimeClientError {
|
||||
return new RemoteRuntimeClientError(
|
||||
'runtime_timeout',
|
||||
'Timed out waiting for the remote Orca runtime to respond.'
|
||||
)
|
||||
}
|
||||
|
||||
export function invalidRemoteRuntimeResponseError(message: string): RemoteRuntimeClientError {
|
||||
return new RemoteRuntimeClientError('invalid_runtime_response', message)
|
||||
}
|
||||
|
||||
export function parseReadyFrame(frame: string): RemoteRuntimeClientError | null {
|
||||
let ready: unknown
|
||||
try {
|
||||
ready = JSON.parse(frame)
|
||||
} catch {
|
||||
return invalidRemoteRuntimeResponseError(
|
||||
'Remote Orca runtime returned an invalid E2EE handshake frame.'
|
||||
)
|
||||
}
|
||||
if (
|
||||
typeof ready !== 'object' ||
|
||||
ready === null ||
|
||||
(ready as { type?: unknown }).type !== 'e2ee_ready'
|
||||
) {
|
||||
return invalidRemoteRuntimeResponseError(
|
||||
'Remote Orca runtime returned an unexpected E2EE handshake frame.'
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function parseAuthenticatedFrame(plaintext: string): RemoteRuntimeClientError | null {
|
||||
let authenticated: unknown
|
||||
try {
|
||||
authenticated = JSON.parse(plaintext)
|
||||
} catch {
|
||||
return invalidRemoteRuntimeResponseError(
|
||||
'Remote Orca runtime returned an invalid E2EE auth frame.'
|
||||
)
|
||||
}
|
||||
const type = (authenticated as { type?: unknown }).type
|
||||
if (type === 'e2ee_authenticated') {
|
||||
return null
|
||||
}
|
||||
const code =
|
||||
typeof authenticated === 'object' &&
|
||||
authenticated !== null &&
|
||||
(authenticated as { error?: { code?: unknown } }).error?.code === 'unauthorized'
|
||||
? 'unauthorized'
|
||||
: 'invalid_runtime_response'
|
||||
return new RemoteRuntimeClientError(code, 'Remote Orca runtime rejected the pairing token.')
|
||||
}
|
||||
|
||||
export function parseRemoteRuntimeRpcFrame(plaintext: string): ParsedRemoteRuntimeFrame {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(plaintext)
|
||||
} catch {
|
||||
return {
|
||||
type: 'error',
|
||||
error: invalidRemoteRuntimeResponseError(
|
||||
'Remote Orca runtime returned an invalid response frame.'
|
||||
)
|
||||
}
|
||||
}
|
||||
if (isKeepaliveFrame(raw)) {
|
||||
return { type: 'keepalive' }
|
||||
}
|
||||
const parsed = RuntimeRpcEnvelopeSchema.safeParse(raw)
|
||||
if (!parsed.success || '_keepalive' in parsed.data) {
|
||||
return {
|
||||
type: 'error',
|
||||
error: invalidRemoteRuntimeResponseError(
|
||||
'Remote Orca runtime returned an invalid response frame.'
|
||||
)
|
||||
}
|
||||
}
|
||||
return { type: 'response', response: parsed.data as RuntimeRpcResponse<unknown> }
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import WebSocket from 'ws'
|
||||
import type { PairingOffer } from './pairing'
|
||||
import {
|
||||
deriveSharedKey,
|
||||
generateKeyPair,
|
||||
publicKeyFromBase64,
|
||||
publicKeyToBase64
|
||||
} from './e2ee-crypto'
|
||||
import { RemoteRuntimeClientError } from './remote-runtime-client'
|
||||
import {
|
||||
invalidRemoteRuntimeResponseError,
|
||||
remoteRuntimeUnavailableError
|
||||
} from './remote-runtime-request-frames'
|
||||
|
||||
export type RemoteRuntimeWebSocket = {
|
||||
ws: WebSocket
|
||||
sharedKey: Uint8Array
|
||||
}
|
||||
|
||||
export type RemoteRuntimeWebSocketCallbacks = {
|
||||
onClose: (ws: WebSocket) => void
|
||||
onError: (ws: WebSocket, error: RemoteRuntimeClientError) => void
|
||||
onTextFrame: (ws: WebSocket, frame: string) => void
|
||||
}
|
||||
|
||||
export function openRemoteRuntimeWebSocket(
|
||||
pairing: PairingOffer,
|
||||
callbacks: RemoteRuntimeWebSocketCallbacks
|
||||
): { ok: true; socket: RemoteRuntimeWebSocket } | { ok: false; error: RemoteRuntimeClientError } {
|
||||
const opened = createSocket(pairing)
|
||||
if (!opened.ok) {
|
||||
return opened
|
||||
}
|
||||
const { ws, keyPair } = opened
|
||||
const serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64)
|
||||
const sharedKey = deriveSharedKey(keyPair.secretKey, serverPublicKey)
|
||||
|
||||
ws.once('open', () => {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'e2ee_hello',
|
||||
publicKeyB64: publicKeyToBase64(keyPair.publicKey)
|
||||
})
|
||||
)
|
||||
})
|
||||
ws.on('error', () => {
|
||||
callbacks.onError(
|
||||
ws,
|
||||
remoteRuntimeUnavailableError('Could not connect to the remote Orca runtime.')
|
||||
)
|
||||
})
|
||||
ws.on('close', () => callbacks.onClose(ws))
|
||||
ws.on('message', (data, isBinary) => {
|
||||
if (isBinary) {
|
||||
callbacks.onError(
|
||||
ws,
|
||||
invalidRemoteRuntimeResponseError(
|
||||
'Remote Orca runtime returned an unexpected binary frame.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
callbacks.onTextFrame(ws, data.toString())
|
||||
})
|
||||
return { ok: true, socket: { ws, sharedKey } }
|
||||
}
|
||||
|
||||
function createSocket(
|
||||
pairing: PairingOffer
|
||||
):
|
||||
| { ok: true; ws: WebSocket; keyPair: ReturnType<typeof generateKeyPair> }
|
||||
| { ok: false; error: RemoteRuntimeClientError } {
|
||||
let keyPair: ReturnType<typeof generateKeyPair>
|
||||
try {
|
||||
keyPair = generateKeyPair()
|
||||
publicKeyFromBase64(pairing.publicKeyB64)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return {
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError(
|
||||
'invalid_argument',
|
||||
`Invalid remote pairing key: ${message}`
|
||||
)
|
||||
}
|
||||
}
|
||||
try {
|
||||
return { ok: true, ws: new WebSocket(pairing.endpoint), keyPair }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return {
|
||||
ok: false,
|
||||
error: new RemoteRuntimeClientError('invalid_argument', `Invalid remote endpoint: ${message}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { mkdtempSync, rmSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { encodePairingOffer } from './pairing'
|
||||
import {
|
||||
RuntimeEnvironmentStoreError,
|
||||
addEnvironmentFromPairingCode,
|
||||
listEnvironments
|
||||
} from './runtime-environment-store'
|
||||
|
||||
function pairingCode(endpoint = 'ws://127.0.0.1:6768'): string {
|
||||
return encodePairingOffer({
|
||||
v: 2,
|
||||
endpoint,
|
||||
deviceToken: 'device-token',
|
||||
publicKeyB64: Buffer.from(new Uint8Array(32).fill(1)).toString('base64')
|
||||
})
|
||||
}
|
||||
|
||||
describe('runtime environment store', () => {
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects duplicate server names instead of silently replacing the saved server', () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-env-store-'))
|
||||
tempDirs.push(userDataPath)
|
||||
|
||||
const first = addEnvironmentFromPairingCode(userDataPath, {
|
||||
name: 'dev box',
|
||||
pairingCode: pairingCode('ws://127.0.0.1:6768')
|
||||
})
|
||||
|
||||
expect(() =>
|
||||
addEnvironmentFromPairingCode(userDataPath, {
|
||||
name: 'dev box',
|
||||
pairingCode: pairingCode('ws://192.0.2.10:6768')
|
||||
})
|
||||
).toThrow(RuntimeEnvironmentStoreError)
|
||||
expect(listEnvironments(userDataPath)).toEqual([first])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,166 @@
|
||||
import { randomUUID } from 'crypto'
|
||||
import { existsSync, readFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { parsePairingCode, type PairingOffer } from './pairing'
|
||||
import { hardenExistingSecureFile, writeSecureJsonFile } from './secure-file'
|
||||
import {
|
||||
createEnvironmentFromPairingOffer,
|
||||
getPreferredPairingOffer,
|
||||
KnownRuntimeEnvironmentSchema,
|
||||
RuntimeEnvironmentStoreSchema,
|
||||
type KnownRuntimeEnvironment,
|
||||
type RuntimeEnvironmentStore
|
||||
} from './runtime-environments'
|
||||
|
||||
const ENVIRONMENTS_FILE = 'orca-environments.json'
|
||||
|
||||
export type RuntimeEnvironmentStoreErrorCode = 'invalid_argument' | 'runtime_error'
|
||||
|
||||
export class RuntimeEnvironmentStoreError extends Error {
|
||||
readonly code: RuntimeEnvironmentStoreErrorCode
|
||||
|
||||
constructor(code: RuntimeEnvironmentStoreErrorCode, message: string) {
|
||||
super(message)
|
||||
this.name = 'RuntimeEnvironmentStoreError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export function getEnvironmentStorePath(userDataPath: string): string {
|
||||
return join(userDataPath, ENVIRONMENTS_FILE)
|
||||
}
|
||||
|
||||
export function listEnvironments(userDataPath: string): KnownRuntimeEnvironment[] {
|
||||
return readEnvironmentStore(userDataPath).environments
|
||||
}
|
||||
|
||||
export function addEnvironmentFromPairingCode(
|
||||
userDataPath: string,
|
||||
args: { name: string; pairingCode: string; now?: number }
|
||||
): KnownRuntimeEnvironment {
|
||||
const offer = parsePairingCode(args.pairingCode)
|
||||
if (!offer) {
|
||||
throw new RuntimeEnvironmentStoreError(
|
||||
'invalid_argument',
|
||||
'Invalid pairing code. Expected an orca://pair#... URL or bare pairing payload.'
|
||||
)
|
||||
}
|
||||
const store = readEnvironmentStore(userDataPath)
|
||||
const now = args.now ?? Date.now()
|
||||
const existing = store.environments.find((entry) => entry.name === args.name)
|
||||
if (existing) {
|
||||
throw new RuntimeEnvironmentStoreError(
|
||||
'invalid_argument',
|
||||
`A server named "${args.name}" already exists.`
|
||||
)
|
||||
}
|
||||
const environment = createEnvironmentFromPairingOffer({
|
||||
id: randomUUID(),
|
||||
name: args.name,
|
||||
now,
|
||||
offer,
|
||||
runtimeId: null
|
||||
})
|
||||
const next = {
|
||||
version: 1 as const,
|
||||
environments: [
|
||||
...store.environments.filter((entry) => entry.id !== environment.id),
|
||||
environment
|
||||
].sort((a, b) => a.name.localeCompare(b.name))
|
||||
}
|
||||
writeEnvironmentStore(userDataPath, next)
|
||||
return environment
|
||||
}
|
||||
|
||||
export function removeEnvironment(userDataPath: string, selector: string): KnownRuntimeEnvironment {
|
||||
const store = readEnvironmentStore(userDataPath)
|
||||
const environment = resolveEnvironmentFromStore(store, selector)
|
||||
writeEnvironmentStore(userDataPath, {
|
||||
version: 1,
|
||||
environments: store.environments.filter((entry) => entry.id !== environment.id)
|
||||
})
|
||||
return environment
|
||||
}
|
||||
|
||||
export function resolveEnvironment(
|
||||
userDataPath: string,
|
||||
selector: string
|
||||
): KnownRuntimeEnvironment {
|
||||
return resolveEnvironmentFromStore(readEnvironmentStore(userDataPath), selector)
|
||||
}
|
||||
|
||||
export function resolveEnvironmentPairingOffer(
|
||||
userDataPath: string,
|
||||
selector: string
|
||||
): PairingOffer {
|
||||
return getPreferredPairingOffer(resolveEnvironment(userDataPath, selector))
|
||||
}
|
||||
|
||||
export function markEnvironmentUsed(
|
||||
userDataPath: string,
|
||||
selector: string,
|
||||
args: { runtimeId?: string | null; now?: number } = {}
|
||||
): void {
|
||||
const store = readEnvironmentStore(userDataPath)
|
||||
const environment = resolveEnvironmentFromStore(store, selector)
|
||||
const now = args.now ?? Date.now()
|
||||
const next = store.environments.map((entry) =>
|
||||
entry.id === environment.id
|
||||
? {
|
||||
...entry,
|
||||
runtimeId: args.runtimeId ?? entry.runtimeId,
|
||||
lastUsedAt: now,
|
||||
updatedAt: now
|
||||
}
|
||||
: entry
|
||||
)
|
||||
writeEnvironmentStore(userDataPath, { version: 1, environments: next })
|
||||
}
|
||||
|
||||
function resolveEnvironmentFromStore(
|
||||
store: RuntimeEnvironmentStore,
|
||||
selector: string
|
||||
): KnownRuntimeEnvironment {
|
||||
const byId = store.environments.find((entry) => entry.id === selector)
|
||||
if (byId) {
|
||||
return byId
|
||||
}
|
||||
const matches = store.environments.filter((entry) => entry.name === selector)
|
||||
if (matches.length === 1) {
|
||||
return matches[0]!
|
||||
}
|
||||
if (matches.length > 1) {
|
||||
throw new RuntimeEnvironmentStoreError(
|
||||
'invalid_argument',
|
||||
`Environment name "${selector}" is ambiguous; use the environment id.`
|
||||
)
|
||||
}
|
||||
throw new RuntimeEnvironmentStoreError('invalid_argument', `Unknown environment: ${selector}`)
|
||||
}
|
||||
|
||||
function readEnvironmentStore(userDataPath: string): RuntimeEnvironmentStore {
|
||||
const path = getEnvironmentStorePath(userDataPath)
|
||||
if (!existsSync(path)) {
|
||||
return { version: 1, environments: [] }
|
||||
}
|
||||
try {
|
||||
hardenExistingSecureFile(path)
|
||||
const parsed = RuntimeEnvironmentStoreSchema.parse(JSON.parse(readFileSync(path, 'utf8')))
|
||||
return {
|
||||
version: 1,
|
||||
environments: parsed.environments
|
||||
.map((entry) => KnownRuntimeEnvironmentSchema.parse(entry))
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
}
|
||||
} catch {
|
||||
throw new RuntimeEnvironmentStoreError(
|
||||
'runtime_error',
|
||||
`Could not read Orca environments at ${path}; the file is invalid.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function writeEnvironmentStore(userDataPath: string, store: RuntimeEnvironmentStore): void {
|
||||
const path = getEnvironmentStorePath(userDataPath)
|
||||
writeSecureJsonFile(path, RuntimeEnvironmentStoreSchema.parse(store))
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { z } from 'zod'
|
||||
import { PAIRING_OFFER_VERSION, type PairingOffer } from './pairing'
|
||||
|
||||
export const RuntimeAccessEndpointSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
kind: z.literal('websocket'),
|
||||
label: z.string().min(1),
|
||||
endpoint: z.string().min(1),
|
||||
deviceToken: z.string().min(1),
|
||||
publicKeyB64: z.string().min(1)
|
||||
})
|
||||
|
||||
export type RuntimeAccessEndpoint = z.infer<typeof RuntimeAccessEndpointSchema>
|
||||
|
||||
export const PublicRuntimeAccessEndpointSchema = RuntimeAccessEndpointSchema.omit({
|
||||
deviceToken: true,
|
||||
publicKeyB64: true
|
||||
})
|
||||
|
||||
export type PublicRuntimeAccessEndpoint = z.infer<typeof PublicRuntimeAccessEndpointSchema>
|
||||
|
||||
export const KnownRuntimeEnvironmentSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
createdAt: z.number().finite(),
|
||||
updatedAt: z.number().finite(),
|
||||
lastUsedAt: z.number().finite().nullable(),
|
||||
runtimeId: z.string().min(1).nullable(),
|
||||
endpoints: z.array(RuntimeAccessEndpointSchema).min(1),
|
||||
preferredEndpointId: z.string().min(1)
|
||||
})
|
||||
|
||||
export type KnownRuntimeEnvironment = z.infer<typeof KnownRuntimeEnvironmentSchema>
|
||||
|
||||
export type PublicKnownRuntimeEnvironment = Omit<KnownRuntimeEnvironment, 'endpoints'> & {
|
||||
endpoints: PublicRuntimeAccessEndpoint[]
|
||||
}
|
||||
|
||||
export function redactRuntimeEnvironment(
|
||||
environment: KnownRuntimeEnvironment
|
||||
): PublicKnownRuntimeEnvironment {
|
||||
return {
|
||||
...environment,
|
||||
endpoints: environment.endpoints.map(
|
||||
({ deviceToken: _deviceToken, publicKeyB64: _key, ...rest }) => rest
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const RuntimeEnvironmentStoreSchema = z.object({
|
||||
version: z.literal(1),
|
||||
environments: z.array(KnownRuntimeEnvironmentSchema)
|
||||
})
|
||||
|
||||
export type RuntimeEnvironmentStore = z.infer<typeof RuntimeEnvironmentStoreSchema>
|
||||
|
||||
export function createEnvironmentFromPairingOffer(args: {
|
||||
id: string
|
||||
name: string
|
||||
now: number
|
||||
offer: PairingOffer
|
||||
runtimeId?: string | null
|
||||
}): KnownRuntimeEnvironment {
|
||||
const endpointId = `ws-${args.id}`
|
||||
return KnownRuntimeEnvironmentSchema.parse({
|
||||
id: args.id,
|
||||
name: args.name,
|
||||
createdAt: args.now,
|
||||
updatedAt: args.now,
|
||||
lastUsedAt: null,
|
||||
runtimeId: args.runtimeId ?? null,
|
||||
endpoints: [
|
||||
{
|
||||
id: endpointId,
|
||||
kind: 'websocket',
|
||||
label: 'WebSocket',
|
||||
endpoint: args.offer.endpoint,
|
||||
deviceToken: args.offer.deviceToken,
|
||||
publicKeyB64: args.offer.publicKeyB64
|
||||
}
|
||||
],
|
||||
preferredEndpointId: endpointId
|
||||
})
|
||||
}
|
||||
|
||||
export function getPreferredPairingOffer(environment: KnownRuntimeEnvironment): PairingOffer {
|
||||
const endpoint =
|
||||
environment.endpoints.find((entry) => entry.id === environment.preferredEndpointId) ??
|
||||
environment.endpoints[0]
|
||||
if (!endpoint) {
|
||||
throw new Error(`Environment ${environment.name} has no access endpoints`)
|
||||
}
|
||||
return {
|
||||
v: PAIRING_OFFER_VERSION,
|
||||
endpoint: endpoint.endpoint,
|
||||
deviceToken: endpoint.deviceToken,
|
||||
publicKeyB64: endpoint.publicKeyB64
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Why: runtime clients can be CLI, desktop, or future non-Electron shells.
|
||||
// Keeping the envelope contract here avoids making those clients import each
|
||||
// other just to validate the shared RPC frame shape.
|
||||
import { z } from 'zod'
|
||||
|
||||
const MetaSuccess = z.object({
|
||||
runtimeId: z.string()
|
||||
})
|
||||
|
||||
const MetaFailure = z
|
||||
.object({
|
||||
runtimeId: z.union([z.string(), z.null()])
|
||||
})
|
||||
.optional()
|
||||
|
||||
const Success = z.object({
|
||||
id: z.string(),
|
||||
ok: z.literal(true),
|
||||
result: z.unknown(),
|
||||
_meta: MetaSuccess
|
||||
})
|
||||
|
||||
const Failure = z.object({
|
||||
id: z.string(),
|
||||
ok: z.literal(false),
|
||||
error: z.object({
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
data: z.unknown().optional()
|
||||
}),
|
||||
_meta: MetaFailure
|
||||
})
|
||||
|
||||
const Keepalive = z.object({
|
||||
_keepalive: z.literal(true)
|
||||
})
|
||||
|
||||
export const RuntimeRpcEnvelopeSchema = z.union([Success, Failure, Keepalive])
|
||||
|
||||
export type RuntimeRpcSuccess<TResult> = {
|
||||
id: string
|
||||
ok: true
|
||||
result: TResult
|
||||
_meta: {
|
||||
runtimeId: string
|
||||
}
|
||||
}
|
||||
|
||||
export type RuntimeRpcFailure = {
|
||||
id: string
|
||||
ok: false
|
||||
error: {
|
||||
code: string
|
||||
message: string
|
||||
data?: unknown
|
||||
}
|
||||
_meta?: {
|
||||
runtimeId: string | null
|
||||
}
|
||||
}
|
||||
|
||||
export type RuntimeRpcResponse<TResult> = RuntimeRpcSuccess<TResult> | RuntimeRpcFailure
|
||||
|
||||
export type RuntimeRpcKeepaliveFrame = z.infer<typeof Keepalive>
|
||||
|
||||
export function isKeepaliveFrame(frame: unknown): frame is RuntimeRpcKeepaliveFrame {
|
||||
return (
|
||||
typeof frame === 'object' &&
|
||||
frame !== null &&
|
||||
'_keepalive' in frame &&
|
||||
(frame as { _keepalive: unknown })._keepalive === true
|
||||
)
|
||||
}
|
||||
+46
-12
@@ -1,10 +1,18 @@
|
||||
/* eslint-disable max-lines -- Why: shared type definitions for all runtime RPC methods live in one file for discoverability and import simplicity. */
|
||||
import type { TerminalPaneLayoutNode } from './types'
|
||||
import type { BrowserSessionProfile, GitWorktreeInfo, Repo } from './types'
|
||||
import type {
|
||||
BrowserCookieImportResult,
|
||||
BrowserSessionProfile,
|
||||
BrowserSessionProfileSource,
|
||||
GitWorktreeInfo,
|
||||
Repo,
|
||||
Worktree
|
||||
} from './types'
|
||||
import type {
|
||||
RuntimeMarkdownReadTabResult,
|
||||
RuntimeMarkdownSaveTabResult
|
||||
} from './mobile-markdown-document'
|
||||
import type { RuntimeCapability } from './protocol-version'
|
||||
|
||||
export type { RuntimeMarkdownReadTabResult, RuntimeMarkdownSaveTabResult }
|
||||
|
||||
@@ -17,9 +25,13 @@ export type RuntimeStatus = {
|
||||
authoritativeWindowId: number | null
|
||||
liveTabCount: number
|
||||
liveLeafCount: number
|
||||
// Why: optional so mobile builds can read both new and pre-PR desktops.
|
||||
// Absence is treated as 0 by mobile's compat evaluator. See
|
||||
// src/shared/protocol-version.ts for bump discipline.
|
||||
// Why: optional so clients can read both new and pre-contract runtimes.
|
||||
// Absence is treated as protocol 0 by the compat evaluator.
|
||||
runtimeProtocolVersion?: number
|
||||
minCompatibleRuntimeClientVersion?: number
|
||||
capabilities?: RuntimeCapability[]
|
||||
// COMPAT(runtimeStatusMobileAliases): added 2026-05-15 for mobile builds
|
||||
// that still read these names; new desktop/CLI code uses the fields above.
|
||||
protocolVersion?: number
|
||||
minCompatibleMobileVersion?: number
|
||||
}
|
||||
@@ -189,6 +201,13 @@ export type RuntimeFileReadResult = {
|
||||
byteLength: number
|
||||
}
|
||||
|
||||
export type RuntimeFilePreviewResult = {
|
||||
content: string
|
||||
isBinary: boolean
|
||||
isImage?: boolean
|
||||
mimeType?: string
|
||||
}
|
||||
|
||||
export type RuntimeTerminalSummary = {
|
||||
handle: string
|
||||
worktreeId: string
|
||||
@@ -292,15 +311,8 @@ export type RuntimeWorktreePsSummary = {
|
||||
|
||||
export type RuntimeWorktreeStatus = 'active' | 'working' | 'permission' | 'done' | 'inactive'
|
||||
|
||||
export type RuntimeWorktreeRecord = {
|
||||
id: string
|
||||
repoId: string
|
||||
path: string
|
||||
branch: string
|
||||
linkedIssue: number | null
|
||||
export type RuntimeWorktreeRecord = Worktree & {
|
||||
git: GitWorktreeInfo
|
||||
displayName: string
|
||||
comment: string
|
||||
}
|
||||
|
||||
export type RuntimeWorktreePsResult = {
|
||||
@@ -446,6 +458,28 @@ export type BrowserProfileDeleteResult = {
|
||||
profileId: string
|
||||
}
|
||||
|
||||
export type BrowserDetectedProfileInfo = {
|
||||
name: string
|
||||
directory: string
|
||||
}
|
||||
|
||||
export type BrowserDetectedInfo = {
|
||||
family: BrowserSessionProfileSource['browserFamily']
|
||||
label: string
|
||||
profiles: BrowserDetectedProfileInfo[]
|
||||
selectedProfile: string
|
||||
}
|
||||
|
||||
export type BrowserDetectProfilesResult = {
|
||||
browsers: BrowserDetectedInfo[]
|
||||
}
|
||||
|
||||
export type BrowserProfileImportFromBrowserResult = BrowserCookieImportResult
|
||||
|
||||
export type BrowserProfileClearDefaultCookiesResult = {
|
||||
cleared: boolean
|
||||
}
|
||||
|
||||
export type BrowserHoverResult = {
|
||||
hovered: string
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { execFileSync } from 'child_process'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from 'fs'
|
||||
import { dirname } from 'path'
|
||||
|
||||
let cachedWindowsUserSid: string | null | undefined
|
||||
|
||||
export function writeSecureJsonFile(targetPath: string, value: unknown): void {
|
||||
writeSecureFile(targetPath, JSON.stringify(value, null, 2))
|
||||
}
|
||||
|
||||
export function writeSecureFile(targetPath: string, contents: string): void {
|
||||
const dir = dirname(targetPath)
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
||||
}
|
||||
hardenSecurePath(dir, { isDirectory: true, platform: process.platform })
|
||||
|
||||
const tmpFile = `${targetPath}.${process.pid}.${Date.now()}.${randomBytes(4).toString('hex')}.tmp`
|
||||
try {
|
||||
writeFileSync(tmpFile, contents, {
|
||||
encoding: 'utf-8',
|
||||
mode: 0o600
|
||||
})
|
||||
hardenSecurePath(tmpFile, { isDirectory: false, platform: process.platform })
|
||||
renameSync(tmpFile, targetPath)
|
||||
// Why: these files carry runtime auth/device credentials; the published
|
||||
// path must remain current-user only after the atomic rename.
|
||||
hardenSecurePath(targetPath, { isDirectory: false, platform: process.platform })
|
||||
} catch (error) {
|
||||
rmSync(tmpFile, { force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function hardenExistingSecureFile(targetPath: string): void {
|
||||
const dir = dirname(targetPath)
|
||||
if (existsSync(dir)) {
|
||||
hardenSecurePath(dir, { isDirectory: true, platform: process.platform })
|
||||
}
|
||||
if (existsSync(targetPath)) {
|
||||
hardenSecurePath(targetPath, { isDirectory: false, platform: process.platform })
|
||||
}
|
||||
}
|
||||
|
||||
export function hardenSecurePath(
|
||||
targetPath: string,
|
||||
options: {
|
||||
isDirectory: boolean
|
||||
platform: NodeJS.Platform
|
||||
}
|
||||
): void {
|
||||
if (options.platform === 'win32') {
|
||||
bestEffortRestrictWindowsPath(targetPath)
|
||||
return
|
||||
}
|
||||
chmodSync(targetPath, options.isDirectory ? 0o700 : 0o600)
|
||||
}
|
||||
|
||||
function bestEffortRestrictWindowsPath(targetPath: string): void {
|
||||
const currentUserSid = getCurrentWindowsUserSid()
|
||||
if (!currentUserSid) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
execFileSync(
|
||||
'icacls',
|
||||
[
|
||||
targetPath,
|
||||
'/inheritance:r',
|
||||
'/grant:r',
|
||||
`*${currentUserSid}:(F)`,
|
||||
'*S-1-5-18:(F)',
|
||||
'*S-1-5-32-544:(F)'
|
||||
],
|
||||
{
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
timeout: 5000
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
// Why: credential-file hardening should not prevent Orca from starting on
|
||||
// Windows machines where icacls is unavailable or locked down differently.
|
||||
}
|
||||
}
|
||||
|
||||
function getCurrentWindowsUserSid(): string | null {
|
||||
if (cachedWindowsUserSid !== undefined) {
|
||||
return cachedWindowsUserSid
|
||||
}
|
||||
try {
|
||||
const output = execFileSync('whoami', ['/user', '/fo', 'csv', '/nh'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
windowsHide: true,
|
||||
timeout: 5000
|
||||
}).trim()
|
||||
const columns = parseCsvLine(output)
|
||||
cachedWindowsUserSid = columns[1] ?? null
|
||||
} catch {
|
||||
cachedWindowsUserSid = null
|
||||
}
|
||||
return cachedWindowsUserSid
|
||||
}
|
||||
|
||||
function parseCsvLine(line: string): string[] {
|
||||
return line.split(/","/).map((part) => part.replace(/^"/, '').replace(/"$/, ''))
|
||||
}
|
||||
@@ -44,6 +44,61 @@ describe('terminal-stream-protocol', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('round-trips terminal input and resize frames', () => {
|
||||
const input = decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Input,
|
||||
streamId: 11,
|
||||
seq: 1,
|
||||
payload: encodeTerminalStreamText('a')
|
||||
})
|
||||
)
|
||||
const resize = decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Resize,
|
||||
streamId: 11,
|
||||
seq: 2,
|
||||
payload: encodeTerminalStreamJson({ cols: 120, rows: 40 })
|
||||
})
|
||||
)
|
||||
|
||||
expect(input?.opcode).toBe(TerminalStreamOpcode.Input)
|
||||
expect(input ? decodeTerminalStreamText(input.payload) : '').toBe('a')
|
||||
expect(resize?.opcode).toBe(TerminalStreamOpcode.Resize)
|
||||
expect(resize && decodeTerminalStreamJson(resize.payload)).toEqual({ cols: 120, rows: 40 })
|
||||
})
|
||||
|
||||
it('round-trips multiplex subscribe and unsubscribe frames', () => {
|
||||
const subscribe = decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Subscribe,
|
||||
streamId: 0,
|
||||
seq: 1,
|
||||
payload: encodeTerminalStreamJson({
|
||||
streamId: 12,
|
||||
terminal: 'terminal-1',
|
||||
viewport: { cols: 120, rows: 40 }
|
||||
})
|
||||
})
|
||||
)
|
||||
const unsubscribe = decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Unsubscribe,
|
||||
streamId: 12,
|
||||
seq: 2,
|
||||
payload: new Uint8Array()
|
||||
})
|
||||
)
|
||||
|
||||
expect(subscribe?.opcode).toBe(TerminalStreamOpcode.Subscribe)
|
||||
expect(subscribe && decodeTerminalStreamJson(subscribe.payload)).toMatchObject({
|
||||
streamId: 12,
|
||||
terminal: 'terminal-1'
|
||||
})
|
||||
expect(unsubscribe?.opcode).toBe(TerminalStreamOpcode.Unsubscribe)
|
||||
expect(unsubscribe?.streamId).toBe(12)
|
||||
})
|
||||
|
||||
it('rejects unknown frame versions and opcodes', () => {
|
||||
const encoded = encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Output,
|
||||
|
||||
@@ -8,7 +8,11 @@ export enum TerminalStreamOpcode {
|
||||
SnapshotChunk = 3,
|
||||
SnapshotEnd = 4,
|
||||
Resized = 5,
|
||||
Error = 6
|
||||
Error = 6,
|
||||
Input = 7,
|
||||
Resize = 8,
|
||||
Subscribe = 9,
|
||||
Unsubscribe = 10
|
||||
}
|
||||
|
||||
export type TerminalStreamFrame = {
|
||||
@@ -82,6 +86,10 @@ function isTerminalStreamOpcode(value: number): value is TerminalStreamOpcode {
|
||||
value === TerminalStreamOpcode.SnapshotChunk ||
|
||||
value === TerminalStreamOpcode.SnapshotEnd ||
|
||||
value === TerminalStreamOpcode.Resized ||
|
||||
value === TerminalStreamOpcode.Error
|
||||
value === TerminalStreamOpcode.Error ||
|
||||
value === TerminalStreamOpcode.Input ||
|
||||
value === TerminalStreamOpcode.Resize ||
|
||||
value === TerminalStreamOpcode.Subscribe ||
|
||||
value === TerminalStreamOpcode.Unsubscribe
|
||||
)
|
||||
}
|
||||
|
||||
@@ -435,6 +435,7 @@ export type PersistedOpenFile = {
|
||||
worktreeId: string
|
||||
language: string
|
||||
isPreview?: boolean
|
||||
runtimeEnvironmentId?: string
|
||||
}
|
||||
|
||||
export type WorkspaceSessionState = {
|
||||
@@ -1382,6 +1383,9 @@ export type GlobalSettings = {
|
||||
* configuration surface and edge cases (conflicts with existing paths,
|
||||
* cleanup on worktree delete) are still being worked out. */
|
||||
experimentalWorktreeSymlinks: boolean
|
||||
/** Active non-local runtime environment for client-routed RPC. `null`
|
||||
* preserves the current local desktop behavior. */
|
||||
activeRuntimeEnvironmentId?: string | null
|
||||
/** GitHub Project mode state — pinned/recent/active project, last selected
|
||||
* view per project. Optional because profiles created before this feature
|
||||
* landed won't have the key; `getDefaultSettings()` hydrates the empty
|
||||
|
||||
@@ -125,7 +125,8 @@ const persistedOpenFileSchema = z.object({
|
||||
relativePath: z.string(),
|
||||
worktreeId: z.string(),
|
||||
language: z.string(),
|
||||
isPreview: z.boolean().optional()
|
||||
isPreview: z.boolean().optional(),
|
||||
runtimeEnvironmentId: z.string().optional()
|
||||
})
|
||||
|
||||
// ─── Browser ────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user