fix(proxy): harden remote terminal WebSocket bridging

Restrict the token-free proxy socket to ticketed persistent PTY connects.
OpenCode builds per-directory services before it validates an /api/pty
ticket, so that route must not be reachable without the Manager token.

- Reject untrusted Origins and an uninitialized lifecycle before upgrading
- Open the upstream socket first and answer 403 on rejection instead of
  upgrading and closing
- Handle ticketed sockets before the repo lookup and the password read
- Cap client-to-upstream buffering at 4 MiB and add a 10 s connect deadline
- Share bridge handlers, peer wrapper, proxy prefix and WebSocket URL helpers
- Remove persistent PTYs with their directory in TerminalService.removeAll
This commit is contained in:
Chris Scott committed 2026-10-07 21:22:15 -04:00
1 parent 98668f684b
commit 958cf7cd53
13 files changed
+1256 -273

No files matched your search

@@ -1,6 +1,6 @@
import { describe, it, expect, afterEach } from 'vitest'
import { ENV, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from '../../../src/services/opencode/upstream'
import { getOpenCodeUpstreamBaseUrl, toWebSocketUrl, withDefaultOpenCodeDirectory } from '../../../src/services/opencode/upstream'
const originalHost = ENV.OPENCODE.HOST
@@ -58,3 +58,25 @@ describe('withDefaultOpenCodeDirectory', () => {
expect(withDefaultOpenCodeDirectory(headers)).toBe(headers)
})
})
describe('toWebSocketUrl', () => {
it('maps an http URL to ws and preserves the path, port and query', () => {
expect(toWebSocketUrl('http://127.0.0.1:5551/api/pty/pty-1/connect?ticket=abc')).toBe(
'ws://127.0.0.1:5551/api/pty/pty-1/connect?ticket=abc',
)
})
it('maps an https URL to wss', () => {
expect(toWebSocketUrl('https://opencode.internal/api/pty/pty-1/connect')).toBe(
'wss://opencode.internal/api/pty/pty-1/connect',
)
})
it('leaves a ws URL unchanged', () => {
expect(toWebSocketUrl('ws://127.0.0.1:5551/api/pty/pty-1/connect')).toBe('ws://127.0.0.1:5551/api/pty/pty-1/connect')
})
it('leaves a wss URL unchanged', () => {
expect(toWebSocketUrl('wss://opencode.internal/api')).toBe('wss://opencode.internal/api')
})
})