Revert "fix(memory): bound OOM-prone accumulators (#10179)" (#10255)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-23 18:35:31 -07:00
committed by GitHub
co-authored by Orca
parent 6eb70d8370
commit aab112933e
1577 changed files with 15167 additions and 91655 deletions
+15 -99
View File
@@ -1,7 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import {
HEADER_LENGTH,
MAX_BUFFERED_FRAME_CHUNKS,
MessageType,
encodeFrame,
encodeJsonRpcFrame,
@@ -13,7 +12,6 @@ import {
type JsonRpcRequest,
type DecodedFrame
} from './relay-protocol'
import { RELAY_JSON_MAX_STRUCTURAL_TOKENS } from '../../shared/relay-json-admission'
describe('git response stream marker', () => {
it('accepts only complete non-negative integer metadata', () => {
@@ -28,15 +26,6 @@ describe('git response stream marker', () => {
__orcaGitResponseStream: { streamId: -1, totalBytes: 1024, chunkCount: 2 }
})
).toBe(false)
expect(
isGitResponseStreamMarker({
__orcaGitResponseStream: {
streamId: 1,
totalBytes: Number.MAX_SAFE_INTEGER + 1,
chunkCount: 2
}
})
).toBe(false)
})
})
@@ -90,37 +79,11 @@ describe('frame encoding', () => {
method: 'x',
params: { data: 'a'.repeat(17 * 1024 * 1024) }
}
const fromSpy = vi.spyOn(Buffer, 'from')
try {
expect(() => encodeJsonRpcFrame(bigPayload, 1, 0)).toThrow('Message too large')
expect(fromSpy).not.toHaveBeenCalled()
} finally {
fromSpy.mockRestore()
}
expect(() => encodeJsonRpcFrame(bigPayload, 1, 0)).toThrow('Message too large')
})
})
describe('FrameDecoder', () => {
it('bounds retained chunk wrappers for a byte-fragmented frame', () => {
const frames: DecodedFrame[] = []
const decoder = new FrameDecoder((frame) => frames.push(frame))
const payloadLength = MAX_BUFFERED_FRAME_CHUNKS + 512
const header = Buffer.alloc(HEADER_LENGTH)
header[0] = MessageType.Regular
header.writeUInt32BE(payloadLength, 9)
decoder.feed(header)
const byte = Buffer.from('x')
const state = decoder as unknown as { chunks: Buffer[] }
for (let index = 0; index < payloadLength; index += 1) {
decoder.feed(byte)
expect(state.chunks.length).toBeLessThanOrEqual(MAX_BUFFERED_FRAME_CHUNKS)
}
expect(frames).toHaveLength(1)
expect(frames[0].payload.equals(Buffer.alloc(payloadLength, 0x78))).toBe(true)
})
it('decodes a complete frame', () => {
const frames: DecodedFrame[] = []
const decoder = new FrameDecoder((f) => frames.push(f))
@@ -200,33 +163,6 @@ describe('FrameDecoder', () => {
expect(errors[0].message).toContain('discarded')
})
it('rejects an oversized header immediately without retaining its payload', () => {
const errors: Error[] = []
const decoder = new FrameDecoder(
() => {},
(err) => errors.push(err)
)
const header = Buffer.alloc(HEADER_LENGTH)
header[0] = MessageType.Regular
header.writeUInt32BE(0xffffffff, 9)
decoder.feed(header)
const state = decoder as unknown as {
bufferedLength: number
oversizedPayloadBytesRemaining: number
}
expect(errors).toHaveLength(1)
expect(state.bufferedLength).toBe(0)
expect(state.oversizedPayloadBytesRemaining).toBe(0xffffffff)
const payloadChunk = Buffer.alloc(64 * 1024)
for (let index = 0; index < 128; index += 1) {
decoder.feed(payloadChunk)
expect(state.bufferedLength).toBe(0)
}
expect(errors).toHaveLength(1)
})
it('reset clears internal buffer', () => {
const frames: DecodedFrame[] = []
const decoder = new FrameDecoder((f) => frames.push(f))
@@ -288,31 +224,26 @@ describe('FrameDecoder', () => {
expect(frames[0].payload.toString()).toBe('after')
})
it('retains ordinary transport chunks without copying them while a frame is incomplete', () => {
it('never rebuilds the buffered stream per feed while assembling a large frame', () => {
// Regression: feed() used Buffer.concat([buffered, chunk]) per data event,
// re-copying the whole backlog for every TCP chunk — O(n²) memcpy on the
// Electron main thread while fs.streamChunk frames arrive (SSH typing lag).
const frames: DecodedFrame[] = []
const decoder = new FrameDecoder((f) => frames.push(f))
const payloadLength = 1024 * 1024
const header = Buffer.alloc(HEADER_LENGTH)
header[0] = MessageType.Regular
header.writeUInt32BE(1, 1)
header.writeUInt32BE(payloadLength, 9)
decoder.feed(header)
const ordinaryChunks = Array.from({ length: 16 }, () => Buffer.alloc(32 * 1024, 0x61))
const frame = encodeFrame(MessageType.Regular, 1, 0, Buffer.alloc(512 * 1024, 0x61))
for (const chunk of ordinaryChunks) {
decoder.feed(chunk)
const concatSpy = vi.spyOn(Buffer, 'concat')
try {
for (let i = 0; i < frame.length; i += 32 * 1024) {
decoder.feed(frame.subarray(i, i + 32 * 1024))
}
} finally {
concatSpy.mockRestore()
}
const state = decoder as unknown as { chunks: Buffer[] }
expect(state.chunks).toHaveLength(ordinaryChunks.length + 1)
for (const [index, chunk] of ordinaryChunks.entries()) {
expect(state.chunks[index + 1]).toBe(chunk)
}
decoder.feed(Buffer.alloc(payloadLength / 2, 0x61))
expect(frames).toHaveLength(1)
expect(frames[0].payload.length).toBe(payloadLength)
expect(frames[0].payload.length).toBe(512 * 1024)
expect(concatSpy).not.toHaveBeenCalled()
})
})
@@ -339,21 +270,6 @@ describe('parseJsonRpcMessage', () => {
const payload = Buffer.from('not json')
expect(() => parseJsonRpcMessage(payload)).toThrow()
})
it('rejects structurally amplified JSON before parsing', () => {
const payload = Buffer.from(
`{"jsonrpc":"2.0","id":1,"method":"x","params":{"values":[${'0,'.repeat(
RELAY_JSON_MAX_STRUCTURAL_TOKENS
)}0]}}`
)
const parseSpy = vi.spyOn(JSON, 'parse')
try {
expect(() => parseJsonRpcMessage(payload)).toThrow(/JSON structure exceeds/)
expect(parseSpy).not.toHaveBeenCalled()
} finally {
parseSpy.mockRestore()
}
})
})
describe('parseUnameToRelayPlatform', () => {
+21 -75
View File
@@ -3,11 +3,6 @@
// See design-ssh-support.md § JSON-RPC Protocol Specification.
import { DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS } from '../../shared/ssh-types'
import {
JsonStringifyByteLimitError,
stringifyJsonWithinByteLimit
} from '../../shared/node-bounded-json-stringify'
import { parseRelayJsonText } from '../../shared/relay-json-admission'
export const RELAY_VERSION = '0.1.0'
export const RELAY_SENTINEL = `ORCA-RELAY v${RELAY_VERSION} READY\n`
@@ -18,8 +13,6 @@ export const RELAY_REMOTE_DIR = '.orca-remote'
export const HEADER_LENGTH = 13
export const MAX_MESSAGE_SIZE = 16 * 1024 * 1024 // 16 MB
export const MAX_BUFFERED_FRAME_CHUNKS = 4_096
const MAX_COALESCED_TINY_FRAME_CHUNK_BYTES = 8 * 1024
/** Message type byte. */
export const MessageType = {
@@ -43,8 +36,7 @@ export const RelayErrorCode = {
PtyAllocationFailed: -33004,
DiskFull: -33005,
TooManyStreams: -33006,
StreamProtocolError: -33007,
MarkdownDocumentListingCapacity: -33008
StreamProtocolError: -33007
} as const
export const JsonRpcErrorCode = {
@@ -76,11 +68,6 @@ export const GIT_RESPONSE_STREAM_THRESHOLD = 256 * 1024
* so it stays cross-version safe. */
export const GIT_RESPONSE_CHUNK_SIZE = 128 * 1024
/** Bounds retained serialized Git results while preserving responses far above
* the per-file render limit and git.exec's output ceiling. */
export const MAX_GIT_RESPONSE_STREAM_BYTES = 64 * 1024 * 1024
export const MAX_GIT_RESPONSE_STREAM_CHUNKS = 4_096
/** Sentinel the relay returns as the RPC result when the real payload streams
* as git.responseChunk frames. Absent from old relays, so a new client falls
* back to the plain result they return. */
@@ -98,11 +85,11 @@ export function isGitResponseStreamMarker(value: unknown): value is GitResponseS
}
const fields = marker as Record<string, unknown>
return (
Number.isSafeInteger(fields.streamId) &&
Number.isInteger(fields.streamId) &&
(fields.streamId as number) > 0 &&
Number.isSafeInteger(fields.totalBytes) &&
Number.isInteger(fields.totalBytes) &&
(fields.totalBytes as number) >= 0 &&
Number.isSafeInteger(fields.chunkCount) &&
Number.isInteger(fields.chunkCount) &&
(fields.chunkCount as number) >= 0
)
}
@@ -157,16 +144,10 @@ export function encodeFrame(
}
export function encodeJsonRpcFrame(msg: JsonRpcMessage, id: number, ack: number): Buffer {
let serialized: string
try {
serialized = stringifyJsonWithinByteLimit(msg, MAX_MESSAGE_SIZE).serialized
} catch (error) {
if (error instanceof JsonStringifyByteLimitError) {
throw new Error(`Message too large: more than ${MAX_MESSAGE_SIZE} bytes`)
}
throw error
const payload = Buffer.from(JSON.stringify(msg), 'utf-8')
if (payload.length > MAX_MESSAGE_SIZE) {
throw new Error(`Message too large: ${payload.length} bytes (max ${MAX_MESSAGE_SIZE})`)
}
const payload = Buffer.from(serialized, 'utf-8')
return encodeFrame(MessageType.Regular, id, ack, payload)
}
@@ -192,7 +173,6 @@ export class FrameDecoder {
// list assembles each frame exactly once instead.
private chunks: Buffer[] = []
private bufferedLength = 0
private oversizedPayloadBytesRemaining = 0
private onFrame: (frame: DecodedFrame) => void
private onError: ((err: Error) => void) | null
@@ -202,18 +182,12 @@ export class FrameDecoder {
}
feed(chunk: Buffer | Uint8Array): void {
let buf = Buffer.isBuffer(chunk)
const buf = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
if (this.oversizedPayloadBytesRemaining > 0 && buf.length > 0) {
const discarded = Math.min(this.oversizedPayloadBytesRemaining, buf.length)
this.oversizedPayloadBytesRemaining -= discarded
buf = buf.subarray(discarded)
}
if (buf.length > 0) {
this.chunks.push(buf)
this.bufferedLength += buf.length
this.coalesceBufferedChunks()
}
while (this.bufferedLength >= HEADER_LENGTH) {
@@ -221,26 +195,25 @@ export class FrameDecoder {
const length = header.readUInt32BE(9)
const totalLength = HEADER_LENGTH + length
if (this.bufferedLength < totalLength) {
// Not fully received yet (also holds oversized frames until they can
// be skipped whole, keeping the decoder synchronized).
break
}
// Why: throwing here would leave the buffer in a partially consumed
// state — subsequent feed() calls would try to parse leftover payload
// bytes as a new header, corrupting every future frame. Instead we
// skip the entire oversized frame so the decoder stays synchronized.
if (length > MAX_MESSAGE_SIZE) {
// Why: retain only the header, then stream-discard the advertised
// payload so a 13-byte malicious header cannot pin up to 4 GiB.
this.discardBytes(HEADER_LENGTH)
this.oversizedPayloadBytesRemaining = length
this.discardBufferedOversizedPayload()
this.discardBytes(totalLength)
const err = new Error(`Frame payload too large: ${length} bytes — discarded`)
if (this.onError) {
this.onError(err)
}
if (this.oversizedPayloadBytesRemaining > 0) {
break
}
continue
}
if (this.bufferedLength < totalLength) {
break
}
const framed = this.takeBytes(totalLength)
const frame: DecodedFrame = {
type: framed[0],
@@ -255,7 +228,6 @@ export class FrameDecoder {
reset(): void {
this.chunks = []
this.bufferedLength = 0
this.oversizedPayloadBytesRemaining = 0
}
/** View of the first `count` buffered bytes without consuming them. */
@@ -320,40 +292,14 @@ export class FrameDecoder {
}
this.bufferedLength -= count
}
private discardBufferedOversizedPayload(): void {
const discarded = Math.min(this.oversizedPayloadBytesRemaining, this.bufferedLength)
if (discarded === 0) {
return
}
this.discardBytes(discarded)
this.oversizedPayloadBytesRemaining -= discarded
}
private coalesceBufferedChunks(): void {
// Why: merge adversarial tiny fragments without copying ordinary transport chunks.
while (this.chunks.length >= 2) {
const right = this.chunks.at(-1)!
const left = this.chunks.at(-2)!
if (
left.length > right.length ||
left.length + right.length > MAX_COALESCED_TINY_FRAME_CHUNK_BYTES
) {
break
}
this.chunks.splice(-2, 2, Buffer.concat([left, right], left.length + right.length))
}
if (this.chunks.length > MAX_BUFFERED_FRAME_CHUNKS) {
this.chunks = [Buffer.concat(this.chunks, this.bufferedLength)]
}
}
}
/**
* Parse a JSON-RPC message from a frame payload.
*/
export function parseJsonRpcMessage(payload: Buffer): JsonRpcMessage {
const msg = parseRelayJsonText<JsonRpcMessage>(payload.toString('utf-8'))
const text = payload.toString('utf-8')
const msg = JSON.parse(text) as JsonRpcMessage
if (msg.jsonrpc !== '2.0') {
throw new Error(`Invalid JSON-RPC version: ${(msg as Record<string, unknown>).jsonrpc}`)
}
-116
View File
@@ -1,116 +0,0 @@
import type { SFTPWrapper } from 'ssh2'
import { SshDirectoryTransferBudget } from './ssh-directory-transfer-budget'
type SftpDirectoryEntry = {
filename: string
attrs?: {
isDirectory?: () => boolean
}
}
export async function removeDirectorySftp(sftp: SFTPWrapper, remoteDir: string): Promise<void> {
const budget = new SshDirectoryTransferBudget()
budget.recordPath(remoteDir, 0, { countEntry: false })
await removeDirectorySftpWithinBudget(sftp, remoteDir, budget, 0)
}
async function removeDirectorySftpWithinBudget(
sftp: SFTPWrapper,
remoteDir: string,
budget: SshDirectoryTransferBudget,
depth: number
): Promise<void> {
const handle = await opendirSftp(sftp, remoteDir)
const normalizedRemoteDir = remoteDir.replace(/\/+$/, '')
let completed = false
try {
for (;;) {
const entries = await readdirSftp(sftp, handle)
if (!entries) {
break
}
for (const entry of entries) {
if (entry.filename === '.' || entry.filename === '..') {
continue
}
const childPath = `${normalizedRemoteDir}/${entry.filename}`
budget.recordPath(childPath, depth + 1)
await (entry.attrs?.isDirectory?.()
? removeDirectorySftpWithinBudget(sftp, childPath, budget, depth + 1)
: unlinkSftp(sftp, childPath))
}
}
completed = true
} finally {
await closeSftpHandle(sftp, handle).catch((error: unknown) => {
if (completed) {
throw error
}
})
}
await rmdirSftp(sftp, remoteDir)
}
function opendirSftp(sftp: SFTPWrapper, remoteDir: string): Promise<Buffer> {
return new Promise((resolve, reject) => {
sftp.opendir(remoteDir, (err, handle) => {
if (err) {
reject(err)
return
}
resolve(handle)
})
})
}
function readdirSftp(sftp: SFTPWrapper, handle: Buffer): Promise<SftpDirectoryEntry[] | null> {
return new Promise((resolve, reject) => {
sftp.readdir(handle, (err, entries) => {
if ((err as { code?: number } | undefined)?.code === 1) {
resolve(null)
return
}
if (err) {
reject(err)
return
}
resolve((entries ?? []) as SftpDirectoryEntry[])
})
})
}
function closeSftpHandle(sftp: SFTPWrapper, handle: Buffer): Promise<void> {
return new Promise((resolve, reject) => {
sftp.close(handle, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
function unlinkSftp(sftp: SFTPWrapper, remotePath: string): Promise<void> {
return new Promise((resolve, reject) => {
sftp.unlink(remotePath, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
function rmdirSftp(sftp: SFTPWrapper, remoteDir: string): Promise<void> {
return new Promise((resolve, reject) => {
sftp.rmdir(remoteDir, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
+4 -33
View File
@@ -5,7 +5,6 @@ import { Writable } from 'node:stream'
import { describe, expect, it, vi } from 'vitest'
import type { SFTPWrapper } from 'ssh2'
import { removeDirectorySftp, uploadBuffer, uploadDirectory, uploadFile } from './sftp-upload'
import { SSH_DIRECTORY_TRANSFER_LIMITS } from './ssh-directory-transfer-budget'
function createWritable(): Writable {
return new Writable({
@@ -19,13 +18,9 @@ function createSftpMock(): SFTPWrapper {
return {
mkdir: vi.fn((_path: string, cb: (err?: Error | null) => void) => cb(null)),
createWriteStream: vi.fn(() => createWritable()),
opendir: vi.fn((path: string, cb: (err: Error | undefined, handle: Buffer) => void) =>
cb(undefined, Buffer.from(path))
readdir: vi.fn((_path: string, cb: (err?: Error | null, entries?: unknown[]) => void) =>
cb(null, [])
),
readdir: vi.fn((_handle: Buffer, cb: (err?: Error | null, entries?: unknown[]) => void) =>
cb(Object.assign(new Error('EOF'), { code: 1 }), [])
),
close: vi.fn((_handle: Buffer, cb: (err?: Error | null) => void) => cb(null)),
unlink: vi.fn((_path: string, cb: (err?: Error | null) => void) => cb(null)),
rmdir: vi.fn((_path: string, cb: (err?: Error | null) => void) => cb(null))
} as unknown as SFTPWrapper
@@ -99,23 +94,6 @@ describe('sftp-upload', () => {
expect(sftp.createWriteStream).not.toHaveBeenCalled()
})
it('rejects excessive depth before creating remote entries', async () => {
const localDir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-'))
let nested = localDir
for (let depth = 0; depth <= SSH_DIRECTORY_TRANSFER_LIMITS.maximumDepth; depth += 1) {
nested = join(nested, 'd')
await mkdir(nested)
}
const sftp = createSftpMock()
await expect(
uploadDirectory(sftp, localDir, '/remote/assets', await realpath(localDir))
).rejects.toMatchObject({ reason: 'depth' })
expect(sftp.mkdir).not.toHaveBeenCalled()
expect(sftp.createWriteStream).not.toHaveBeenCalled()
})
it('does not create the remote file when the local source is a symlink', async () => {
const localDir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-'))
const targetPath = join(localDir, process.platform === 'win32' ? 'target-dir' : 'target.txt')
@@ -138,14 +116,8 @@ describe('sftp-upload', () => {
it('removes remote directory contents before removing the directory', async () => {
const sftp = createSftpMock()
const readPaths = new Set<string>()
vi.mocked(sftp.readdir).mockImplementation((handle, cb) => {
const pathString = String(handle)
if (readPaths.has(pathString)) {
cb(Object.assign(new Error('EOF'), { code: 1 }), [] as never)
return
}
readPaths.add(pathString)
vi.mocked(sftp.readdir).mockImplementation((remotePath, cb) => {
const pathString = String(remotePath)
if (pathString === '/remote/assets') {
cb(undefined, [
{ filename: '.', attrs: { isDirectory: () => true } },
@@ -172,6 +144,5 @@ describe('sftp-upload', () => {
expect(sftp.rmdir).toHaveBeenNthCalledWith(1, '/remote/assets/nested', expect.any(Function))
expect(sftp.unlink).toHaveBeenNthCalledWith(2, '/remote/assets/logo.png', expect.any(Function))
expect(sftp.rmdir).toHaveBeenNthCalledWith(2, '/remote/assets', expect.any(Function))
expect(sftp.close).toHaveBeenCalledTimes(2)
})
})
+78 -59
View File
@@ -1,11 +1,8 @@
import { constants } from 'node:fs'
import type { ReadStream } from 'node:fs'
import { lstat, open, opendir, realpath } from 'node:fs/promises'
import { lstat, open, readdir, realpath } from 'node:fs/promises'
import { isAbsolute, join as pathJoin, relative, sep } from 'node:path'
import type { SFTPWrapper } from 'ssh2'
import { SshDirectoryTransferBudget } from './ssh-directory-transfer-budget'
export { removeDirectorySftp } from './sftp-directory-removal'
export function mkdirSftp(
sftp: SFTPWrapper,
@@ -135,65 +132,87 @@ export async function uploadDirectory(
rootRealPath = localDir,
options?: { exclusive?: boolean }
): Promise<void> {
const entries = await collectLocalUploadEntries(localDir, remoteDir, rootRealPath)
for (const entry of entries) {
await assertLocalUploadPathInsideRoot(rootRealPath, entry.localPath)
const statResult = await lstat(entry.localPath)
if (statResult.isSymbolicLink() || statResult.isDirectory() !== (entry.kind === 'directory')) {
throw new Error(`Upload source changed during transfer: ${entry.localPath}`)
}
await (entry.kind === 'directory'
? mkdirSftp(sftp, entry.remotePath, { allowExisting: !options?.exclusive })
: uploadFile(sftp, entry.localPath, entry.remotePath, {
exclusive: options?.exclusive
}))
}
}
type LocalUploadEntry = {
kind: 'directory' | 'file'
localPath: string
remotePath: string
}
async function collectLocalUploadEntries(
localDir: string,
remoteDir: string,
rootRealPath: string
): Promise<LocalUploadEntry[]> {
const budget = new SshDirectoryTransferBudget()
const collected: LocalUploadEntry[] = []
const pending = [{ localDir, remoteDir, depth: 0 }]
await assertLocalUploadPathInsideRoot(rootRealPath, localDir)
budget.recordPath(remoteDir, 0, { countEntry: false })
budget.recordPath(localDir, 0, { countEntry: false })
const entries = await readdir(localDir, { withFileTypes: true })
for (const entry of entries) {
const localPath = pathJoin(localDir, entry.name)
const remotePath = `${remoteDir}/${entry.name}`
await assertLocalUploadPathInsideRoot(rootRealPath, localPath)
const statResult = await lstat(localPath)
while (pending.length > 0) {
const current = pending.pop()!
const handle = await opendir(current.localDir)
try {
for await (const entry of handle) {
const localPath = pathJoin(current.localDir, entry.name)
const remotePath = `${current.remoteDir}/${entry.name}`
const depth = current.depth + 1
budget.recordPath(remotePath, depth)
budget.recordPath(localPath, depth, { countEntry: false })
await assertLocalUploadPathInsideRoot(rootRealPath, localPath)
const statResult = await lstat(localPath)
if (statResult.isSymbolicLink() || (!statResult.isFile() && !statResult.isDirectory())) {
continue
}
const kind = statResult.isDirectory() ? 'directory' : 'file'
collected.push({ kind, localPath, remotePath })
if (kind === 'directory') {
pending.push({ localDir: localPath, remoteDir: remotePath, depth })
}
}
} finally {
await handle.close().catch(() => undefined)
// Why: skip symlinks and special files (sockets, FIFOs, devices) to
// prevent following symlinks that could exfiltrate local files to the
// remote. The caller's pre-scan catches symlinks up-front, but this
// guard closes the TOCTOU gap if one is created between scan and upload.
if (statResult.isSymbolicLink() || (!statResult.isFile() && !statResult.isDirectory())) {
continue
}
if (statResult.isDirectory()) {
await mkdirSftp(sftp, remotePath, { allowExisting: !options?.exclusive })
await uploadDirectory(sftp, localPath, remotePath, rootRealPath, options)
} else {
await uploadFile(sftp, localPath, remotePath, { exclusive: options?.exclusive })
}
}
return collected
}
export async function removeDirectorySftp(sftp: SFTPWrapper, remoteDir: string): Promise<void> {
const entries = await readdirSftp(sftp, remoteDir)
const normalizedRemoteDir = remoteDir.replace(/\/+$/, '')
for (const entry of entries) {
if (entry.filename === '.' || entry.filename === '..') {
continue
}
const childPath = `${normalizedRemoteDir}/${entry.filename}`
await (entry.attrs?.isDirectory?.()
? removeDirectorySftp(sftp, childPath)
: unlinkSftp(sftp, childPath))
}
await rmdirSftp(sftp, remoteDir)
}
type SftpDirectoryEntry = {
filename: string
attrs?: {
isDirectory?: () => boolean
}
}
function readdirSftp(sftp: SFTPWrapper, remoteDir: string): Promise<SftpDirectoryEntry[]> {
return new Promise((resolve, reject) => {
sftp.readdir(remoteDir, (err, entries) => {
if (err) {
reject(err)
return
}
resolve((entries ?? []) as SftpDirectoryEntry[])
})
})
}
function unlinkSftp(sftp: SFTPWrapper, remotePath: string): Promise<void> {
return new Promise((resolve, reject) => {
sftp.unlink(remotePath, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
function rmdirSftp(sftp: SFTPWrapper, remoteDir: string): Promise<void> {
return new Promise((resolve, reject) => {
sftp.rmdir(remoteDir, (err) => {
if (err) {
reject(err)
return
}
resolve()
})
})
}
async function assertLocalUploadPathInsideRoot(
+11 -11
View File
@@ -4,11 +4,11 @@ import { join } from 'node:path'
const mocks = vi.hoisted(() => ({
createAgent: vi.fn(),
parseKey: vi.fn(),
readSshKeyFile: vi.fn()
readFileSync: vi.fn()
}))
vi.mock('./ssh-key-file', () => ({
readSshKeyFile: (...args: unknown[]) => mocks.readSshKeyFile(...args)
vi.mock('fs', () => ({
readFileSync: (...args: unknown[]) => mocks.readFileSync(...args)
}))
vi.mock('os', () => ({
@@ -50,13 +50,13 @@ describe('createIdentityFilteredAgent', () => {
beforeEach(() => {
mocks.createAgent.mockReset()
mocks.parseKey.mockReset()
mocks.readSshKeyFile.mockReset()
mocks.readFileSync.mockReset()
})
it('offers only agent identities matching configured identity files', async () => {
const allowedKey = makeKey('allowed')
const otherKey = makeKey('other')
mocks.readSshKeyFile.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.parseKey.mockReturnValue(allowedKey)
mocks.createAgent.mockReturnValue({
getIdentities: vi.fn((callback) => callback(undefined, [allowedKey, otherKey])),
@@ -75,12 +75,12 @@ describe('createIdentityFilteredAgent', () => {
})
expect(identities).toEqual([allowedKey])
expect(mocks.readSshKeyFile).toHaveBeenCalledWith(testHomePath('.ssh', 'work_key.pub'))
expect(mocks.readFileSync).toHaveBeenCalledWith(testHomePath('.ssh', 'work_key.pub'))
})
it('expands Windows-style configured identity file paths before filtering', async () => {
const allowedKey = makeKey('allowed')
mocks.readSshKeyFile.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.parseKey.mockReturnValue(allowedKey)
mocks.createAgent.mockReturnValue({
getIdentities: vi.fn((callback) => callback(undefined, [allowedKey])),
@@ -99,7 +99,7 @@ describe('createIdentityFilteredAgent', () => {
})
expect(identities).toEqual([allowedKey])
expect(mocks.readSshKeyFile).toHaveBeenCalledWith(testHomePath('.ssh', 'work_key.pub'))
expect(mocks.readFileSync).toHaveBeenCalledWith(testHomePath('.ssh', 'work_key.pub'))
})
it('filters nested public key entries returned by ssh2 agents', async () => {
@@ -107,7 +107,7 @@ describe('createIdentityFilteredAgent', () => {
const otherKey = makeKey('other')
const allowedEntry = { pubKey: { pubKey: allowedKey, comment: 'allowed' } }
const otherEntry = { pubKey: { pubKey: otherKey, comment: 'other' } }
mocks.readSshKeyFile.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.parseKey.mockReturnValue(allowedKey)
mocks.createAgent.mockReturnValue({
getIdentities: vi.fn((callback) => callback(undefined, [allowedEntry, otherEntry])),
@@ -129,7 +129,7 @@ describe('createIdentityFilteredAgent', () => {
})
it('does not create a broad agent when configured identity keys cannot be parsed', () => {
mocks.readSshKeyFile.mockReturnValue('not-a-key')
mocks.readFileSync.mockReturnValue('not-a-key')
mocks.parseKey.mockReturnValue(new Error('parse failed'))
expect(createIdentityFilteredAgent('/tmp/agent.sock', ['~/.ssh/work_key'])).toBeUndefined()
@@ -141,7 +141,7 @@ describe('createIdentityFilteredAgent', () => {
const sign = vi.fn()
const options = { hash: 'sha256' as const }
const callback = vi.fn()
mocks.readSshKeyFile.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed')
mocks.parseKey.mockReturnValue(allowedKey)
mocks.createAgent.mockReturnValue({
getIdentities: vi.fn(),
+2 -2
View File
@@ -1,3 +1,4 @@
import { readFileSync } from 'node:fs'
import {
BaseAgent,
createAgent,
@@ -9,7 +10,6 @@ import {
type SigningRequestOptions
} from 'ssh2'
import { resolveSshConfigHomePath } from './ssh-config-path-expansion'
import { readSshKeyFile } from './ssh-key-file'
type AgentPublicKey = ParsedKey | Buffer | string | PublicKeyEntry
@@ -70,7 +70,7 @@ class IdentityFilteredAgent extends BaseAgent<ParsedKey | Buffer | string> {
function parseIdentityKeyFile(filePath: string): ParsedKey | undefined {
try {
const parsed = utils.parseKey(readSshKeyFile(filePath)) as ParsedKey | ParsedKey[] | Error
const parsed = utils.parseKey(readFileSync(filePath)) as ParsedKey | ParsedKey[] | Error
if (parsed instanceof Error) {
return undefined
}
+3 -4
View File
@@ -1,10 +1,9 @@
import { existsSync } from 'node:fs'
import { existsSync, readFileSync } from 'node:fs'
import { utils, type BaseAgent, type ParsedKey } from 'ssh2'
import type { SshTarget } from '../../shared/ssh-types'
import type { SshResolvedConfig } from './ssh-config-parser'
import { createIdentityFilteredAgent } from './ssh-agent-identity-filter'
import { resolveSshConfigHomePath } from './ssh-config-path-expansion'
import { readSshKeyFile } from './ssh-key-file'
// Why: ssh2 only tries keys that are explicitly provided. Users with keys in
// standard locations (e.g. ~/.ssh/id_ed25519) but no SSH agent running would
@@ -27,7 +26,7 @@ export function findDefaultKeyFile(): PrivateKeyFile | undefined {
if (!existsSync(resolved)) {
continue
}
const contents = readSshKeyFile(resolved)
const contents = readFileSync(resolved)
return { path: keyPath, contents }
} catch {
continue
@@ -97,7 +96,7 @@ function resolveExplicitPrivateKeyPath(
function readPrivateKey(keyPath: string): PrivateKeyFile | undefined {
try {
const resolvedPath = resolveSshConfigHomePath(keyPath)
return { path: keyPath, contents: readSshKeyFile(resolvedPath) }
return { path: keyPath, contents: readFileSync(resolvedPath) }
} catch {
return undefined
}
@@ -471,25 +471,6 @@ describe('SshChannelMultiplexer', () => {
expect(internals.disposeHandlers).toHaveLength(0)
})
it('invokes every dispose handler when handlers unsubscribe themselves', () => {
const called: string[] = []
let unsubscribeFirst = (): void => {}
let unsubscribeSecond = (): void => {}
unsubscribeFirst = mux.onDispose(() => {
called.push('first')
unsubscribeFirst()
})
unsubscribeSecond = mux.onDispose(() => {
called.push('second')
unsubscribeSecond()
})
mux.dispose('connection_lost')
expect(called).toEqual(['first', 'second'])
expect(getMuxInternals(mux).disposeHandlers).toHaveLength(0)
})
it('does not retain handlers registered after dispose', () => {
mux.dispose()
+2 -2
View File
@@ -305,14 +305,14 @@ export class SshChannelMultiplexer {
this.decoder.reset()
this.transport.close?.()
// Why: stream handlers unsubscribe while failing; detach first so one cleanup cannot skip the next.
for (const handler of this.disposeHandlers.splice(0)) {
for (const handler of this.disposeHandlers) {
try {
handler(reason)
} catch {
// Don't let a handler error prevent other handlers from running
}
}
this.disposeHandlers.length = 0
}
isDisposed(): boolean {
@@ -1,75 +0,0 @@
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join, posix, win32 } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { resolveBoundedSshConfigGlob } from './ssh-config-bounded-glob'
const pathApi = process.platform === 'win32' ? win32 : posix
const tempRoots: string[] = []
const SOURCE = readFileSync(new URL('./ssh-config-bounded-glob.ts', import.meta.url), 'utf8')
function makeTempRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'orca-ssh-config-glob-'))
tempRoots.push(root)
return root
}
afterEach(() => {
for (const root of tempRoots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
describe('bounded SSH config include globbing', () => {
it('retains only the first 256 sorted matches without materializing every result', () => {
const root = makeTempRoot()
const includeDir = join(root, 'conf.d')
mkdirSync(includeDir)
for (let index = 0; index < 2_000; index += 1) {
writeFileSync(join(includeDir, `${String(index).padStart(4, '0')}.conf`), '')
}
const result = resolveBoundedSshConfigGlob(join(includeDir, '*.conf'), pathApi, 256)
expect(result.totalMatches).toBe(2_000)
expect(result.truncated).toBe(true)
expect(result.matches).toHaveLength(256)
expect(result.matches.map((filePath) => basename(filePath))).toEqual(
Array.from({ length: 256 }, (_, index) => `${String(index).padStart(4, '0')}.conf`)
)
expect(SOURCE).not.toContain('globSync')
})
it('scans past nonmatches and preserves sorted order below the cap', () => {
const root = makeTempRoot()
const includeDir = join(root, 'conf.d')
mkdirSync(includeDir)
for (let index = 0; index < 300; index += 1) {
writeFileSync(join(includeDir, `${index}.txt`), '')
}
writeFileSync(join(includeDir, 'zeta.conf'), '')
writeFileSync(join(includeDir, 'alpha.conf'), '')
const result = resolveBoundedSshConfigGlob(join(includeDir, '*.conf'), pathApi, 256)
expect(result).toMatchObject({ totalMatches: 2, truncated: false })
expect(result.matches.map((filePath) => basename(filePath))).toEqual([
'alpha.conf',
'zeta.conf'
])
})
it('rejects path patterns deep enough to threaten the traversal stack', () => {
const pattern = pathApi.join(
pathApi.parse(process.cwd()).root,
...Array.from({ length: 65 }, () => '*')
)
expect(resolveBoundedSshConfigGlob(pattern, pathApi, 256)).toEqual({
matches: [],
totalMatches: 0,
truncated: true,
patternTooDeep: true
})
})
})
-124
View File
@@ -1,124 +0,0 @@
import { existsSync, opendirSync, statSync } from 'node:fs'
import type { posix, win32 } from 'node:path'
export type SshConfigPathApi = typeof posix | typeof win32
export type BoundedSshConfigGlobResult = {
matches: string[]
totalMatches: number
truncated: boolean
patternTooDeep: boolean
}
const MAX_GLOB_PATTERN_SEGMENTS = 64
export function resolveBoundedSshConfigGlob(
absolutePattern: string,
pathApi: SshConfigPathApi,
matchLimit: number
): BoundedSshConfigGlobResult {
const root = pathApi.parse(absolutePattern).root
const segments = absolutePattern.slice(root.length).split(pathApi.sep).filter(Boolean)
if (segments.length > MAX_GLOB_PATTERN_SEGMENTS) {
return { matches: [], totalMatches: 0, truncated: true, patternTooDeep: true }
}
const matches: string[] = []
let totalMatches = 0
const retainMatch = (matchedPath: string): void => {
totalMatches += 1
insertSortedWithinLimit(matches, matchedPath, matchLimit)
}
const visit = (directoryPath: string, segmentIndex: number): void => {
const segment = segments[segmentIndex]
const isLast = segmentIndex === segments.length - 1
if (!hasGlobPattern(segment)) {
const nextPath = pathApi.join(directoryPath, segment)
if (isLast) {
if (existsSync(nextPath)) {
retainMatch(nextPath)
}
return
}
visit(nextPath, segmentIndex + 1)
return
}
let directory: ReturnType<typeof opendirSync>
try {
directory = opendirSync(directoryPath)
} catch {
return
}
try {
for (let entry = directory.readSync(); entry; entry = directory.readSync()) {
if (!pathApi.matchesGlob(entry.name, segment)) {
continue
}
const nextPath = pathApi.join(directoryPath, entry.name)
if (isLast) {
retainMatch(nextPath)
continue
}
if (entry.isDirectory() || isDirectorySymlink(nextPath, entry.isSymbolicLink())) {
visit(nextPath, segmentIndex + 1)
}
}
} finally {
directory.closeSync()
}
}
if (segments.length === 0) {
if (existsSync(root)) {
retainMatch(root)
}
} else {
visit(root, 0)
}
return {
matches,
totalMatches,
truncated: totalMatches > matchLimit,
patternTooDeep: false
}
}
function insertSortedWithinLimit(target: string[], value: string, limit: number): void {
if (limit <= 0) {
return
}
let low = 0
let high = target.length
while (low < high) {
const middle = (low + high) >>> 1
if (target[middle].localeCompare(value) <= 0) {
low = middle + 1
} else {
high = middle
}
}
if (low >= limit) {
return
}
target.splice(low, 0, value)
if (target.length > limit) {
target.pop()
}
}
function isDirectorySymlink(filePath: string, isSymbolicLink: boolean): boolean {
if (!isSymbolicLink) {
return false
}
try {
return statSync(filePath).isDirectory()
} catch {
return false
}
}
function hasGlobPattern(input: string): boolean {
return /[*?[]/.test(input)
}
-153
View File
@@ -1,153 +0,0 @@
import { statSync } from 'node:fs'
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
export const SSH_CONFIG_INCLUDE_LIMITS = {
expandedBytes: 16 * 1024 * 1024,
expandedLines: 200_000,
fileBytes: 1024 * 1024,
files: 1024,
globMatches: 256,
nestingDepth: 16,
sourceBytes: 16 * 1024 * 1024
} as const
export type SshConfigExpansionBudget = {
cache: Map<string, string>
expandedBytes: number
expandedLines: number
fileCount: number
outputTruncated: boolean
sourceBytes: number
warnedLimits: Set<string>
}
export function createSshConfigExpansionBudget(): SshConfigExpansionBudget {
return {
cache: new Map(),
expandedBytes: 0,
expandedLines: 0,
fileCount: 0,
outputTruncated: false,
sourceBytes: 0,
warnedLimits: new Set()
}
}
export function admitSshConfigIncludeDepth(
budget: SshConfigExpansionBudget,
activeDepth: number
): boolean {
if (activeDepth < SSH_CONFIG_INCLUDE_LIMITS.nestingDepth) {
return true
}
warnOnce(
budget,
'nesting-depth',
`[ssh] SSH config Include nesting exceeds ${SSH_CONFIG_INCLUDE_LIMITS.nestingDepth}; skipping deeper files`
)
return false
}
export function appendSshConfigExpandedLine(
target: string[],
line: string,
budget: SshConfigExpansionBudget
): void {
const nextBytes = Buffer.byteLength(line, 'utf8') + (target.length > 0 ? 1 : 0)
if (
budget.expandedLines >= SSH_CONFIG_INCLUDE_LIMITS.expandedLines ||
budget.expandedBytes + nextBytes > SSH_CONFIG_INCLUDE_LIMITS.expandedBytes
) {
budget.outputTruncated = true
warnOnce(
budget,
'expanded-output',
`[ssh] Expanded SSH config exceeds ${SSH_CONFIG_INCLUDE_LIMITS.expandedBytes} bytes or ${SSH_CONFIG_INCLUDE_LIMITS.expandedLines} lines; truncating`
)
return
}
target.push(line)
budget.expandedBytes += nextBytes
budget.expandedLines += 1
}
export function readSshConfigSourceFile(
filePath: string,
budget: SshConfigExpansionBudget
): string | null {
const cached = budget.cache.get(filePath)
if (cached !== undefined) {
return cached
}
if (budget.fileCount >= SSH_CONFIG_INCLUDE_LIMITS.files) {
warnOnce(
budget,
'file-count',
`[ssh] SSH config Include file count exceeds ${SSH_CONFIG_INCLUDE_LIMITS.files}; skipping additional files`
)
return null
}
const fileBytes = getReadableRegularFileBytes(filePath)
if (fileBytes === null || !hasSourceCapacity(budget, fileBytes)) {
return null
}
try {
const content = readNodeFileSyncWithinLimit(
filePath,
SSH_CONFIG_INCLUDE_LIMITS.fileBytes
).buffer.toString('utf-8')
const actualBytes = Buffer.byteLength(content, 'utf8')
if (
actualBytes > SSH_CONFIG_INCLUDE_LIMITS.fileBytes ||
!hasSourceCapacity(budget, actualBytes)
) {
return null
}
budget.cache.set(filePath, content)
budget.fileCount += 1
budget.sourceBytes += actualBytes
return content
} catch {
return null
}
}
function hasSourceCapacity(budget: SshConfigExpansionBudget, fileBytes: number): boolean {
if (budget.sourceBytes + fileBytes <= SSH_CONFIG_INCLUDE_LIMITS.sourceBytes) {
return true
}
warnOnce(
budget,
'source-bytes',
`[ssh] SSH config Include sources exceed ${SSH_CONFIG_INCLUDE_LIMITS.sourceBytes} bytes; skipping additional files`
)
return false
}
function getReadableRegularFileBytes(filePath: string): number | null {
try {
const stats = statSync(filePath)
if (!stats.isFile()) {
console.warn(`[ssh] Skipping SSH config include "${filePath}": not a regular file`)
return null
}
if (stats.size > SSH_CONFIG_INCLUDE_LIMITS.fileBytes) {
console.warn(
`[ssh] Skipping SSH config include "${filePath}": size ${stats.size} exceeds ${SSH_CONFIG_INCLUDE_LIMITS.fileBytes} bytes`
)
return null
}
return stats.size
} catch {
return null
}
}
function warnOnce(budget: SshConfigExpansionBudget, key: string, message: string): void {
if (budget.warnedLimits.has(key)) {
return
}
budget.warnedLimits.add(key)
console.warn(message)
}
+73 -48
View File
@@ -1,20 +1,11 @@
import { existsSync, realpathSync } from 'node:fs'
import { existsSync, globSync, readFileSync, realpathSync, statSync } from 'node:fs'
import { homedir, hostname, userInfo } from 'node:os'
import { posix, win32 } from 'node:path'
import { resolveBoundedSshConfigGlob, type SshConfigPathApi } from './ssh-config-bounded-glob'
import {
admitSshConfigIncludeDepth,
appendSshConfigExpandedLine,
createSshConfigExpansionBudget,
readSshConfigSourceFile,
SSH_CONFIG_INCLUDE_LIMITS,
type SshConfigExpansionBudget
} from './ssh-config-expansion-budget'
type PathApi = SshConfigPathApi
type PathApi = typeof posix | typeof win32
type IncludeExpansionContext = {
budget: SshConfigExpansionBudget
cache: Map<string, string>
home: string
pathApi: PathApi
rootDir: string
@@ -23,6 +14,8 @@ type IncludeExpansionContext = {
username: string
}
const MAX_INCLUDE_GLOB_MATCHES = 256
const MAX_INCLUDE_FILE_BYTES = 1024 * 1024
const TARGET_DEPENDENT_INCLUDE_TOKENS = new Set(['h', 'n', 'p', 'r', 'j', 'k', 'C'])
export function expandSshConfigIncludes(configPath: string): string {
@@ -32,7 +25,7 @@ export function expandSshConfigIncludes(configPath: string): string {
const localHostname = hostname()
const context: IncludeExpansionContext = {
budget: createSshConfigExpansionBudget(),
cache: new Map(),
home,
pathApi,
rootDir: pathApi.dirname(configPath),
@@ -41,51 +34,69 @@ export function expandSshConfigIncludes(configPath: string): string {
username: currentUser
}
const expandedLines: string[] = []
expandSshConfigFile(configPath, context, [], expandedLines)
return expandedLines.join('\n')
return expandSshConfigFile(configPath, context, []).join('\n')
}
function expandSshConfigFile(
filePath: string,
context: IncludeExpansionContext,
activeStack: string[],
expandedLines: string[]
): void {
activeStack: string[]
): string[] {
const canonicalPath = getCanonicalPath(filePath)
if (!canonicalPath || activeStack.includes(canonicalPath)) {
return
}
if (!admitSshConfigIncludeDepth(context.budget, activeStack.length)) {
return
return []
}
const rawContent = readSshConfigSourceFile(canonicalPath, context.budget)
const rawContent = readCachedFile(canonicalPath, context)
if (rawContent === null) {
return
return []
}
const expandedLines: string[] = []
const nextStack = [...activeStack, canonicalPath]
for (const line of rawContent.split(/\r?\n/)) {
if (context.budget.outputTruncated) {
return
}
const includeArgs = parseIncludeDirective(line)
if (!includeArgs) {
appendSshConfigExpandedLine(expandedLines, line, context.budget)
expandedLines.push(line)
continue
}
for (const includeArg of includeArgs) {
for (const matchedPath of resolveIncludePaths(includeArg, context)) {
expandSshConfigFile(matchedPath, context, nextStack, expandedLines)
if (context.budget.outputTruncated) {
return
}
appendExpandedLines(expandedLines, expandSshConfigFile(matchedPath, context, nextStack))
}
}
}
return expandedLines
}
function appendExpandedLines(target: string[], lines: readonly string[]): void {
// Why: SSH config includes are user-controlled files, and a large included
// file can exceed the JavaScript call argument limit when spread into push.
for (const line of lines) {
target.push(line)
}
}
function readCachedFile(filePath: string, context: IncludeExpansionContext): string | null {
const cached = context.cache.get(filePath)
if (cached !== undefined) {
return cached
}
if (!isReadableRegularFile(filePath)) {
return null
}
try {
const content = readFileSync(filePath, 'utf-8')
context.cache.set(filePath, content)
return content
} catch {
return null
}
}
function parseIncludeDirective(line: string): string[] | null {
@@ -157,23 +168,18 @@ function resolveIncludePaths(pattern: string, context: IncludeExpansionContext):
const absolutePattern = resolveIncludePatternPath(withTokens, context)
if (hasGlobPattern(absolutePattern)) {
const result = resolveBoundedSshConfigGlob(
absolutePattern,
context.pathApi,
SSH_CONFIG_INCLUDE_LIMITS.globMatches
)
if (result.patternTooDeep) {
console.warn(
`[ssh] Include pattern "${absolutePattern}" has too many path segments; skipping`
)
try {
const matches = globSync(absolutePattern).sort((left, right) => left.localeCompare(right))
if (matches.length > MAX_INCLUDE_GLOB_MATCHES) {
console.warn(
`[ssh] Include pattern "${absolutePattern}" matched ${matches.length} files; processing first ${MAX_INCLUDE_GLOB_MATCHES}`
)
return matches.slice(0, MAX_INCLUDE_GLOB_MATCHES)
}
return matches
} catch {
return []
}
if (result.truncated) {
console.warn(
`[ssh] Include pattern "${absolutePattern}" matched ${result.totalMatches} files; processing first ${SSH_CONFIG_INCLUDE_LIMITS.globMatches}`
)
}
return result.matches
}
return existsSync(absolutePattern) ? [absolutePattern] : []
@@ -287,6 +293,25 @@ function getCanonicalPath(filePath: string): string | null {
}
}
function isReadableRegularFile(filePath: string): boolean {
try {
const stats = statSync(filePath)
if (!stats.isFile()) {
console.warn(`[ssh] Skipping SSH config include "${filePath}": not a regular file`)
return false
}
if (stats.size > MAX_INCLUDE_FILE_BYTES) {
console.warn(
`[ssh] Skipping SSH config include "${filePath}": size ${stats.size} exceeds ${MAX_INCLUDE_FILE_BYTES} bytes`
)
return false
}
return true
} catch {
return false
}
}
function getCurrentUid(): string | undefined {
try {
const info = userInfo()
@@ -1,82 +0,0 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
appendSshConfigExpandedLine,
createSshConfigExpansionBudget,
readSshConfigSourceFile,
SSH_CONFIG_INCLUDE_LIMITS
} from './ssh-config-expansion-budget'
import { expandSshConfigIncludes } from './ssh-config-include-expander'
const tempRoots: string[] = []
function makeTempRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'orca-ssh-config-bounds-'))
tempRoots.push(root)
return root
}
afterEach(() => {
vi.restoreAllMocks()
for (const root of tempRoots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
describe('SSH config include expansion bounds', () => {
it('stops recursive includes at 16 active files', () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const root = makeTempRoot()
for (let depth = 0; depth < 20; depth += 1) {
writeFileSync(
join(root, `${depth}.conf`),
`Host depth-${depth}\n${depth < 19 ? `Include ${depth + 1}.conf\n` : ''}`
)
}
const expanded = expandSshConfigIncludes(join(root, '0.conf'))
expect(expanded).toContain('Host depth-15')
expect(expanded).not.toContain('Host depth-16')
expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('nesting exceeds 16'))
})
it('admits exactly 1,024 unique files and 16 MiB of source bytes', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const root = makeTempRoot()
const firstPath = join(root, 'first.conf')
const secondPath = join(root, 'second.conf')
writeFileSync(firstPath, 'a')
writeFileSync(secondPath, 'b')
const fileBudget = createSshConfigExpansionBudget()
fileBudget.fileCount = SSH_CONFIG_INCLUDE_LIMITS.files - 1
expect(readSshConfigSourceFile(firstPath, fileBudget)).toBe('a')
expect(readSshConfigSourceFile(secondPath, fileBudget)).toBeNull()
const byteBudget = createSshConfigExpansionBudget()
byteBudget.sourceBytes = SSH_CONFIG_INCLUDE_LIMITS.sourceBytes - 1
expect(readSshConfigSourceFile(firstPath, byteBudget)).toBe('a')
expect(readSshConfigSourceFile(secondPath, byteBudget)).toBeNull()
expect(warn).toHaveBeenCalledWith(expect.stringContaining('file count exceeds 1024'))
expect(warn).toHaveBeenCalledWith(expect.stringContaining('sources exceed 16777216 bytes'))
})
it('caps expanded output at 16 MiB or 200,000 lines', () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const byteBudget = createSshConfigExpansionBudget()
byteBudget.expandedBytes = SSH_CONFIG_INCLUDE_LIMITS.expandedBytes - 1
const byteLines = ['']
appendSshConfigExpandedLine(byteLines, '', byteBudget)
expect(byteBudget.expandedBytes).toBe(SSH_CONFIG_INCLUDE_LIMITS.expandedBytes)
appendSshConfigExpandedLine(byteLines, '', byteBudget)
expect(byteBudget.outputTruncated).toBe(true)
const lineBudget = createSshConfigExpansionBudget()
lineBudget.expandedLines = SSH_CONFIG_INCLUDE_LIMITS.expandedLines
appendSshConfigExpandedLine([], 'Host overflow', lineBudget)
expect(lineBudget.outputTruncated).toBe(true)
})
})
@@ -8,7 +8,6 @@ afterEach(() => {
vi.resetModules()
vi.doUnmock('fs')
vi.doUnmock('os')
vi.doUnmock('../../shared/node-bounded-file-reader')
})
function normalizeWin(value: string): string {
@@ -25,24 +24,6 @@ function platformSshPath(home: string, relativePath: string): string {
: `${home}/${relativePath}`
}
function mockDirectory(names: string[]) {
let index = 0
return {
readSync: () => {
const name = names[index]
index += 1
return name === undefined
? null
: {
name,
isDirectory: () => false,
isSymbolicLink: () => false
}
},
closeSync: () => {}
}
}
async function mockOs(
home: string,
username = 'testuser',
@@ -61,18 +42,6 @@ async function mockOs(
}
async function loadUserSshConfig() {
vi.doMock('../../shared/node-bounded-file-reader', async () => {
const fs = await import('node:fs')
return {
readNodeFileSyncWithinLimit: (filePath: string, maxBytes: number) => {
const buffer = Buffer.from(fs.readFileSync(filePath, 'utf8'))
if (buffer.byteLength > maxBytes) {
throw new Error('File too large')
}
return { buffer, stats: fs.statSync(filePath) }
}
}
})
const mod = await import('./ssh-config-parser')
return mod.loadUserSshConfig()
}
@@ -108,12 +77,13 @@ describe('loadUserSshConfig regressions', () => {
return {
...actual,
existsSync: (filePath: string) => files.has(normalizeWin(filePath)),
opendirSync: (directoryPath: string) => {
if (normalizeWin(directoryPath) !== normalizeWin('C:/Users/Test User/.ssh/conf.d')) {
throw new Error(`ENOENT: ${directoryPath}`)
}
return mockDirectory(['zeta.conf', 'alpha.conf'])
},
globSync: (pattern: string) =>
normalizeWin(pattern) === normalizeWin('C:/Users/Test User/.ssh/conf.d/*.conf')
? [
normalizeWin('C:/Users/Test User/.ssh/conf.d/alpha.conf'),
normalizeWin('C:/Users/Test User/.ssh/conf.d/zeta.conf')
]
: [],
readFileSync: (filePath: string) => {
const content = files.get(normalizeWin(filePath))
if (content === undefined) {
@@ -235,8 +205,7 @@ describe('loadUserSshConfig regressions', () => {
...actual,
existsSync: (filePath: string) =>
filePath === configPath || includePaths.includes(filePath),
opendirSync: () =>
mockDirectory(includePaths.map((filePath) => filePath.split(/[\\/]/).at(-1)!)),
globSync: () => [...includePaths].toReversed(),
readFileSync: (filePath: string) => {
if (filePath === configPath) {
return 'Include conf.d/*.conf\n'
+26 -160
View File
@@ -1,15 +1,9 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
_internals,
MAX_RETAINED_SSH_CONNECTION_GENERATION_LEASES,
MAX_SSH_CONNECTION_GENERATION_RETAINED_TARGET_ID_BYTES,
MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES,
MAX_TRACKED_SSH_CONNECTION_GENERATIONS,
advanceSshConnectionGeneration,
assertSshMutationExpectation,
getSshConnectionGeneration,
resetSshConnectionGenerations,
retainSshConnectionGeneration,
setSshConnectionGeneration
} from './ssh-connection-generation'
@@ -21,31 +15,23 @@ describe('SSH connection generation session scope', () => {
it('does not reuse a target token when a restarted HUB reaches the same counter', () => {
resetSshConnectionGenerations(41)
const beforeRestartLease = retainSshConnectionGeneration('ssh-a')
const beforeRestart = getSshConnectionGeneration('ssh-a')
const beforeRestart = advanceSshConnectionGeneration('ssh-a')
resetSshConnectionGenerations(42)
const afterRestartLease = retainSshConnectionGeneration('ssh-a')
const afterRestart = getSshConnectionGeneration('ssh-a')
const afterRestart = advanceSshConnectionGeneration('ssh-a')
expect(afterRestart).not.toBe(beforeRestart)
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', beforeRestart)).toThrow(
'SSH connection changed; refresh and try again'
)
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', afterRestart)).not.toThrow()
beforeRestartLease.release()
afterRestartLease.release()
})
it('allocates globally unique target tokens within one HUB session', () => {
it('keeps target counters independent within one HUB session', () => {
resetSshConnectionGenerations(7)
const first = retainSshConnectionGeneration('ssh-a')
const second = retainSshConnectionGeneration('ssh-b')
expect(getSshConnectionGeneration('ssh-a')).not.toBe(getSshConnectionGeneration('ssh-b'))
first.release()
second.release()
expect(advanceSshConnectionGeneration('ssh-a')).toBe(advanceSshConnectionGeneration('ssh-b'))
expect(getSshConnectionGeneration('ssh-a')).toBe(getSshConnectionGeneration('ssh-b'))
})
it('rejects an SSH execution-host expectation when direct IPC resolves locally', () => {
@@ -60,165 +46,45 @@ describe('SSH connection generation session scope', () => {
)
})
it('rejects an unretained target even when its expected token equals the session base', () => {
it('rolls the session scope after counter exhaustion and keeps rotating', () => {
resetSshConnectionGenerations(7)
const exhaustedGeneration = 8 * SESSION_COUNTER_STRIDE - 1
setSshConnectionGeneration('ssh-a', exhaustedGeneration)
expect(() =>
assertSshMutationExpectation('ssh-a', 'ssh-a', 7 * SESSION_COUNTER_STRIDE)
).toThrow('SSH connection changed; refresh and try again')
const rolledGeneration = advanceSshConnectionGeneration('ssh-a')
expect(rolledGeneration).toBe(8 * SESSION_COUNTER_STRIDE + 1)
expect(advanceSshConnectionGeneration('ssh-a')).toBe(rolledGeneration + 1)
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', exhaustedGeneration)).toThrow(
'SSH connection changed; refresh and try again'
)
})
it('rotates allocation scopes without invalidating unrelated retained targets', () => {
it('invalidates other targets when exhaustion rolls the session scope', () => {
resetSshConnectionGenerations(11)
const otherLease = retainSshConnectionGeneration('ssh-b')
const otherTargetGeneration = getSshConnectionGeneration('ssh-b')
const rotatingLease = retainSshConnectionGeneration('ssh-a')
const otherTargetGeneration = advanceSshConnectionGeneration('ssh-b')
setSshConnectionGeneration('ssh-a', 12 * SESSION_COUNTER_STRIDE - 1)
const rotatedGeneration = advanceSshConnectionGeneration('ssh-a')
const rolledGeneration = advanceSshConnectionGeneration('ssh-a')
expect(rotatedGeneration).toBe(12 * SESSION_COUNTER_STRIDE + 1)
expect(getSshConnectionGeneration('ssh-b')).toBe(otherTargetGeneration)
expect(() =>
assertSshMutationExpectation('ssh-b', 'ssh-b', otherTargetGeneration)
).not.toThrow()
otherLease.release()
rotatingLease.release()
expect(getSshConnectionGeneration('ssh-b')).toBe(12 * SESSION_COUNTER_STRIDE)
expect(rolledGeneration).toBe(12 * SESSION_COUNTER_STRIDE + 1)
expect(() => assertSshMutationExpectation('ssh-b', 'ssh-b', otherTargetGeneration)).toThrow(
'SSH connection changed; refresh and try again'
)
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', rolledGeneration)).not.toThrow()
})
it('wraps the maximum numeric scope without reusing an allocated token', () => {
it('wraps the maximum safe numeric scope without reusing it', () => {
resetSshConnectionGenerations(MAX_SESSION_SCOPE)
const lease = retainSshConnectionGeneration('ssh-a')
setSshConnectionGeneration('ssh-a', Number.MAX_SAFE_INTEGER)
const rolledGeneration = advanceSshConnectionGeneration('ssh-a')
expect(rolledGeneration).toBe(1)
expect(Number.isSafeInteger(rolledGeneration)).toBe(true)
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', rolledGeneration!)).not.toThrow()
lease.release()
})
it('rejects only the 4,097th target without changing active or in-flight tokens', () => {
resetSshConnectionGenerations(7)
const leases = Array.from({ length: MAX_TRACKED_SSH_CONNECTION_GENERATIONS }, (_, index) =>
retainSshConnectionGeneration(`ssh-${index}`)
)
const activeGeneration = getSshConnectionGeneration('ssh-0')
const inFlightGeneration = getSshConnectionGeneration(
`ssh-${MAX_TRACKED_SSH_CONNECTION_GENERATIONS - 1}`
)
expect(() => retainSshConnectionGeneration('ssh-overflow')).toThrow(
'SSH connection generation target capacity exhausted'
)
expect(getSshConnectionGeneration('ssh-0')).toBe(activeGeneration)
expect(getSshConnectionGeneration(`ssh-${MAX_TRACKED_SSH_CONNECTION_GENERATIONS - 1}`)).toBe(
inFlightGeneration
)
expect(() => assertSshMutationExpectation('ssh-0', 'ssh-0', activeGeneration)).not.toThrow()
leases[1].release()
const overflowLease = retainSshConnectionGeneration('ssh-overflow')
expect(getSshConnectionGeneration('ssh-0')).toBe(activeGeneration)
for (const lease of leases) {
lease.release()
}
overflowLease.release()
expect(_internals.evidenceForTest()).toEqual({
retainedGenerationLeases: 0,
retainedTargetIdBytes: 0,
trackedTargets: 0
})
})
it('keeps an entry until its final ownership lease releases', () => {
const activeLease = retainSshConnectionGeneration('ssh-a')
const inFlightLease = retainSshConnectionGeneration('ssh-a')
const generation = getSshConnectionGeneration('ssh-a')
activeLease.release()
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', generation)).not.toThrow()
inFlightLease.release()
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', generation)).toThrow(
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', Number.MAX_SAFE_INTEGER)).toThrow(
'SSH connection changed; refresh and try again'
)
})
it('never reuses a released target token during sequential churn', () => {
let previous = 0
for (let index = 0; index < 10_000; index += 1) {
const lease = retainSshConnectionGeneration(`ssh-${index}`)
const generation = getSshConnectionGeneration(`ssh-${index}`)
expect(generation).toBeGreaterThan(previous)
previous = generation
lease.release()
}
expect(_internals.evidenceForTest()).toEqual({
retainedGenerationLeases: 0,
retainedTargetIdBytes: 0,
trackedTargets: 0
})
})
it('bounds outstanding leases for one hung target', () => {
const leases = Array.from({ length: MAX_RETAINED_SSH_CONNECTION_GENERATION_LEASES }, () =>
retainSshConnectionGeneration('ssh-a')
)
const generation = getSshConnectionGeneration('ssh-a')
expect(() => retainSshConnectionGeneration('ssh-a')).toThrow(
'SSH connection generation lease capacity exhausted'
)
expect(getSshConnectionGeneration('ssh-a')).toBe(generation)
expect(() => assertSshMutationExpectation('ssh-a', 'ssh-a', generation)).not.toThrow()
expect(_internals.evidenceForTest()).toEqual({
retainedGenerationLeases: MAX_RETAINED_SSH_CONNECTION_GENERATION_LEASES,
retainedTargetIdBytes: 5,
trackedTargets: 1
})
for (const lease of leases) {
lease.release()
}
expect(_internals.evidenceForTest()).toEqual({
retainedGenerationLeases: 0,
retainedTargetIdBytes: 0,
trackedTargets: 0
})
})
it('bounds individual and aggregate retained target-id bytes', () => {
expect(() =>
retainSshConnectionGeneration('x'.repeat(MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES + 1))
).toThrow('SSH connection generation target id exceeds')
const leases = Array.from(
{
length:
MAX_SSH_CONNECTION_GENERATION_RETAINED_TARGET_ID_BYTES /
MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES
},
(_, index) => {
const prefix = `${index}:`
return retainSshConnectionGeneration(
prefix + 'x'.repeat(MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES - prefix.length)
)
}
)
expect(() => retainSshConnectionGeneration('overflow')).toThrow(
'SSH connection generation target capacity exhausted'
)
for (const lease of leases) {
lease.release()
}
expect(_internals.evidenceForTest()).toEqual({
retainedGenerationLeases: 0,
retainedTargetIdBytes: 0,
trackedTargets: 0
})
})
})
+36 -159
View File
@@ -1,184 +1,77 @@
import { randomBytes } from 'node:crypto'
import { toSshExecutionHostId } from '../../shared/execution-host'
import { measureUtf8ByteLength } from '../../shared/utf8-byte-limits'
const SESSION_COUNTER_BITS = 13
const SESSION_COUNTER_STRIDE = 2 ** SESSION_COUNTER_BITS
const MAX_SESSION_SCOPE = 2 ** (53 - SESSION_COUNTER_BITS) - 1
export const MAX_TRACKED_SSH_CONNECTION_GENERATIONS = 4_096
export const MAX_RETAINED_SSH_CONNECTION_GENERATION_LEASES = 8_192
export const MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES = 64 * 1024
export const MAX_SSH_CONNECTION_GENERATION_RETAINED_TARGET_ID_BYTES = 4 * 1024 * 1024
type SshConnectionGenerationEntry = {
generation: number
leaseCount: number
targetIdBytes: number
}
export type SshConnectionGenerationLease = {
release: () => void
}
function createSessionScope(): number {
return randomBytes(5).readUIntBE(0, 5)
}
let allocationSessionBase = 0
let allocationSessionCounter = 0
let sessionGenerationBase = 0
let sessionInitialized = false
let allocatedSessionScopeCount = 1
let generationRegistryEpoch = 0
let retainedGenerationLeases = 0
let retainedTargetIdBytes = 0
const connectionGenerationByTarget = new Map<string, SshConnectionGenerationEntry>()
const connectionGenerationByTarget = new Map<string, number>()
const usedSessionScopes = new Set<number>()
function rotateAllocationSessionScope(): void {
if (allocatedSessionScopeCount >= MAX_SESSION_SCOPE + 1) {
function assertGenerationInCurrentSession(generation: number): void {
if (
!Number.isSafeInteger(generation) ||
generation < sessionGenerationBase ||
generation - sessionGenerationBase >= SESSION_COUNTER_STRIDE
) {
throw new Error('SSH connection generation exhausted for this runtime session')
}
const nextSessionScope =
(allocationSessionBase / SESSION_COUNTER_STRIDE + 1) % (MAX_SESSION_SCOPE + 1)
allocationSessionBase = nextSessionScope * SESSION_COUNTER_STRIDE
allocationSessionCounter = 0
allocatedSessionScopeCount += 1
}
function allocateGeneration(): number {
if (allocationSessionCounter >= SESSION_COUNTER_STRIDE - 1) {
rotateAllocationSessionScope()
}
allocationSessionCounter += 1
const generation = allocationSessionBase + allocationSessionCounter
if (!Number.isSafeInteger(generation)) {
throw new Error('SSH connection generation exhausted for this runtime session')
}
return generation
}
function measureTargetId(targetId: string): number {
const measured = measureUtf8ByteLength(targetId, {
stopAfterBytes: MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES
})
if (measured.exceededLimit) {
throw new Error(
`SSH connection generation target id exceeds ${MAX_SSH_CONNECTION_GENERATION_TARGET_ID_BYTES} UTF-8 bytes`
)
}
return measured.byteLength
}
export function retainSshConnectionGeneration(targetId: string): SshConnectionGenerationLease {
if (retainedGenerationLeases >= MAX_RETAINED_SSH_CONNECTION_GENERATION_LEASES) {
throw new Error('SSH connection generation lease capacity exhausted')
}
let entry = connectionGenerationByTarget.get(targetId)
if (!entry) {
const targetIdBytes = measureTargetId(targetId)
if (
connectionGenerationByTarget.size >= MAX_TRACKED_SSH_CONNECTION_GENERATIONS ||
retainedTargetIdBytes + targetIdBytes > MAX_SSH_CONNECTION_GENERATION_RETAINED_TARGET_ID_BYTES
) {
throw new Error('SSH connection generation target capacity exhausted')
}
entry = {
generation: allocateGeneration(),
leaseCount: 0,
targetIdBytes
}
connectionGenerationByTarget.set(targetId, entry)
retainedTargetIdBytes += targetIdBytes
}
entry.leaseCount += 1
retainedGenerationLeases += 1
const retainedEntry = entry
const retainedEpoch = generationRegistryEpoch
let retained = true
return {
release: () => {
if (!retained) {
return
}
retained = false
retainedEntry.leaseCount -= 1
if (generationRegistryEpoch === retainedEpoch) {
retainedGenerationLeases -= 1
}
if (
retainedEntry.leaseCount === 0 &&
connectionGenerationByTarget.get(targetId) === retainedEntry
) {
connectionGenerationByTarget.delete(targetId)
retainedTargetIdBytes -= retainedEntry.targetIdBytes
}
}
}
}
export function getSshConnectionGeneration(targetId: string): number {
return connectionGenerationByTarget.get(targetId)?.generation ?? allocationSessionBase
return connectionGenerationByTarget.get(targetId) ?? sessionGenerationBase
}
export function initializeSshConnectionGenerationSession(): void {
if (sessionInitialized) {
return
}
allocationSessionBase = createSessionScope() * SESSION_COUNTER_STRIDE
allocationSessionCounter = 0
allocatedSessionScopeCount = 1
const sessionScope = createSessionScope()
// Why: randomize the process scope so a replacement HUB does not predictably reuse the prior target/counter token.
sessionGenerationBase = sessionScope * SESSION_COUNTER_STRIDE
usedSessionScopes.add(sessionScope)
sessionInitialized = true
}
export function advanceSshConnectionGeneration(targetId: string): number | null {
const entry = connectionGenerationByTarget.get(targetId)
if (!entry) {
return null
export function advanceSshConnectionGeneration(targetId: string): number {
let next = getSshConnectionGeneration(targetId) + 1
if (next - sessionGenerationBase >= SESSION_COUNTER_STRIDE) {
let nextSessionScope =
(sessionGenerationBase / SESSION_COUNTER_STRIDE + 1) % (MAX_SESSION_SCOPE + 1)
while (usedSessionScopes.has(nextSessionScope)) {
nextSessionScope = (nextSessionScope + 1) % (MAX_SESSION_SCOPE + 1)
}
usedSessionScopes.add(nextSessionScope)
sessionGenerationBase = nextSessionScope * SESSION_COUNTER_STRIDE
// Why: changing the scope must revoke tokens for every target, not only the target that exhausted its counter.
connectionGenerationByTarget.clear()
next = sessionGenerationBase + 1
}
entry.generation = allocateGeneration()
return entry.generation
assertGenerationInCurrentSession(next)
connectionGenerationByTarget.set(targetId, next)
return next
}
export function setSshConnectionGeneration(targetId: string, generation: number): void {
const generationOffset = generation - allocationSessionBase
if (
!Number.isSafeInteger(generation) ||
generationOffset < 0 ||
generationOffset >= SESSION_COUNTER_STRIDE
) {
throw new Error('SSH connection generation exhausted for this runtime session')
}
let entry = connectionGenerationByTarget.get(targetId)
if (!entry) {
const targetIdBytes = measureTargetId(targetId)
if (
retainedGenerationLeases >= MAX_RETAINED_SSH_CONNECTION_GENERATION_LEASES ||
connectionGenerationByTarget.size >= MAX_TRACKED_SSH_CONNECTION_GENERATIONS ||
retainedTargetIdBytes + targetIdBytes > MAX_SSH_CONNECTION_GENERATION_RETAINED_TARGET_ID_BYTES
) {
throw new Error('SSH connection generation target capacity exhausted')
}
entry = { generation, leaseCount: 1, targetIdBytes }
connectionGenerationByTarget.set(targetId, entry)
retainedGenerationLeases += 1
retainedTargetIdBytes += targetIdBytes
} else {
entry.generation = generation
}
allocationSessionCounter = Math.max(allocationSessionCounter, generationOffset)
assertGenerationInCurrentSession(generation)
connectionGenerationByTarget.set(targetId, generation)
}
export function resetSshConnectionGenerations(sessionScope = 0): void {
if (!Number.isSafeInteger(sessionScope) || sessionScope < 0 || sessionScope > MAX_SESSION_SCOPE) {
throw new Error('Invalid SSH connection generation session scope')
}
allocationSessionBase = sessionScope * SESSION_COUNTER_STRIDE
allocationSessionCounter = 0
sessionGenerationBase = sessionScope * SESSION_COUNTER_STRIDE
sessionInitialized = true
allocatedSessionScopeCount = 1
generationRegistryEpoch += 1
retainedGenerationLeases = 0
retainedTargetIdBytes = 0
connectionGenerationByTarget.clear()
usedSessionScopes.clear()
usedSessionScopes.add(sessionScope)
}
export function assertSshMutationExpectation(
@@ -198,27 +91,11 @@ export function assertSshMutationExpectation(
}
return
}
const current = connectionGenerationByTarget.get(connectionId)
if (
expectedTargetId !== connectionId ||
expectedGeneration === undefined ||
!current ||
expectedGeneration !== current.generation
expectedGeneration !== getSshConnectionGeneration(connectionId)
) {
throw new Error('SSH connection changed; refresh and try again')
}
}
export const _internals = {
evidenceForTest(): {
retainedGenerationLeases: number
retainedTargetIdBytes: number
trackedTargets: number
} {
return {
retainedGenerationLeases,
retainedTargetIdBytes,
trackedTargets: connectionGenerationByTarget.size
}
}
}
+4 -32
View File
@@ -24,11 +24,8 @@ function testHomePath(...parts: string[]): string {
}
vi.mock('fs', () => ({
existsSync: (...args: unknown[]) => mockExistsSync(...args)
}))
vi.mock('./ssh-key-file', () => ({
readSshKeyFile: (...args: unknown[]) => mockReadFileSync(...args)
existsSync: (...args: unknown[]) => mockExistsSync(...args),
readFileSync: (...args: unknown[]) => mockReadFileSync(...args)
}))
import {
@@ -54,10 +51,7 @@ import type { SshResolvedConfig } from './ssh-config-parser'
type MockProxyProcess = EventEmitter & {
stdin: EventEmitter & { write: ReturnType<typeof vi.fn> }
stdout: EventEmitter & {
pause: ReturnType<typeof vi.fn>
resume: ReturnType<typeof vi.fn>
}
stdout: EventEmitter
stderr: EventEmitter
}
@@ -66,10 +60,7 @@ function createMockProxyProcess(): MockProxyProcess {
proc.stdin = Object.assign(new EventEmitter(), {
write: vi.fn((_chunk, cb?: (error?: Error | null) => void) => cb?.())
})
proc.stdout = Object.assign(new EventEmitter(), {
pause: vi.fn(),
resume: vi.fn()
})
proc.stdout = new EventEmitter()
proc.stderr = new EventEmitter()
return proc
}
@@ -732,23 +723,4 @@ describe('spawnProxyCommand', () => {
expect(proc.stdin.listenerCount('error')).toBe(0)
expect(proc.listenerCount('error')).toBe(0)
})
it('pauses proxy stdout at the socket high-water mark and resumes on demand', async () => {
const proc = createMockProxyProcess()
spawnMock.mockReturnValue(proc)
const { sock } = spawnProxyCommand(
{ kind: 'jump-host', jumpHost: 'bastion.example.com' },
'target.example.com',
22,
'deploy'
)
proc.stdout.emit('data', Buffer.alloc(64 * 1024))
expect(proc.stdout.pause).toHaveBeenCalledOnce()
sock.on('data', () => {})
await new Promise<void>((resolve) => setImmediate(resolve))
expect(proc.stdout.resume).toHaveBeenCalled()
sock.destroy()
})
})
+2 -6
View File
@@ -311,9 +311,7 @@ export function spawnProxyCommand(
proc.off('error', onProcessError)
}
const onStdoutData = (data: Buffer): void => {
if (!stream.push(data)) {
proc.stdout!.pause()
}
stream.push(data)
}
const onStdoutEnd = (): void => {
stream.push(null)
@@ -325,9 +323,7 @@ export function spawnProxyCommand(
stream.destroy(err)
}
const stream = new Duplex({
read() {
proc.stdout!.resume()
},
read() {},
write(chunk, _encoding, cb) {
proc.stdin!.write(chunk, cb)
},
-11
View File
@@ -168,7 +168,6 @@ import {
} from './ssh-system-fallback'
import { getRemoteHostPlatform } from './ssh-remote-platform'
import type { SshTarget } from '../../shared/ssh-types'
import { SSH_CONNECTION_ERROR_MAX_UTF8_BYTES } from '../../shared/ssh-retained-payload-admission'
function createTarget(overrides?: Partial<SshTarget>): SshTarget {
return {
@@ -437,16 +436,6 @@ describe('SshConnection', () => {
expect(conn.getState().status).toBe('error')
})
it('does not retain an oversized provider error in connection state', async () => {
connectBehavior = 'error'
connectErrorMessage = 'x'.repeat(SSH_CONNECTION_ERROR_MAX_UTF8_BYTES + 100)
const conn = new SshConnection(createTarget(), createCallbacks())
await conn.connect().catch(() => undefined)
expect(conn.getState().error).toHaveLength(SSH_CONNECTION_ERROR_MAX_UTF8_BYTES)
})
it('guards late ssh2 errors emitted while destroying a failed startup client', async () => {
connectBehavior = 'error'
connectErrorMessage = 'Connection lost before handshake'
+7 -10
View File
@@ -5,7 +5,6 @@ import { Client as SshClient } from 'ssh2'
import type { ChildProcess } from 'node:child_process'
import type { ClientChannel, ConnectConfig, SFTPWrapper } from 'ssh2'
import type { SshTarget, SshConnectionState, SshConnectionStatus } from '../../shared/ssh-types'
import { clampSshConnectionError } from '../../shared/ssh-retained-payload-admission'
import {
getOrcaControlSocketPath,
spawnSystemSsh,
@@ -47,7 +46,6 @@ import {
createLinkedSshFileTransferSignal,
raceSftpFileTransferWithAbort
} from './ssh-file-transfer-abort'
import { SystemSshOutputTail } from './system-ssh-output-tail'
export type { SshConnectionCallbacks } from './ssh-connection-utils'
type SshRemoteFileOptions = {
@@ -815,8 +813,8 @@ export class SshConnection {
})
try {
await new Promise<void>((resolve, reject) => {
const stdout = new SystemSshOutputTail()
const stderr = new SystemSshOutputTail()
let stdout = ''
let stderr = ''
let settled = false
const cleanup = (): void => {
clearTimeout(timeout)
@@ -835,10 +833,10 @@ export class SshConnection {
callback()
}
const onStdoutData = (data: Buffer): void => {
stdout.push(data)
stdout += data.toString('utf-8')
}
const onStderrData = (data: Buffer): void => {
stderr.push(data)
stderr += data.toString('utf-8')
}
const onError = (err: Error): void => {
settle(() => reject(err))
@@ -849,11 +847,10 @@ export class SshConnection {
reject(new Error('SSH connection attempt was cancelled'))
return
}
if (code !== 0 || !stdout.toString().includes('ORCA-SYSTEM-SSH-OK')) {
const stderrText = stderr.toString()
if (code !== 0 || !stdout.includes('ORCA-SYSTEM-SSH-OK')) {
reject(
new Error(
`System SSH probe failed${code != null ? ` (exit ${code})` : ''}.${stderrText ? ` stderr: ${stderrText.trim()}` : ''}`
`System SSH probe failed${code != null ? ` (exit ${code})` : ''}.${stderr ? ` stderr: ${stderr.trim()}` : ''}`
)
)
return
@@ -1330,7 +1327,7 @@ export class SshConnection {
this.state = {
...this.state,
status,
error: clampSshConnectionError(error ?? null),
error: error ?? null,
supportsFolderDownload: status === 'connected' && !this.useSystemSshTransport
}
this.callbacks.onStateChange(this.target.id, { ...this.state })
@@ -1,51 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
SshDirectoryTransferBudget,
type SshDirectoryTransferLimits
} from './ssh-directory-transfer-budget'
const limits: SshDirectoryTransferLimits = {
maximumEntries: 2,
maximumDepth: 2,
maximumPathBytes: 4,
maximumRetainedPathBytes: 8,
maximumFileBytes: 4,
maximumTotalFileBytes: 8
}
describe('SshDirectoryTransferBudget', () => {
it('accepts every exact boundary', () => {
const budget = new SshDirectoryTransferBudget(limits)
budget.recordPath('1234', 2)
budget.recordPath('5678', 2)
budget.recordFile(4)
budget.recordFile(4)
})
it.each([
['entries', (budget: SshDirectoryTransferBudget) => budget.recordPath('', 0)],
['depth', (budget: SshDirectoryTransferBudget) => budget.recordPath('', 3)],
['path', (budget: SshDirectoryTransferBudget) => budget.recordPath('12345', 0)],
[
'paths',
(budget: SshDirectoryTransferBudget) => budget.recordPath('1', 0, { countEntry: false })
],
['file', (budget: SshDirectoryTransferBudget) => budget.recordFile(5)],
['files', (budget: SshDirectoryTransferBudget) => budget.recordFile(1)]
] as const)('rejects one unit beyond the %s boundary', (reason, exceed) => {
const budget = new SshDirectoryTransferBudget(limits)
if (reason === 'entries') {
budget.recordPath('', 0)
budget.recordPath('', 0)
} else if (reason === 'paths') {
budget.recordPath('1234', 0, { countEntry: false })
budget.recordPath('5678', 0, { countEntry: false })
} else if (reason === 'files') {
budget.recordFile(4)
budget.recordFile(4)
}
expect(() => exceed(budget)).toThrow(expect.objectContaining({ reason }))
})
})
@@ -1,64 +0,0 @@
export type SshDirectoryTransferLimits = {
maximumEntries: number
maximumDepth: number
maximumPathBytes: number
maximumRetainedPathBytes: number
maximumFileBytes: number
maximumTotalFileBytes: number
}
export const SSH_DIRECTORY_TRANSFER_LIMITS: SshDirectoryTransferLimits = {
maximumEntries: 4_096,
maximumDepth: 64,
maximumPathBytes: 16 * 1024,
maximumRetainedPathBytes: 4 * 1024 * 1024,
maximumFileBytes: 16 * 1024 * 1024,
maximumTotalFileBytes: 32 * 1024 * 1024
}
export const WINDOWS_SSH_UPLOAD_PACKAGE_MAX_BYTES = 48 * 1024 * 1024
export class SshDirectoryTransferCapacityError extends Error {
constructor(readonly reason: 'entries' | 'depth' | 'path' | 'paths' | 'file' | 'files') {
super(`SSH directory transfer exceeds the ${reason} limit`)
this.name = 'SshDirectoryTransferCapacityError'
}
}
export class SshDirectoryTransferBudget {
private entries = 0
private retainedPathBytes = 0
private totalFileBytes = 0
constructor(private readonly limits = SSH_DIRECTORY_TRANSFER_LIMITS) {}
recordPath(path: string, depth: number, options?: { countEntry?: boolean }): void {
if (depth > this.limits.maximumDepth) {
throw new SshDirectoryTransferCapacityError('depth')
}
if (options?.countEntry !== false) {
this.entries += 1
if (this.entries > this.limits.maximumEntries) {
throw new SshDirectoryTransferCapacityError('entries')
}
}
const pathBytes = Buffer.byteLength(path, 'utf8')
if (pathBytes > this.limits.maximumPathBytes) {
throw new SshDirectoryTransferCapacityError('path')
}
this.retainedPathBytes += pathBytes
if (this.retainedPathBytes > this.limits.maximumRetainedPathBytes) {
throw new SshDirectoryTransferCapacityError('paths')
}
}
recordFile(fileBytes: number): void {
if (fileBytes > this.limits.maximumFileBytes) {
throw new SshDirectoryTransferCapacityError('file')
}
this.totalFileBytes += fileBytes
if (this.totalFileBytes > this.limits.maximumTotalFileBytes) {
throw new SshDirectoryTransferCapacityError('files')
}
}
}
-196
View File
@@ -1,196 +0,0 @@
import type { FileReadResult } from '../providers/types'
import { RelayErrorCode, STREAM_CHUNK_SIZE } from './relay-protocol'
import {
defaultSshStreamAssemblyBudget,
type SshStreamAssemblyBudget,
base64EncodedLength
} from './ssh-stream-reader-memory'
import type { RasterImageDimensions } from '../../shared/raster-image-dimensions'
import { isRasterImagePreviewDimensions } from '../../shared/raster-image-preview-limits'
const MAX_PREVIEWABLE_BINARY_SIZE = 50 * 1024 * 1024
const MAX_TEXT_FILE_SIZE = 10 * 1024 * 1024
type FileStreamMetadata = {
streamId?: number
totalSize: number
isBinary: boolean
isImage?: boolean
mimeType?: string
imageDimensions?: RasterImageDimensions
resultEncoding?: 'base64' | 'utf-8'
empty?: boolean
}
export class StreamProtocolError extends Error {
readonly code = RelayErrorCode.StreamProtocolError
constructor(message: string) {
super(message)
}
}
export type FileStreamSetup =
| { kind: 'empty'; result: FileReadResult }
| { kind: 'stream'; streamId: number; assembler: FileStreamAssembler }
export function createFileStreamSetup(
rawMetadata: unknown,
assemblyBudget: SshStreamAssemblyBudget = defaultSshStreamAssemblyBudget
): FileStreamSetup {
const metadata = rawMetadata as FileStreamMetadata
if (
typeof metadata !== 'object' ||
metadata === null ||
typeof metadata.isBinary !== 'boolean' ||
!Number.isSafeInteger(metadata.totalSize) ||
(metadata.empty !== undefined && typeof metadata.empty !== 'boolean') ||
(metadata.isImage !== undefined && typeof metadata.isImage !== 'boolean') ||
(metadata.mimeType !== undefined && typeof metadata.mimeType !== 'string') ||
(metadata.imageDimensions !== undefined &&
!isRasterImagePreviewDimensions(metadata.imageDimensions)) ||
(metadata.resultEncoding !== undefined &&
metadata.resultEncoding !== 'base64' &&
metadata.resultEncoding !== 'utf-8')
) {
throw new StreamProtocolError('Malformed file stream metadata')
}
if (metadata.empty) {
return {
kind: 'empty',
result: {
content: '',
isBinary: metadata.isBinary,
...(metadata.isImage !== undefined ? { isImage: metadata.isImage } : {}),
...(metadata.mimeType !== undefined ? { mimeType: metadata.mimeType } : {}),
...(metadata.imageDimensions !== undefined
? { imageDimensions: metadata.imageDimensions }
: {})
}
}
}
if (
typeof metadata.streamId !== 'number' ||
!Number.isSafeInteger(metadata.streamId) ||
metadata.streamId <= 0
) {
throw new StreamProtocolError('Metadata missing streamId for non-empty stream')
}
const cap = metadata.isBinary ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_TEXT_FILE_SIZE
if (metadata.totalSize < 0 || metadata.totalSize > cap) {
throw new StreamProtocolError(
`Reported totalSize ${metadata.totalSize} exceeds client cap ${cap}`
)
}
return {
kind: 'stream',
streamId: metadata.streamId,
assembler: new FileStreamAssembler(metadata, assemblyBudget)
}
}
export class FileStreamAssembler {
private buffer: Buffer | null
private expectedSeq = 0
private bytesReceived = 0
private readonly totalChunks: number
private releaseBudget: (() => void) | null
constructor(
private readonly metadata: FileStreamMetadata,
assemblyBudget: SshStreamAssemblyBudget
) {
this.releaseBudget = assemblyBudget.reserve(metadata.totalSize)
if (!this.releaseBudget) {
throw new StreamProtocolError(
`Active SSH stream assembly would exceed ${assemblyBudget.maxBytes} bytes`
)
}
try {
this.buffer = Buffer.alloc(metadata.totalSize)
} catch (error) {
this.releaseMemory()
throw new StreamProtocolError(
`Failed to allocate ${metadata.totalSize} bytes: ${(error as Error).message}`
)
}
this.totalChunks =
metadata.totalSize === 0 ? 0 : Math.ceil(metadata.totalSize / STREAM_CHUNK_SIZE)
}
acceptChunk(params: Record<string, unknown>, streamId: number): number {
const seq = params.seq
const data = params.data
if (typeof seq !== 'number' || !Number.isSafeInteger(seq) || typeof data !== 'string') {
throw new StreamProtocolError(`Malformed chunk for stream ${streamId}`)
}
if (seq !== this.expectedSeq) {
throw new StreamProtocolError(
`Out-of-order chunk for stream ${streamId}: expected ${this.expectedSeq}, got ${seq}`
)
}
if (seq >= this.totalChunks) {
throw new StreamProtocolError(
`File stream ${streamId} exceeded declared chunk count ${this.totalChunks}`
)
}
const offset = seq * STREAM_CHUNK_SIZE
const expectedLength = Math.min(STREAM_CHUNK_SIZE, this.metadata.totalSize - offset)
if (expectedLength < 0 || data.length !== base64EncodedLength(expectedLength)) {
throw new StreamProtocolError(
`Encoded chunk length mismatch for stream ${streamId}: seq=${seq}`
)
}
const decoded = Buffer.from(data, 'base64')
if (decoded.length !== expectedLength) {
throw new StreamProtocolError(
`Chunk length mismatch for stream ${streamId}: seq=${seq} expected=${expectedLength} got=${decoded.length}`
)
}
if (!this.buffer) {
throw new StreamProtocolError(`Chunk arrived after completion for stream ${streamId}`)
}
decoded.copy(this.buffer, offset)
this.expectedSeq += 1
this.bytesReceived += decoded.length
return seq
}
finish(streamId: number): FileReadResult {
if (this.expectedSeq !== this.totalChunks || this.bytesReceived !== this.metadata.totalSize) {
throw new StreamProtocolError(
`File stream ${streamId} incomplete: chunks ${this.expectedSeq}/${this.totalChunks}, bytes ${this.bytesReceived}/${this.metadata.totalSize}`
)
}
if (!this.buffer) {
throw new StreamProtocolError(`Stream ${streamId} already completed`)
}
const buffer = this.buffer
this.buffer = null
try {
return {
content:
(this.metadata.resultEncoding ?? 'base64') === 'base64'
? buffer.toString('base64')
: buffer.toString('utf-8'),
isBinary: this.metadata.isBinary,
...(this.metadata.isImage !== undefined ? { isImage: this.metadata.isImage } : {}),
...(this.metadata.mimeType !== undefined ? { mimeType: this.metadata.mimeType } : {}),
...(this.metadata.imageDimensions !== undefined
? { imageDimensions: this.metadata.imageDimensions }
: {})
}
} finally {
this.releaseMemory()
}
}
release(): void {
this.buffer = null
this.releaseMemory()
}
private releaseMemory(): void {
this.releaseBudget?.()
this.releaseBudget = null
}
}
+146 -97
View File
@@ -1,25 +1,23 @@
import type { SshChannelMultiplexer } from './ssh-channel-multiplexer'
import { JsonRpcErrorCode } from './relay-protocol'
import { STREAM_CHUNK_SIZE, JsonRpcErrorCode, RelayErrorCode } from './relay-protocol'
import type { FileReadResult } from '../providers/types'
import {
PreMetadataStreamFrameBuffer,
STREAM_READER_INACTIVITY_TIMEOUT_MS,
defaultSshPreMetadataStreamBudget,
defaultSshStreamAssemblyBudget,
type SshPreMetadataStreamBudget,
type SshStreamAssemblyBudget,
createStreamInactivityDeadline
} from './ssh-stream-reader-memory'
import {
createFileStreamSetup,
type FileStreamAssembler,
StreamProtocolError
} from './ssh-file-stream-assembler'
export { StreamProtocolError } from './ssh-file-stream-assembler'
const RESULT_ENCODING_BASE64 = 'base64'
const SENTINEL_STREAM_ID = -1
const MAX_PREVIEWABLE_BINARY_SIZE = 50 * 1024 * 1024
const MAX_TEXT_FILE_SIZE = 10 * 1024 * 1024
type StreamMetadataResponse = {
streamId?: number
totalSize: number
isBinary: boolean
isImage?: boolean
mimeType?: string
resultEncoding?: 'base64' | 'utf-8'
empty?: boolean
}
export function isMethodNotFoundError(err: unknown): boolean {
if (!err || typeof err !== 'object') {
return false
@@ -28,12 +26,16 @@ export function isMethodNotFoundError(err: unknown): boolean {
return code === JsonRpcErrorCode.MethodNotFound
}
export class StreamProtocolError extends Error {
readonly code = RelayErrorCode.StreamProtocolError
constructor(message: string) {
super(message)
}
}
export async function readFileViaStream(
mux: SshChannelMultiplexer,
filePath: string,
options?: { inactivityTimeoutMs?: number },
assemblyBudget: SshStreamAssemblyBudget = defaultSshStreamAssemblyBudget,
preMetadataBudget: SshPreMetadataStreamBudget = defaultSshPreMetadataStreamBudget
filePath: string
): Promise<FileReadResult> {
// Why: subscribe BEFORE awaiting the metadata response so a chunk arriving
// immediately after the response cannot beat the listener registration.
@@ -53,44 +55,42 @@ export async function readFileViaStream(
}
return new Promise<FileReadResult>((resolve, reject) => {
let assembler: FileStreamAssembler | null = null
let buffer: Buffer | null = null
let resultEncoding: 'base64' | 'utf-8' = RESULT_ENCODING_BASE64
let isBinary = false
let isImage: boolean | undefined
let mimeType: string | undefined
let totalSize = 0
let expectedSeq = 0
let receivedChunks = 0
let totalChunks = 0
let bytesReceived = 0
let settled = false
// Why: chunk/end/error frames may arrive in the same dispatch tick as the
// metadata response. Queue them until streamIdRef is set, then drain.
const pending = new PreMetadataStreamFrameBuffer(preMetadataBudget)
type PendingFrame =
| { kind: 'chunk'; params: Record<string, unknown> }
| { kind: 'end'; params: Record<string, unknown> }
| { kind: 'error'; params: Record<string, unknown> }
const pending: PendingFrame[] = []
let metadataReady = false
const inactivityMs = options?.inactivityTimeoutMs ?? STREAM_READER_INACTIVITY_TIMEOUT_MS
const inactivity = createStreamInactivityDeadline(inactivityMs, () => {
fail(new StreamProtocolError(`File stream stalled (>${inactivityMs}ms without data)`))
})
const cancelStreamId = (streamId: number): void => {
if (!mux.isDisposed()) {
const cancel = (): void => {
if (streamIdRef.current !== SENTINEL_STREAM_ID && !mux.isDisposed()) {
try {
mux.notify('fs.cancelStream', { streamId })
mux.notify('fs.cancelStream', { streamId: streamIdRef.current })
} catch {
// Best-effort
}
}
}
const cancel = (): void => {
if (streamIdRef.current !== SENTINEL_STREAM_ID) {
cancelStreamId(streamIdRef.current)
}
}
const fail = (err: Error): void => {
if (settled) {
return
}
settled = true
inactivity.clear()
pending.clear()
assembler?.release()
assembler = null
cancel()
cleanup()
reject(err)
@@ -101,8 +101,6 @@ export async function readFileViaStream(
return
}
settled = true
inactivity.clear()
pending.clear()
cleanup()
resolve(value)
}
@@ -115,26 +113,45 @@ export async function readFileViaStream(
if (id !== streamIdRef.current) {
return
}
if (!assembler) {
const seq = params.seq as number
const data = params.data as string
if (typeof seq !== 'number' || typeof data !== 'string') {
fail(new StreamProtocolError(`Malformed chunk for stream ${id}`))
return
}
if (seq !== expectedSeq) {
fail(
new StreamProtocolError(
`Out-of-order chunk for stream ${id}: expected ${expectedSeq}, got ${seq}`
)
)
return
}
const offset = seq * STREAM_CHUNK_SIZE
const decoded = Buffer.from(data, 'base64')
// Why: a short chunk would leave the pre-allocated buffer zero-filled and
// resolve as silently-corrupt data; validate each chunk's exact length.
const expectedLength = Math.min(STREAM_CHUNK_SIZE, totalSize - offset)
if (decoded.length !== expectedLength) {
fail(
new StreamProtocolError(
`Chunk length mismatch for stream ${id}: seq=${seq} expected=${expectedLength} got=${decoded.length}`
)
)
return
}
if (!buffer) {
fail(new StreamProtocolError(`Chunk arrived before metadata for stream ${id}`))
return
}
let seq: number
try {
seq = assembler.acceptChunk(params, id)
} catch (error) {
fail(error as Error)
return
}
inactivity.reset()
decoded.copy(buffer, offset)
expectedSeq += 1
receivedChunks += 1
bytesReceived += decoded.length
// Why: credit-based flow control — the relay caps unacked chunks so bulk
// stream frames cannot queue unbounded ahead of interactive pty.data
// frames on the shared SSH channel. Old relays ignore this notification.
try {
mux.notify('fs.streamAck', { streamId: id, seq })
} catch {
// Disposal can race the write; teardown will settle the reader.
}
mux.notify('fs.streamAck', { streamId: id, seq })
}
const handleEnd = (params: Record<string, unknown>): void => {
@@ -145,15 +162,38 @@ export async function readFileViaStream(
if (id !== streamIdRef.current) {
return
}
if (!assembler) {
if (receivedChunks !== totalChunks) {
fail(
new StreamProtocolError(
`Chunk count mismatch for stream ${id}: expected ${totalChunks}, received ${receivedChunks}`
)
)
return
}
// Why: redundant given the per-chunk length + count checks, but kept as a
// last-line invariant guard; never resolve with fewer bytes than declared.
if (bytesReceived !== totalSize) {
fail(
new StreamProtocolError(
`Byte count mismatch for stream ${id}: expected ${totalSize}, received ${bytesReceived}`
)
)
return
}
if (!buffer) {
fail(new StreamProtocolError(`Stream end before metadata for stream ${id}`))
return
}
try {
succeed(assembler.finish(id))
} catch (error) {
fail(error as Error)
}
const content =
resultEncoding === RESULT_ENCODING_BASE64
? buffer.toString('base64')
: buffer.toString('utf-8')
succeed({
content,
isBinary,
...(isImage !== undefined ? { isImage } : {}),
...(mimeType !== undefined ? { mimeType } : {})
})
}
const handleStreamError = (params: Record<string, unknown>): void => {
@@ -173,10 +213,7 @@ export async function readFileViaStream(
const drainPending = (): void => {
while (!settled && pending.length > 0) {
const frame = pending.shift()
if (!frame) {
break
}
const frame = pending.shift()!
if (frame.kind === 'chunk') {
handleChunk(frame.params)
} else if (frame.kind === 'end') {
@@ -187,18 +224,10 @@ export async function readFileViaStream(
}
}
const pushPending = (
kind: 'chunk' | 'end' | 'error',
params: Record<string, unknown>
): void => {
// Why: the stream id is unknown here; overload drops must not let one foreign frame fail every reader.
pending.push({ kind, params })
}
unsubscribers.push(
mux.onNotificationByMethod('fs.streamChunk', (params) => {
if (!metadataReady) {
pushPending('chunk', params)
pending.push({ kind: 'chunk', params })
return
}
handleChunk(params)
@@ -207,7 +236,7 @@ export async function readFileViaStream(
unsubscribers.push(
mux.onNotificationByMethod('fs.streamEnd', (params) => {
if (!metadataReady) {
pushPending('end', params)
pending.push({ kind: 'end', params })
return
}
handleEnd(params)
@@ -216,7 +245,7 @@ export async function readFileViaStream(
unsubscribers.push(
mux.onNotificationByMethod('fs.streamError', (params) => {
if (!metadataReady) {
pushPending('error', params)
pending.push({ kind: 'error', params })
return
}
handleStreamError(params)
@@ -240,31 +269,51 @@ export async function readFileViaStream(
.request('fs.readFileStream', { filePath, flowControl: 'ack' })
.then((rawMetadata) => {
if (settled) {
const streamId = (rawMetadata as { streamId?: unknown } | null)?.streamId
if (typeof streamId === 'number') {
cancelStreamId(streamId)
}
return
}
let setup
const metadata = rawMetadata as StreamMetadataResponse
isBinary = metadata.isBinary
isImage = metadata.isImage
mimeType = metadata.mimeType
resultEncoding = metadata.resultEncoding ?? RESULT_ENCODING_BASE64
if (metadata.empty) {
succeed({
content: '',
isBinary: metadata.isBinary,
...(metadata.isImage !== undefined ? { isImage: metadata.isImage } : {}),
...(metadata.mimeType !== undefined ? { mimeType: metadata.mimeType } : {})
})
return
}
if (typeof metadata.streamId !== 'number') {
fail(new StreamProtocolError('Metadata missing streamId for non-empty stream'))
return
}
const cap = metadata.isBinary ? MAX_PREVIEWABLE_BINARY_SIZE : MAX_TEXT_FILE_SIZE
if (metadata.totalSize < 0 || metadata.totalSize > cap) {
streamIdRef.current = metadata.streamId
fail(
new StreamProtocolError(
`Reported totalSize ${metadata.totalSize} exceeds client cap ${cap}`
)
)
return
}
totalSize = metadata.totalSize
totalChunks = totalSize === 0 ? 0 : Math.ceil(totalSize / STREAM_CHUNK_SIZE)
try {
setup = createFileStreamSetup(rawMetadata, assemblyBudget)
} catch (error) {
const streamId = (rawMetadata as { streamId?: unknown } | null)?.streamId
if (typeof streamId === 'number') {
streamIdRef.current = streamId
}
fail(error as Error)
buffer = Buffer.alloc(totalSize)
} catch (err) {
streamIdRef.current = metadata.streamId
fail(new Error(`Failed to allocate ${totalSize} bytes: ${(err as Error).message}`))
return
}
if (setup.kind === 'empty') {
succeed(setup.result)
return
}
streamIdRef.current = setup.streamId
assembler = setup.assembler
streamIdRef.current = metadata.streamId
metadataReady = true
inactivity.reset()
drainPending()
})
.catch((err) => {
@@ -1,108 +0,0 @@
import { RelayErrorCode } from './relay-protocol'
import { type SshStreamAssemblyBudget, base64EncodedLength } from './ssh-stream-reader-memory'
export class GitResponseStreamError extends Error {
readonly code = RelayErrorCode.StreamProtocolError
constructor(message: string) {
super(message)
}
}
export class GitResponseStreamAssembler {
private buffer: Buffer | null
private expectedSeq = 0
private receivedBytes = 0
private releaseBudget: (() => void) | null
constructor(
private readonly streamId: number,
private readonly totalBytes: number,
private readonly chunkCount: number,
assemblyBudget: SshStreamAssemblyBudget
) {
this.releaseBudget = assemblyBudget.reserve(totalBytes)
if (!this.releaseBudget) {
throw new GitResponseStreamError(
`Active SSH stream assembly would exceed ${assemblyBudget.maxBytes} bytes`
)
}
try {
this.buffer = Buffer.alloc(totalBytes)
} catch (error) {
this.release()
throw new GitResponseStreamError(
`Failed to allocate ${totalBytes} bytes: ${(error as Error).message}`
)
}
}
acceptChunk(params: Record<string, unknown>): number {
const seq = params.seq
const data = params.data
if (
typeof seq !== 'number' ||
!Number.isSafeInteger(seq) ||
seq < 0 ||
typeof data !== 'string'
) {
throw new GitResponseStreamError(`Malformed chunk for git stream ${this.streamId}`)
}
if (seq !== this.expectedSeq) {
throw new GitResponseStreamError(
`Out-of-order chunk for git stream ${this.streamId}: expected ${this.expectedSeq}, got ${seq}`
)
}
if (this.expectedSeq >= this.chunkCount) {
throw new GitResponseStreamError(
`Git stream ${this.streamId} exceeded declared chunk count ${this.chunkCount}`
)
}
const remainingBytes = this.totalBytes - this.receivedBytes
if (data.length > base64EncodedLength(remainingBytes)) {
throw new GitResponseStreamError(
`Git stream ${this.streamId} chunk exceeds ${remainingBytes} remaining bytes`
)
}
const decoded = Buffer.from(data, 'base64')
if (decoded.length > remainingBytes) {
throw new GitResponseStreamError(
`Git stream ${this.streamId} decoded beyond its declared size`
)
}
if (!this.buffer) {
throw new GitResponseStreamError(
`Chunk arrived after completion for git stream ${this.streamId}`
)
}
decoded.copy(this.buffer, this.receivedBytes)
this.receivedBytes += decoded.length
this.expectedSeq += 1
return seq
}
finish(): unknown {
if (this.expectedSeq !== this.chunkCount || this.receivedBytes !== this.totalBytes) {
throw new GitResponseStreamError(
`Git stream ${this.streamId} incomplete: chunks ${this.expectedSeq}/${this.chunkCount}, bytes ${this.receivedBytes}/${this.totalBytes}`
)
}
if (!this.buffer) {
throw new GitResponseStreamError(`Git stream ${this.streamId} already completed`)
}
const serialized = this.buffer.toString('utf-8')
this.release()
try {
return JSON.parse(serialized)
} catch (error) {
throw new GitResponseStreamError(
`Git stream ${this.streamId} JSON parse failed: ${String(error)}`
)
}
}
release(): void {
this.buffer = null
this.releaseBudget?.()
this.releaseBudget = null
}
}
+98 -102
View File
@@ -1,26 +1,31 @@
import type { SshChannelMultiplexer } from './ssh-channel-multiplexer'
import {
MAX_GIT_RESPONSE_STREAM_BYTES,
MAX_GIT_RESPONSE_STREAM_CHUNKS,
isGitResponseStreamMarker
} from './relay-protocol'
import {
PreMetadataStreamFrameBuffer,
STREAM_READER_INACTIVITY_TIMEOUT_MS,
defaultSshPreMetadataStreamBudget,
defaultSshStreamAssemblyBudget,
type SshPreMetadataStreamBudget,
type SshStreamAssemblyBudget,
createStreamInactivityDeadline
} from './ssh-stream-reader-memory'
import {
GitResponseStreamAssembler,
GitResponseStreamError
} from './ssh-git-response-stream-assembler'
import { RelayErrorCode, isGitResponseStreamMarker } from './relay-protocol'
const SENTINEL_STREAM_ID = -1
export { GitResponseStreamError } from './ssh-git-response-stream-assembler'
/** Reject if no stream frame (chunk/end/error) arrives within this window,
* reset on each frame. mux.request's own timeout only bounds the fast sentinel
* response; without this, a relay pump that breaks on staleness (which sends no
* responseEnd) while the SSH channel stays up would hang the client forever. */
const STREAM_INACTIVITY_TIMEOUT_MS = 30_000
/** Bound transient buffering of other concurrent streams' chunks while this
* reader awaits its sentinel: every reader sees all git.responseChunk frames
* and can't filter by streamId until its own sentinel resolves. Foreign frames
* are dropped on drain anyway; this just caps the pre-sentinel backlog. */
const MAX_PENDING_FRAMES = 64
export class GitResponseStreamError extends Error {
readonly code = RelayErrorCode.StreamProtocolError
constructor(message: string) {
super(message)
}
}
type PendingFrame =
| { kind: 'chunk'; params: Record<string, unknown> }
| { kind: 'end'; params: Record<string, unknown> }
| { kind: 'error'; params: Record<string, unknown> }
/**
* Request a git method that may return a large payload, opting into response
@@ -44,9 +49,7 @@ export function requestGitStreamable(
timeoutMs?: number
/** Bounds the post-sentinel reassembly stall; resets on each chunk. */
inactivityTimeoutMs?: number
},
assemblyBudget: SshStreamAssemblyBudget = defaultSshStreamAssemblyBudget,
preMetadataBudget: SshPreMetadataStreamBudget = defaultSshPreMetadataStreamBudget
}
): Promise<unknown> {
// Why: subscribe to chunk/end/error BEFORE awaiting the sentinel response so a
// chunk that lands in the same dispatch tick as the response is not dropped
@@ -65,22 +68,42 @@ export function requestGitStreamable(
}
return new Promise<unknown>((resolve, reject) => {
let assembler: GitResponseStreamAssembler | null = null
const parts: Buffer[] = []
let expectedSeq = 0
let receivedBytes = 0
let totalBytes = 0
let chunkCount = 0
let settled = false
let metadataReady = false
const pending = new PreMetadataStreamFrameBuffer(preMetadataBudget)
const pending: PendingFrame[] = []
const inactivityMs = options?.inactivityTimeoutMs ?? STREAM_READER_INACTIVITY_TIMEOUT_MS
const inactivity = createStreamInactivityDeadline(inactivityMs, () => {
fail(
new GitResponseStreamError(`Git response stream stalled (>${inactivityMs}ms without data)`)
)
})
const inactivityMs = options?.inactivityTimeoutMs ?? STREAM_INACTIVITY_TIMEOUT_MS
let inactivityTimer: ReturnType<typeof setTimeout> | null = null
const clearInactivity = (): void => {
if (inactivityTimer) {
clearTimeout(inactivityTimer)
inactivityTimer = null
}
}
// Why: reset on every stream frame so a legitimately long stream is not
// killed, but a wedged stream (no frames arriving) rejects instead of
// hanging the caller forever.
const armInactivity = (): void => {
clearInactivity()
inactivityTimer = setTimeout(() => {
fail(
new GitResponseStreamError(
`Git response stream stalled (>${inactivityMs}ms without data)`
)
)
}, inactivityMs)
inactivityTimer.unref?.()
}
const cancelStreamId = (streamId: number): void => {
if (streamId !== SENTINEL_STREAM_ID && !mux.isDisposed()) {
const cancel = (): void => {
if (streamIdRef.current !== SENTINEL_STREAM_ID && !mux.isDisposed()) {
try {
mux.notify('git.cancelResponseStream', { streamId })
mux.notify('git.cancelResponseStream', { streamId: streamIdRef.current })
} catch {
// best-effort
}
@@ -91,11 +114,8 @@ export function requestGitStreamable(
return
}
settled = true
inactivity.clear()
pending.clear()
assembler?.release()
assembler = null
cancelStreamId(streamIdRef.current)
clearInactivity()
cancel()
cleanup()
reject(err)
}
@@ -104,8 +124,7 @@ export function requestGitStreamable(
return
}
settled = true
inactivity.clear()
pending.clear()
clearInactivity()
cleanup()
resolve(value)
}
@@ -114,22 +133,25 @@ export function requestGitStreamable(
if (settled || p.streamId !== streamIdRef.current) {
return
}
if (!assembler) {
const seq = p.seq as number
const data = p.data as string
if (typeof seq !== 'number' || typeof data !== 'string') {
fail(new GitResponseStreamError(`Malformed chunk for git stream ${streamIdRef.current}`))
return
}
if (seq !== expectedSeq) {
fail(
new GitResponseStreamError(
`Chunk arrived before metadata for git stream ${streamIdRef.current}`
`Out-of-order chunk for git stream ${streamIdRef.current}: expected ${expectedSeq}, got ${seq}`
)
)
return
}
let seq: number
try {
seq = assembler.acceptChunk(p)
} catch (error) {
fail(error as Error)
return
}
inactivity.reset()
const decoded = Buffer.from(data, 'base64')
parts.push(decoded)
receivedBytes += decoded.length
expectedSeq += 1
armInactivity()
// Why: credit-based flow control — the relay caps unacked chunks so a big
// response cannot queue unbounded ahead of interactive pty.data frames.
if (!mux.isDisposed()) {
@@ -145,18 +167,22 @@ export function requestGitStreamable(
if (settled || p.streamId !== streamIdRef.current) {
return
}
if (!assembler) {
if (expectedSeq !== chunkCount || receivedBytes !== totalBytes) {
fail(
new GitResponseStreamError(
`Stream end before metadata for git stream ${streamIdRef.current}`
`Git stream ${streamIdRef.current} incomplete: chunks ${expectedSeq}/${chunkCount}, bytes ${receivedBytes}/${totalBytes}`
)
)
return
}
try {
succeed(assembler.finish())
} catch (error) {
fail(error as Error)
succeed(JSON.parse(Buffer.concat(parts).toString('utf-8')))
} catch (err) {
fail(
new GitResponseStreamError(
`Git stream ${streamIdRef.current} JSON parse failed: ${String(err)}`
)
)
}
}
@@ -169,10 +195,7 @@ export function requestGitStreamable(
const drainPending = (): void => {
while (!settled && pending.length > 0) {
const frame = pending.shift()
if (!frame) {
break
}
const frame = pending.shift()!
if (frame.kind === 'chunk') {
handleChunk(frame.params)
} else if (frame.kind === 'end') {
@@ -183,18 +206,22 @@ export function requestGitStreamable(
}
}
const pushPending = (
kind: 'chunk' | 'end' | 'error',
params: Record<string, unknown>
): void => {
// Why: the stream id is unknown here; overload drops must not let one foreign frame fail every reader.
pending.push({ kind, params })
// Why: pre-sentinel we cannot filter by streamId (our id is unknown yet), so
// every concurrent reader transiently buffers all readers' chunks. Cap the
// backlog by dropping the oldest; foreign frames are dropped on drain anyway,
// and if our own seq-0 were ever dropped the seq check fails loudly rather
// than corrupting. The sentinel normally resolves long before this cap.
const pushPending = (frame: PendingFrame): void => {
pending.push(frame)
if (pending.length > MAX_PENDING_FRAMES) {
pending.shift()
}
}
unsubscribers.push(
mux.onNotificationByMethod('git.responseChunk', (p) => {
if (!metadataReady) {
pushPending('chunk', p)
pushPending({ kind: 'chunk', params: p })
return
}
handleChunk(p)
@@ -203,7 +230,7 @@ export function requestGitStreamable(
unsubscribers.push(
mux.onNotificationByMethod('git.responseEnd', (p) => {
if (!metadataReady) {
pushPending('end', p)
pushPending({ kind: 'end', params: p })
return
}
handleEnd(p)
@@ -212,7 +239,7 @@ export function requestGitStreamable(
unsubscribers.push(
mux.onNotificationByMethod('git.responseError', (p) => {
if (!metadataReady) {
pushPending('error', p)
pushPending({ kind: 'error', params: p })
return
}
handleStreamError(p)
@@ -262,52 +289,21 @@ export function requestGitStreamable(
void requestPromise
.then((result) => {
if (settled) {
if (isGitResponseStreamMarker(result)) {
cancelStreamId(result.__orcaGitResponseStream.streamId)
}
return
}
// Old relay / small result: plain single-frame value, no stream follows.
if (!isGitResponseStreamMarker(result)) {
if (
typeof result === 'object' &&
result !== null &&
'__orcaGitResponseStream' in result
) {
fail(new GitResponseStreamError('Malformed Git response stream metadata'))
return
}
succeed(result)
return
}
const marker = result.__orcaGitResponseStream
totalBytes = marker.totalBytes
chunkCount = marker.chunkCount
streamIdRef.current = marker.streamId
if (
marker.totalBytes > MAX_GIT_RESPONSE_STREAM_BYTES ||
marker.chunkCount > MAX_GIT_RESPONSE_STREAM_CHUNKS
) {
fail(
new GitResponseStreamError(
`Git response stream exceeds client limit (${marker.totalBytes} bytes, ${marker.chunkCount} chunks)`
)
)
return
}
try {
assembler = new GitResponseStreamAssembler(
marker.streamId,
marker.totalBytes,
marker.chunkCount,
assemblyBudget
)
} catch (error) {
fail(error as Error)
return
}
metadataReady = true
// Why: start the inactivity deadline now — mux.request's timeout only
// covered the sentinel; the reassembly phase needs its own guard.
inactivity.reset()
armInactivity()
drainPending()
})
.catch((err) => fail(err as Error))
-37
View File
@@ -1,37 +0,0 @@
import { closeSync, ftruncateSync, mkdtempSync, openSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { readSshKeyFile, SSH_KEY_FILE_MAX_BYTES } from './ssh-key-file'
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
function makeKeyPath(): string {
const root = mkdtempSync(join(tmpdir(), 'orca-ssh-key-'))
roots.push(root)
return join(root, 'id_ed25519')
}
describe('SSH key file bounds', () => {
it('preserves ordinary key bytes', () => {
const keyPath = makeKeyPath()
writeFileSync(keyPath, 'private-key')
expect(readSshKeyFile(keyPath)).toEqual(Buffer.from('private-key'))
})
it('rejects an oversized sparse key file', () => {
const keyPath = makeKeyPath()
const descriptor = openSync(keyPath, 'w')
ftruncateSync(descriptor, SSH_KEY_FILE_MAX_BYTES + 1)
closeSync(descriptor)
expect(() => readSshKeyFile(keyPath)).toThrow('exceeds')
})
})
-7
View File
@@ -1,7 +0,0 @@
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
export const SSH_KEY_FILE_MAX_BYTES = 1024 * 1024
export function readSshKeyFile(filePath: string): Buffer {
return readNodeFileSyncWithinLimit(filePath, SSH_KEY_FILE_MAX_BYTES).buffer
}
+1 -38
View File
@@ -1,7 +1,7 @@
import { EventEmitter } from 'node:events'
import { createServer } from 'node:net'
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { SSH_FORWARD_CLOSE_CONCURRENCY, SshPortForwardManager } from './ssh-port-forward'
import { SshPortForwardManager } from './ssh-port-forward'
const { startSystemSshPortForwardProcessMock } = vi.hoisted(() => ({
startSystemSshPortForwardProcessMock: vi.fn()
@@ -246,43 +246,6 @@ describe('SshPortForwardManager', () => {
expect(resolved).toBe(true)
})
it.each([
['at the limit', SSH_FORWARD_CLOSE_CONCURRENCY],
['above the limit', SSH_FORWARD_CLOSE_CONCURRENCY + 1]
])('bounds forward closes %s', async (_, count) => {
let active = 0
let peak = 0
let started = 0
const releases: (() => void)[] = []
const forwards = Array.from({ length: count }, () => {
const forward = createFakeSystemSshForward()
forward.close.mockImplementation(async () => {
started++
active++
peak = Math.max(peak, active)
await new Promise<void>((resolve) => releases.push(resolve))
active--
})
return forward
})
startSystemSshPortForwardProcessMock.mockImplementation(() => forwards.shift())
const conn = createSystemSshConn()
for (let index = 0; index < count; index++) {
await manager.addForward('conn-1', conn as never, 3000 + index, '127.0.0.1', 8080)
}
const removal = manager.removeAllForwards('conn-1')
await vi.waitFor(() => expect(started).toBe(Math.min(count, SSH_FORWARD_CLOSE_CONCURRENCY)))
if (count > SSH_FORWARD_CLOSE_CONCURRENCY) {
releases.shift()?.()
await vi.waitFor(() => expect(started).toBe(count))
}
releases.splice(0).forEach((release) => release())
await removal
expect(peak).toBe(Math.min(count, SSH_FORWARD_CLOSE_CONCURRENCY))
})
it('removes an unexpectedly exited system SSH forward and calls the close callback', async () => {
const onForwardClosed = vi.fn()
manager.setCallbacks({ onForwardClosed })
+1 -12
View File
@@ -7,9 +7,6 @@ import type {
SshPortForwardProvider,
StartedPortForward
} from './ssh-port-forward-provider'
import { mapSettledWithConcurrency } from '../../shared/map-with-concurrency'
export const SSH_FORWARD_CLOSE_CONCURRENCY = 8
export type { PortForwardEntry }
export type { PortForwardCloseReason }
@@ -182,15 +179,7 @@ export class SshPortForwardManager {
const toRemove = [...this.forwards.entries()]
.filter(([, { entry }]) => entry.connectionId === connectionId)
.map(([id]) => id)
const results = await mapSettledWithConcurrency(toRemove, SSH_FORWARD_CLOSE_CONCURRENCY, (id) =>
this.removeForwardAsync(id)
)
const failedClose = results.find(
(result): result is PromiseRejectedResult => result.status === 'rejected'
)
if (failedClose) {
throw failedClose.reason
}
await Promise.all(toRemove.map((id) => this.removeForwardAsync(id)))
}
dispose(): void {
-24
View File
@@ -7,10 +7,6 @@ import {
} from './ssh-port-scanner'
import type { SshChannelMultiplexer } from './ssh-channel-multiplexer'
import type { DetectedPort } from '../../shared/ssh-types'
import {
SSH_DETECTED_PORTS_MAX_ENTRIES,
SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES
} from '../../shared/ssh-retained-payload-admission'
type VisibilityHarness = {
visibility: PortScannerWindowVisibility
@@ -220,26 +216,6 @@ describe('PortScanner', () => {
scanner.dispose()
})
it('bounds remote rows before retaining or publishing a scan', async () => {
const harness = createVisibilityHarness(true)
const remoteRows = Array.from({ length: SSH_DETECTED_PORTS_MAX_ENTRIES + 20 }, (_, index) => ({
...port(3000 + index),
processName: 'x'.repeat(SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES + 100)
}))
const { mux } = createMux(() => remoteRows)
const onChanged = vi.fn()
const scanner = new PortScanner(harness.visibility)
scanner.startScanning('t1', mux, onChanged)
await vi.advanceTimersByTimeAsync(0)
const retained = scanner.getDetectedPorts('t1')
expect(retained).toHaveLength(SSH_DETECTED_PORTS_MAX_ENTRIES)
expect(retained[0].processName).toHaveLength(SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES)
expect(onChanged).toHaveBeenCalledWith('t1', retained, 'linux')
scanner.dispose()
})
it('stopScanning halts polling and detaches the visibility listener', async () => {
const harness = createVisibilityHarness(true)
const { mux, request } = createMux(() => [port(3000)])
+2 -5
View File
@@ -1,6 +1,5 @@
import type { SshChannelMultiplexer } from './ssh-channel-multiplexer'
import type { DetectedPort } from '../../shared/ssh-types'
import { admitSshDetectedPorts } from '../../shared/ssh-retained-payload-admission'
// Why: every tick walks /proc/*/fd on the remote relay, so cadence is remote
// CPU, not just a local timer. 12s cuts steady-state request volume 4x vs the
@@ -76,10 +75,8 @@ export class PortScanner {
return
}
// Why: relay responses cross a provider boundary and are retained between scans.
const admittedPorts = admitSshDetectedPorts(result.ports)
const currentPorts = new Map<string, DetectedPort>()
for (const p of admittedPorts) {
for (const p of result.ports) {
currentPorts.set(`${p.host}:${p.port}`, p)
}
@@ -90,7 +87,7 @@ export class PortScanner {
if (!portsEqual(handle.previousPorts, currentPorts)) {
handle.previousPorts = currentPorts
handle.intervalMs = SSH_PORT_SCAN_BASE_INTERVAL_MS
onChanged(targetId, admittedPorts, result.platform)
onChanged(targetId, result.ports, result.platform)
} else {
handle.intervalMs = Math.min(handle.intervalMs * 2, SSH_PORT_SCAN_MAX_INTERVAL_MS)
}
@@ -1,121 +0,0 @@
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import {
getRelayBaseDirectoryListingCommand,
RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL,
RELAY_BASE_DIRECTORY_MAX_ENTRIES,
RELAY_BASE_DIRECTORY_MAX_UTF8_BYTES
} from './ssh-relay-base-directory-listing'
import { getRemoteHostPlatform } from './ssh-remote-platform'
const posix = getRemoteHostPlatform('linux-x64')
const windows = getRemoteHostPlatform('win32-x64')
function decodePowerShellCommand(command: string): string {
const match = command.match(/-EncodedCommand\s+([A-Za-z0-9+/=]+)/)
return match ? Buffer.from(match[1], 'base64').toString('utf16le') : ''
}
function runPosixListing(
directory: string,
options: { maxEntries: number; maxUtf8Bytes: number }
): string[] {
const result = spawnSync(
'/bin/sh',
['-c', getRelayBaseDirectoryListingCommand(posix, directory, options)],
{ encoding: 'utf8' }
)
if (result.status !== 0) {
throw new Error(`listing exited ${result.status}: ${result.stderr}`)
}
return result.stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
}
function withTempDirectory(run: (directory: string) => void): void {
const directory = mkdtempSync(join(tmpdir(), 'orca-relay-listing-'))
try {
run(directory)
} finally {
rmSync(directory, { recursive: true, force: true })
}
}
describe('relay base-directory listing', () => {
it('streams POSIX entries through fixed entry and byte budgets', () => {
const command = getRelayBaseDirectoryListingCommand(posix, '/home/u/.orca-remote')
expect(command).toContain('find "$base" -mindepth 1 -maxdepth 1 -print')
expect(command).toContain(`entry_count>${RELAY_BASE_DIRECTORY_MAX_ENTRIES}`)
expect(command).toContain(`output_bytes+line_bytes>${RELAY_BASE_DIRECTORY_MAX_UTF8_BYTES}`)
expect(command).toContain('| sort')
expect(command).not.toContain('ls -1')
})
it('allows the exact POSIX entry and output-byte bounds', () => {
withTempDirectory((directory) => {
mkdirSync(join(directory, 'a'))
mkdirSync(join(directory, 'b'))
expect(
runPosixListing(directory, {
maxEntries: 2,
maxUtf8Bytes: 4
}).sort()
).toEqual(['a', 'b'])
})
})
it('emits a sentinel on the first POSIX entry beyond the bound', () => {
withTempDirectory((directory) => {
mkdirSync(join(directory, 'a'))
mkdirSync(join(directory, 'b'))
mkdirSync(join(directory, 'c'))
expect(
runPosixListing(directory, {
maxEntries: 2,
maxUtf8Bytes: 100
})
).toContain(RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL)
})
})
it('emits a sentinel before exceeding the POSIX output-byte bound', () => {
withTempDirectory((directory) => {
mkdirSync(join(directory, 'aa'))
mkdirSync(join(directory, 'bb'))
const lines = runPosixListing(directory, {
maxEntries: 2,
maxUtf8Bytes: 5
})
expect(lines).toContain(RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL)
expect(
lines.filter((line) => line !== RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL)
).toHaveLength(1)
})
})
it('uses a disposable streaming iterator on Windows', () => {
const script = decodePowerShellCommand(
getRelayBaseDirectoryListingCommand(windows, 'C:/Users/u/.orca-remote')
)
expect(script).toContain('[System.IO.Directory]::EnumerateDirectories($base)')
expect(script).toContain('.GetEnumerator()')
expect(script).toContain('$iterator.MoveNext()')
expect(script).toContain('$iterator.Dispose()')
expect(script).toContain(`$maxEntries = ${RELAY_BASE_DIRECTORY_MAX_ENTRIES}`)
expect(script).toContain(`$maxBytes = ${RELAY_BASE_DIRECTORY_MAX_UTF8_BYTES}`)
expect(script).toContain('UTF8.GetByteCount($name) + 2')
expect(script).toContain(RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL)
expect(script).not.toContain('Get-ChildItem')
})
})
@@ -1,93 +0,0 @@
import type { RemoteHostPlatform } from './ssh-remote-platform'
import { isWindowsRemoteHost } from './ssh-remote-platform'
import { powerShellCommand, powerShellLiteral } from './ssh-remote-powershell'
import { shellEscape } from './ssh-connection-utils'
export const RELAY_BASE_DIRECTORY_MAX_ENTRIES = 4_096
export const RELAY_BASE_DIRECTORY_MAX_UTF8_BYTES = 256 * 1024
export const RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL =
'__ORCA_RELAY_BASE_DIRECTORY_LISTING_TOO_LARGE__'
export function isRelayBaseDirectoryListingLimited(listing: string): boolean {
return listing
.split(/\r?\n/)
.some((line) => line.trim() === RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL)
}
type RelayBaseDirectoryListingOptions = {
maxEntries?: number
maxUtf8Bytes?: number
}
function positiveInteger(value: number | undefined, fallback: number, name: string): number {
const resolved = value ?? fallback
if (!Number.isSafeInteger(resolved) || resolved < 1) {
throw new Error(`${name} must be a positive integer`)
}
return resolved
}
export function getRelayBaseDirectoryListingCommand(
host: RemoteHostPlatform,
baseDir: string,
options?: RelayBaseDirectoryListingOptions
): string {
const maxEntries = positiveInteger(
options?.maxEntries,
RELAY_BASE_DIRECTORY_MAX_ENTRIES,
'maxEntries'
)
const maxUtf8Bytes = positiveInteger(
options?.maxUtf8Bytes,
RELAY_BASE_DIRECTORY_MAX_UTF8_BYTES,
'maxUtf8Bytes'
)
if (!isWindowsRemoteHost(host)) {
const awkProgram = [
'{',
'entry_count++;',
`if(entry_count>${maxEntries}){print "${RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL}";exit}`,
'name=$0;sub(/^.*\\//,"",name);',
'if(substr(name,1,1)==".")next;',
'line_bytes=length(name)+1;',
`if(output_bytes+line_bytes>${maxUtf8Bytes}){print "${RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL}";exit}`,
'print name;output_bytes+=line_bytes',
'}'
].join('')
return [
`base=${shellEscape(baseDir)};`,
'if [ -d "$base" ]; then',
'LC_ALL=C find "$base" -mindepth 1 -maxdepth 1 -print 2>/dev/null',
`| LC_ALL=C awk ${shellEscape(awkProgram)} | sort;`,
'fi'
].join(' ')
}
return powerShellCommand(
[
`$base = ${powerShellLiteral(baseDir)}`,
`if (Test-Path -LiteralPath $base -PathType Container) {`,
`$maxEntries = ${maxEntries}`,
`$maxBytes = ${maxUtf8Bytes}`,
`$sentinel = ${powerShellLiteral(RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL)}`,
'$entryCount = 0',
'$outputBytes = 0',
'$iterator = ([System.IO.Directory]::EnumerateDirectories($base)).GetEnumerator()',
'try {',
'while ($iterator.MoveNext()) {',
'if ($entryCount -ge $maxEntries) { Write-Output $sentinel; break }',
'$entryCount++',
'$name = [System.IO.Path]::GetFileName([string]$iterator.Current)',
'$lineBytes = [System.Text.Encoding]::UTF8.GetByteCount($name) + 2',
'if (($outputBytes + $lineBytes) -gt $maxBytes) { Write-Output $sentinel; break }',
'Write-Output $name',
'$outputBytes += $lineBytes',
'}',
'} finally {',
'if ($null -ne $iterator) { $iterator.Dispose() }',
'}',
'}'
].join('\n')
)
}
@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
SSH_RELAY_MARKER_MAX_BYTES,
posixReadRelayMarkerAssignment,
powerShellReadRelayMarkerAssignment
} from './ssh-relay-bounded-marker-commands'
describe('bounded SSH relay marker commands', () => {
it('reads at most one byte past the Windows marker ceiling', () => {
const script = powerShellReadRelayMarkerAssignment('C:/Users/me/.orca-remote/.gc-owner')
expect(script).toContain('[System.IO.File]::Open')
expect(script).toContain(`New-Object byte[] ${SSH_RELAY_MARKER_MAX_BYTES + 1}`)
expect(script).toContain(`-le ${SSH_RELAY_MARKER_MAX_BYTES}`)
expect(script).not.toContain('Get-Content')
expect(script).not.toContain('ReadAllText')
})
it('caps POSIX command substitution before comparing an owner token', () => {
const script = posixReadRelayMarkerAssignment('/home/u/.orca-remote/.gc-owner')
expect(script).toContain(`bs=${SSH_RELAY_MARKER_MAX_BYTES + 1}`)
expect(script).toContain(`-gt ${SSH_RELAY_MARKER_MAX_BYTES}`)
expect(script).not.toContain('cat ')
})
})
@@ -1,23 +0,0 @@
import { shellEscape } from './ssh-connection-utils'
import { powerShellLiteral } from './ssh-remote-powershell'
export const SSH_RELAY_MARKER_MAX_BYTES = 1024
export function powerShellReadRelayMarkerAssignment(markerPath: string): string {
return [
'$orcaMarkerValue = $null',
'$orcaMarkerStream = $null',
`try { $orcaMarkerStream = [System.IO.File]::Open(${powerShellLiteral(markerPath)}, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, ([System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete))`,
`$orcaMarkerBuffer = New-Object byte[] ${SSH_RELAY_MARKER_MAX_BYTES + 1}`,
'$orcaMarkerCount = $orcaMarkerStream.Read($orcaMarkerBuffer, 0, $orcaMarkerBuffer.Length)',
`if ($orcaMarkerCount -le ${SSH_RELAY_MARKER_MAX_BYTES}) { $orcaMarkerValue = [System.Text.Encoding]::UTF8.GetString($orcaMarkerBuffer, 0, $orcaMarkerCount) }`,
'} catch {} finally { if ($null -ne $orcaMarkerStream) { $orcaMarkerStream.Dispose() } }'
].join('; ')
}
export function posixReadRelayMarkerAssignment(markerPath: string): string {
return [
`orca_marker=$(dd if=${shellEscape(markerPath)} bs=${SSH_RELAY_MARKER_MAX_BYTES + 1} count=1 2>/dev/null) || orca_marker=`,
`if [ "\${#orca_marker}" -gt ${SSH_RELAY_MARKER_MAX_BYTES} ]; then orca_marker=; fi`
].join('; ')
}
@@ -14,10 +14,8 @@ vi.mock('electron', () => ({
}))
vi.mock('fs', () => ({
existsSync: vi.fn().mockReturnValue(true)
}))
vi.mock('../../shared/relay-version-marker', () => ({
readRelayVersionMarkerSync: vi.fn().mockReturnValue('0.1.0+v2hash')
existsSync: vi.fn().mockReturnValue(true),
readFileSync: vi.fn().mockReturnValue('0.1.0+v2hash')
}))
vi.mock('./relay-protocol', () => ({
+1 -62
View File
@@ -3,12 +3,7 @@ import { describe, expect, it, vi } from 'vitest'
import type { ClientChannel } from 'ssh2'
import { execCommand, waitForSentinel } from './ssh-relay-deploy-helpers'
import { shouldProbeBuildToolchainAfterNativeDepsFailure } from './ssh-relay-build-toolchain'
import {
HEADER_LENGTH,
MAX_BUFFERED_FRAME_CHUNKS,
MAX_MESSAGE_SIZE,
RELAY_SENTINEL
} from './relay-protocol'
import { RELAY_SENTINEL } from './relay-protocol'
import {
RelayVersionMismatchError,
RELAY_EXIT_CODE_VERSION_MISMATCH
@@ -209,62 +204,6 @@ describe('waitForSentinel', () => {
expect(Buffer.concat(chunks)).toEqual(postSentinelPayload)
expect(channel.close).not.toHaveBeenCalled()
})
it('preserves the exact post-sentinel payload at the pending transport cap', async () => {
const channel = createMockChannel()
const transportPromise = waitForSentinel(channel)
const payload = Buffer.alloc((MAX_MESSAGE_SIZE + HEADER_LENGTH) * 2, 'p')
channel.emit('data', Buffer.from(RELAY_SENTINEL))
channel.emit('data', payload)
const transport = await transportPromise
const chunks: Buffer[] = []
transport.onData((chunk) => chunks.push(chunk))
expect(chunks).toHaveLength(1)
expect(chunks[0]?.equals(payload)).toBe(true)
expect(channel.close).not.toHaveBeenCalled()
})
it('closes before retaining post-sentinel bytes beyond the pending transport cap', async () => {
const channel = createMockChannel()
const transportPromise = waitForSentinel(channel)
channel.emit('data', Buffer.from(RELAY_SENTINEL))
channel.emit('data', Buffer.alloc((MAX_MESSAGE_SIZE + HEADER_LENGTH) * 2, 'p'))
channel.emit('data', Buffer.from('overflow'))
const transport = await transportPromise
const onData = vi.fn()
const onClose = vi.fn()
transport.onData(onData)
transport.onClose(onClose)
expect(onData).not.toHaveBeenCalled()
expect(onClose).toHaveBeenCalledOnce()
expect(channel.close).toHaveBeenCalledOnce()
})
it('closes before retaining too many post-sentinel fragments', async () => {
const channel = createMockChannel()
const transportPromise = waitForSentinel(channel)
channel.emit('data', Buffer.from(RELAY_SENTINEL))
for (let index = 0; index <= MAX_BUFFERED_FRAME_CHUNKS; index++) {
channel.emit('data', Buffer.from('p'))
}
const transport = await transportPromise
const onData = vi.fn()
const onClose = vi.fn()
transport.onData(onData)
transport.onClose(onClose)
expect(onData).not.toHaveBeenCalled()
expect(onClose).toHaveBeenCalledOnce()
expect(channel.close).toHaveBeenCalledOnce()
})
})
describe('execCommand', () => {
+18 -39
View File
@@ -1,12 +1,6 @@
import type { ClientChannel } from 'ssh2'
import { createSshOperationAbortError } from './ssh-connection-utils'
import {
HEADER_LENGTH,
MAX_BUFFERED_FRAME_CHUNKS,
MAX_MESSAGE_SIZE,
RELAY_SENTINEL,
RELAY_SENTINEL_TIMEOUT_MS
} from './relay-protocol'
import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from './relay-protocol'
import type { MultiplexerTransport } from './ssh-channel-multiplexer'
import { buildRelayVersionMismatchError } from './ssh-relay-handshake-mismatch'
@@ -16,8 +10,6 @@ export { execCommand, isUnconfirmedSshCommandTermination } from './ssh-relay-exe
// ── Sentinel detection ────────────────────────────────────────────────
const MAX_RELAY_STARTUP_BUFFER_BYTES = 64 * 1024
// One maximum frame may be coalesced with the start of the next.
const MAX_PENDING_RELAY_BYTES = (MAX_MESSAGE_SIZE + HEADER_LENGTH) * 2
const RELAY_SENTINEL_BUFFER = Buffer.from(RELAY_SENTINEL, 'utf-8')
export function waitForSentinel(
@@ -170,35 +162,19 @@ export function waitForSentinel(
notifyClosed()
})
// The caller cannot subscribe until the resolved promise resumes.
let pendingAfterSentinel: Buffer[] = []
let pendingAfterSentinelBytes = 0
const bufferAfterSentinel = (data: Buffer): void => {
if (closedAfterSentinel) {
return
}
if (
data.length > MAX_PENDING_RELAY_BYTES - pendingAfterSentinelBytes ||
pendingAfterSentinel.length >= MAX_BUFFERED_FRAME_CHUNKS
) {
pendingAfterSentinel = []
pendingAfterSentinelBytes = 0
notifyClosed()
channel.close()
return
}
pendingAfterSentinel.push(data)
pendingAfterSentinelBytes += data.length
}
// Why: data arriving in the same TCP chunk as the sentinel is buffered
// here. It's delivered on the first onData registration rather than
// immediately after resolve, because resolve schedules a microtask —
// the caller's `await` hasn't resumed yet, so no callbacks are
// registered when the synchronous code after resolve runs.
let pendingAfterSentinel: Buffer | null = null
channel.on('data', (data: Buffer) => {
if (sentinelReceived) {
if (closedAfterSentinel) {
return
}
if (dataCallbacks.length === 0) {
bufferAfterSentinel(data)
pendingAfterSentinel = pendingAfterSentinel
? Buffer.concat([pendingAfterSentinel, data])
: data
} else {
for (const cb of dataCallbacks) {
cb(data)
@@ -235,16 +211,19 @@ export function waitForSentinel(
const afterSentinel = data.subarray(Math.max(0, afterSentinelOffset))
if (afterSentinel.length > 0) {
bufferAfterSentinel(afterSentinel)
pendingAfterSentinel = afterSentinel
}
const transport: MultiplexerTransport = {
write: (buf: Buffer) => channel.stdin.write(buf),
onData: (cb) => {
dataCallbacks.push(cb)
if (pendingAfterSentinel.length > 0) {
const buf = Buffer.concat(pendingAfterSentinel, pendingAfterSentinelBytes)
pendingAfterSentinel = []
pendingAfterSentinelBytes = 0
// Why: deliver buffered post-sentinel data to the first
// subscriber. This is the multiplexer constructor, which
// registers onData synchronously — the data is guaranteed
// to reach the decoder before any other frames arrive.
if (pendingAfterSentinel) {
const buf = pendingAfterSentinel
pendingAfterSentinel = null
cb(buf)
}
},
+2 -10
View File
@@ -101,11 +101,7 @@ function extractWindowsSockPath(script: string): string {
}
function extractWindowsMarkerPath(script: string): string {
return (
/(?:-LiteralPath\s+|\[System\.IO\.File\]::Open\()'([^']*\.windows-active-pipe[^']*)'/.exec(
script
)?.[1] ?? ''
)
return /-LiteralPath\s+'([^']*\.windows-active-pipe[^']*)'/.exec(script)?.[1] ?? ''
}
function makeMockConnection(): SshConnection {
@@ -899,11 +895,7 @@ describe('deployAndLaunchRelay', () => {
const markerPaths = mockExecCommand.mock.calls
.map(([, command]) => decodePowerShellCommand(command))
.filter((script): script is string =>
Boolean(
script?.includes('[System.IO.File]::Open') && script.includes('.windows-active-pipe')
)
)
.filter((script): script is string => Boolean(script?.includes('Get-Content')))
.map(extractWindowsMarkerPath)
expect(markerPaths).toHaveLength(2)
+12 -3
View File
@@ -64,8 +64,6 @@ import {
MAX_SSH_RELAY_GRACE_PERIOD_SECONDS,
MIN_SSH_RELAY_GRACE_PERIOD_SECONDS
} from '../../shared/ssh-types'
import { powerShellReadRelayMarkerAssignment } from './ssh-relay-bounded-marker-commands'
import { windowsRelayTailLogCommand } from './ssh-windows-log-tail-command'
export type RelayDeployResult = {
transport: MultiplexerTransport
@@ -1166,7 +1164,7 @@ async function readWindowsActiveRelayEndpoint(
conn,
hostPlatform,
powerShellCommand(
`${powerShellReadRelayMarkerAssignment(markerPath)}; if ($null -ne $orcaMarkerValue) { [Console]::Out.Write($orcaMarkerValue) }`
`if (Test-Path -LiteralPath ${powerShellLiteral(markerPath)} -PathType Leaf) { Get-Content -LiteralPath ${powerShellLiteral(markerPath)} -Raw -ErrorAction SilentlyContinue }`
),
{ signal }
).catch(() => {
@@ -1520,3 +1518,14 @@ function windowsRelayWaitCommand(
].join(' ')
)
}
function windowsRelayTailLogCommand(logFile: string, errFile: string): string {
const script = [
`$out = if (Test-Path -LiteralPath ${powerShellLiteral(logFile)}) { Get-Content -LiteralPath ${powerShellLiteral(logFile)} -Tail 20 -ErrorAction SilentlyContinue } else { '(no stdout log)' }`,
`$err = if (Test-Path -LiteralPath ${powerShellLiteral(errFile)}) { Get-Content -LiteralPath ${powerShellLiteral(errFile)} -Tail 20 -ErrorAction SilentlyContinue } else { '(no stderr log)' }`,
'Write-Output $out',
"Write-Output '--- stderr ---'",
'Write-Output $err'
].join('; ')
return powerShellCommand(script)
}
+6 -12
View File
@@ -9,10 +9,6 @@ import {
} from './ssh-relay-install-lock-commands'
import { removeRemoteTreeCommand } from './ssh-remote-commands'
import { powerShellCommand, powerShellLiteral } from './ssh-remote-powershell'
import {
posixReadRelayMarkerAssignment,
powerShellReadRelayMarkerAssignment
} from './ssh-relay-bounded-marker-commands'
import {
getRemoteHostPlatform,
isWindowsRemoteHost,
@@ -135,9 +131,9 @@ export async function isRelayGcClaimOwned(
const ownerPath = joinRemotePath(host, relayGcClaimPath(remoteRelayDir), RELAY_GC_OWNER_NAME)
const command = isWindowsRemoteHost(host)
? powerShellCommand(
`${powerShellReadRelayMarkerAssignment(ownerPath)}; if ($orcaMarkerValue -ceq ${powerShellLiteral(token)}) { 'OWNED' } else { 'LOST' }`
`if ((Get-Content -LiteralPath ${powerShellLiteral(ownerPath)} -Raw -ErrorAction SilentlyContinue) -ceq ${powerShellLiteral(token)}) { 'OWNED' } else { 'LOST' }`
)
: `${posixReadRelayMarkerAssignment(ownerPath)}; test "$orca_marker" = ${shellEscape(token)} && echo OWNED || echo LOST`
: `test "$(cat ${shellEscape(ownerPath)} 2>/dev/null)" = ${shellEscape(token)} && echo OWNED || echo LOST`
const output = await execHostCommand(conn, host, command).catch(() => 'LOST')
return output.trim() === 'OWNED'
}
@@ -156,17 +152,15 @@ export async function releaseRelayGcClaim(
? powerShellCommand(
`$claim = ${powerShellLiteral(claimPath)}; ` +
`if (-not (Test-Path -LiteralPath $claim)) { 'RELEASED' } ` +
`else { ${powerShellReadRelayMarkerAssignment(ownerPath)}; ` +
`if ($orcaMarkerValue -cne ${powerShellLiteral(token)}) { 'LOST' } ` +
`elseif ((Get-Content -LiteralPath ${powerShellLiteral(ownerPath)} -Raw -ErrorAction SilentlyContinue) -cne ${powerShellLiteral(token)}) { 'LOST' } ` +
'else { try { Remove-Item -LiteralPath $claim -Recurse -Force -ErrorAction Stop } catch {}; ' +
"if (Test-Path -LiteralPath $claim) { 'UNKNOWN' } else { 'RELEASED' } } }"
"if (Test-Path -LiteralPath $claim) { 'UNKNOWN' } else { 'RELEASED' } }"
)
: [
`if ! test -e ${shellEscape(claimPath)}; then echo RELEASED;`,
`else ${posixReadRelayMarkerAssignment(ownerPath)};`,
`if test "$orca_marker" != ${shellEscape(token)}; then echo LOST;`,
`elif test "$(cat ${shellEscape(ownerPath)} 2>/dev/null)" != ${shellEscape(token)}; then echo LOST;`,
`else ${removeRemoteTreeCommand(host, claimPath)} 2>/dev/null;`,
`if test -e ${shellEscape(claimPath)}; then echo UNKNOWN; else echo RELEASED; fi; fi; fi`
`if test -e ${shellEscape(claimPath)}; then echo UNKNOWN; else echo RELEASED; fi; fi`
].join(' ')
const output = await execHostCommand(conn, host, command).catch(() => 'UNKNOWN')
switch (output.trim()) {
@@ -92,10 +92,7 @@ function posixStealInstallLockCommand(lockDir: string, staleAfterSeconds: number
'steal="$steal_root.$steal_generation";',
'done;',
'if [ "$owns_steal" = 1 ]; then',
'steal_parent=${steal_root%/*};',
'steal_leaf=${steal_root##*/};',
'[ "$steal_parent" != "$steal_root" ] || steal_parent=.;',
`trap 'find "$steal_parent" -mindepth 1 -maxdepth 1 -name "$steal_leaf.*" -exec rm -rf {} + 2>/dev/null || true; rm -rf "$lock_tombstone" 2>/dev/null || true' EXIT;`,
`trap 'rm -rf "$steal_root".* 2>/dev/null || true; rm -rf "$lock_tombstone" 2>/dev/null || true' EXIT;`,
`${posixLockIdentityAssignment(lockDir, 'current_key')} && current_mtime=\${current_key%%:*} && current_now=$(date +%s) && current_age=$((current_now - current_mtime)) || current_age=0;`,
`if [ "$current_key" = "$lock_key" ] && [ "\${current_age:-0}" -gt ${staleAfterSeconds} ] 2>/dev/null; then`,
`lock_tombstone=${escapedLockDir}.tombstone.$$.$(date +%s);`,
@@ -1,156 +0,0 @@
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { GENERATED_NODE_MANAGED_FILE_MAX_BYTES } from '../generated-node-bounded-file-reader'
import {
getWindowsRelayLivenessProbeSource,
WINDOWS_RELAY_LIVENESS_DIRECTORY_BUFFER_SIZE,
WINDOWS_RELAY_LIVENESS_INCONCLUSIVE_STATE,
WINDOWS_RELAY_LIVENESS_MAX_DIRECTORY_ENTRIES,
WINDOWS_RELAY_LIVENESS_MAX_PIPE_PATHS
} from './ssh-relay-liveness-probe-source'
const PIPE_A = '\\\\.\\pipe\\orca-relay-00000000000000000000'
const PIPE_B = '\\\\.\\pipe\\orca-relay-11111111111111111111'
const PIPE_C = '\\\\.\\pipe\\orca-relay-22222222222222222222'
function runProbe(
directory: string,
options: {
maxDirectoryEntries: number
maxPipePaths: number
seedPipePaths?: string[]
}
): string {
const source = getWindowsRelayLivenessProbeSource({
maxDirectoryEntries: options.maxDirectoryEntries,
maxPipePaths: options.maxPipePaths,
directoryBufferSize: 1
})
const result = spawnSync(
process.execPath,
['-e', source, directory, ...(options.seedPipePaths ?? [])],
{
encoding: 'utf8',
timeout: 5_000
}
)
if (result.status !== 0) {
throw new Error(`probe exited ${result.status}: ${result.stderr}`)
}
return result.stdout
}
function withTempDirectory(run: (directory: string) => void): void {
const directory = mkdtempSync(join(tmpdir(), 'orca-relay-liveness-'))
try {
run(directory)
} finally {
rmSync(directory, { recursive: true, force: true })
}
}
describe('Windows relay liveness probe source', () => {
it('uses fixed-capacity incremental directory iteration', () => {
const source = getWindowsRelayLivenessProbeSource()
expect(source).toContain(
`maxEntries=${WINDOWS_RELAY_LIVENESS_MAX_DIRECTORY_ENTRIES},maxPipes=${WINDOWS_RELAY_LIVENESS_MAX_PIPE_PATHS}`
)
expect(source).toContain(
`opendirSync(dir,{bufferSize:${WINDOWS_RELAY_LIVENESS_DIRECTORY_BUFFER_SIZE}})`
)
expect(source).toContain('directory.readSync()')
expect(source).not.toContain('readdirSync')
expect(source).not.toContain('pipes.includes')
})
it('allows exactly the directory-entry limit', () => {
withTempDirectory((directory) => {
writeFileSync(join(directory, 'one'), '')
writeFileSync(join(directory, 'two'), '')
expect(
runProbe(directory, {
maxDirectoryEntries: 2,
maxPipePaths: 1,
seedPipePaths: [PIPE_A]
})
).toBe('WAITING')
})
})
it('fails closed when the incremental iterator finds one entry beyond the limit', () => {
withTempDirectory((directory) => {
writeFileSync(join(directory, 'one'), '')
writeFileSync(join(directory, 'two'), '')
writeFileSync(join(directory, 'three'), '')
expect(
runProbe(directory, {
maxDirectoryEntries: 2,
maxPipePaths: 1,
seedPipePaths: [PIPE_A]
})
).toBe(WINDOWS_RELAY_LIVENESS_INCONCLUSIVE_STATE)
})
})
it('allows exactly the retained-pipe limit', () => {
withTempDirectory((directory) => {
writeFileSync(join(directory, '.windows-active-pipe-a'), PIPE_A)
writeFileSync(join(directory, '.windows-active-pipe-b'), PIPE_B)
expect(
runProbe(directory, {
maxDirectoryEntries: 2,
maxPipePaths: 2
})
).toBe('WAITING')
})
})
it('fails closed before retaining a pipe beyond the limit', () => {
withTempDirectory((directory) => {
writeFileSync(join(directory, '.windows-active-pipe-a'), PIPE_A)
writeFileSync(join(directory, '.windows-active-pipe-b'), PIPE_B)
writeFileSync(join(directory, '.windows-active-pipe-c'), PIPE_C)
expect(
runProbe(directory, {
maxDirectoryEntries: 3,
maxPipePaths: 2
})
).toBe(WINDOWS_RELAY_LIVENESS_INCONCLUSIVE_STATE)
})
})
it('fails closed when a marker exceeds its file-size limit', () => {
withTempDirectory((directory) => {
writeFileSync(
join(directory, '.windows-active-pipe-oversized'),
'x'.repeat(GENERATED_NODE_MANAGED_FILE_MAX_BYTES + 1)
)
expect(
runProbe(directory, {
maxDirectoryEntries: 1,
maxPipePaths: 1
})
).toBe(WINDOWS_RELAY_LIVENESS_INCONCLUSIVE_STATE)
})
})
it('preserves the missing-directory liveness result', () => {
withTempDirectory((directory) => {
expect(
runProbe(join(directory, 'missing'), {
maxDirectoryEntries: 1,
maxPipePaths: 1
})
).toBe('ALIVE')
})
})
})
@@ -1,91 +0,0 @@
import { getGeneratedNodeBoundedFileReaderSourceLines } from '../generated-node-bounded-file-reader'
export const WINDOWS_RELAY_LIVENESS_MAX_DIRECTORY_ENTRIES = 4_096
export const WINDOWS_RELAY_LIVENESS_MAX_PIPE_PATHS = 1_024
export const WINDOWS_RELAY_LIVENESS_DIRECTORY_BUFFER_SIZE = 32
export const WINDOWS_RELAY_LIVENESS_INCONCLUSIVE_STATE = 'INCONCLUSIVE'
type WindowsRelayLivenessProbeSourceOptions = {
maxDirectoryEntries?: number
maxPipePaths?: number
directoryBufferSize?: number
}
function positiveInteger(value: number | undefined, fallback: number, name: string): number {
const resolved = value ?? fallback
if (!Number.isSafeInteger(resolved) || resolved < 1) {
throw new Error(`${name} must be a positive integer`)
}
return resolved
}
export function getWindowsRelayLivenessProbeSource(
options?: WindowsRelayLivenessProbeSourceOptions
): string {
const maxDirectoryEntries = positiveInteger(
options?.maxDirectoryEntries,
WINDOWS_RELAY_LIVENESS_MAX_DIRECTORY_ENTRIES,
'maxDirectoryEntries'
)
const maxPipePaths = positiveInteger(
options?.maxPipePaths,
WINDOWS_RELAY_LIVENESS_MAX_PIPE_PATHS,
'maxPipePaths'
)
const directoryBufferSize = positiveInteger(
options?.directoryBufferSize,
WINDOWS_RELAY_LIVENESS_DIRECTORY_BUFFER_SIZE,
'directoryBufferSize'
)
const boundedReadSource = getGeneratedNodeBoundedFileReaderSourceLines().join('')
return [
'const fs=require("fs"),path=require("path"),net=require("net");',
boundedReadSource,
'const [dir,...seed]=process.argv.slice(1);',
'const valid=/^\\\\\\\\[.?]\\\\pipe\\\\orca-relay-[0-9a-f]{20}$/i;',
`const maxEntries=${maxDirectoryEntries},maxPipes=${maxPipePaths};`,
'const pipes=[],seen=new Set();',
'let markerCount=0,capacityExceeded=false;',
'function addPipe(p){',
'if(!valid.test(p)||seen.has(p))return;',
'if(pipes.length>=maxPipes){capacityExceeded=true;return}',
'seen.add(p);pipes.push(p)',
'}',
'for(const p of seed){addPipe(p);if(capacityExceeded)break}',
'let directory;',
'if(!capacityExceeded)try{',
`directory=fs.opendirSync(dir,{bufferSize:${directoryBufferSize}});`,
'let entryCount=0;',
'while(true){',
'const entry=directory.readSync();',
'if(!entry)break;',
'if(entryCount>=maxEntries){capacityExceeded=true;break}',
'entryCount++;',
'const name=entry.name;',
'if(!name.startsWith(".windows-active-pipe-"))continue;',
'markerCount++;',
'const p=readOrcaManagedFileWithinLimit(fs,path.join(dir,name)).trim();',
'addPipe(p);',
'if(capacityExceeded)break',
'}',
'}catch(error){if(error&&error.code==="EFBIG")capacityExceeded=true}',
'finally{if(directory)try{directory.closeSync()}catch{}}',
`if(capacityExceeded){process.stdout.write("${WINDOWS_RELAY_LIVENESS_INCONCLUSIVE_STATE}");process.exit(0)}`,
'if(markerCount===0&&pipes.length===0){process.stdout.write("ALIVE");process.exit(0)}',
'let i=0;',
'function done(ok){process.stdout.write(ok?"ALIVE":"WAITING")}',
'function next(){',
'const pipe=pipes[i++];',
'if(!pipe)return done(false);',
'const s=net.connect(pipe);',
'let settled=false;',
'function finish(ok){if(settled)return;settled=true;s.destroy();if(ok)done(true);else next()}',
's.setTimeout(200);',
's.on("connect",()=>finish(true));',
's.on("timeout",()=>finish(false));',
's.on("error",()=>finish(false));',
'}',
'next();'
].join('')
}
@@ -56,12 +56,6 @@ vi.mock('../ipc/pty', () => ({
setPtyOwnership: vi.fn()
}))
vi.mock('../ipc/pty-renderer-delivery-router', () => ({
routeExternalPtyData: vi.fn(),
routeExternalPtyReplay: vi.fn(),
routeExternalPtyExit: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
registerSshFilesystemProvider: vi.fn(),
unregisterSshFilesystemProvider: vi.fn(),
@@ -74,7 +68,6 @@ vi.mock('../providers/ssh-git-dispatch', () => ({
}))
const { registerSshPtyProvider } = await import('../ipc/pty')
const { routeExternalPtyData } = await import('../ipc/pty-renderer-delivery-router')
describe('SshRelaySession data delivery', () => {
beforeEach(() => {
@@ -83,9 +76,16 @@ describe('SshRelaySession data delivery', () => {
mockDeploySuccess()
})
it('routes empty transformed relay spans with raw sequence metadata', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
it('delivers empty transformed relay spans with raw sequence metadata', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const runtime = { onPtyData: vi.fn(() => 17), onPtyExit: vi.fn() }
const session = new SshRelaySession(
'target-1',
getMainWindow,
mockStore,
mockPortForward,
runtime as never
)
await session.establish(mockConn)
const ptyProvider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as {
onData: ReturnType<typeof vi.fn>
@@ -99,11 +99,14 @@ describe('SshRelaySession data delivery', () => {
onData({ id: 'ssh-pty-1', data: '', sequenceChars: 9, transformed: true })
expect(routeExternalPtyData).toHaveBeenCalledWith({
expect(runtime.onPtyData).toHaveBeenCalledWith('ssh-pty-1', '', expect.any(Number), 9, true)
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: 'ssh-pty-1',
data: '',
sequenceChars: 9,
transformed: true
transformed: true,
seq: 17,
rawLength: 9
})
})
})
@@ -51,11 +51,6 @@ vi.mock('../ipc/pty', () => ({
isCurrentPtyExit: vi.fn(() => true),
answerStartupTerminalColorQueriesForPty: vi.fn((_id: string, data: string) => data)
}))
vi.mock('../ipc/pty-renderer-delivery-router', () => ({
routeExternalPtyData: vi.fn(),
routeExternalPtyReplay: vi.fn(),
routeExternalPtyExit: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
registerSshFilesystemProvider: vi.fn(),
unregisterSshFilesystemProvider: vi.fn(),
@@ -68,7 +63,6 @@ vi.mock('../providers/ssh-git-dispatch', () => ({
const { registerSshPtyProvider, clearProviderPtyState, deletePtyOwnership, isCurrentPtyExit } =
await import('../ipc/pty')
const { routeExternalPtyExit } = await import('../ipc/pty-renderer-delivery-router')
describe('SSH relay PTY incarnation exits', () => {
beforeEach(() => {
@@ -79,7 +73,7 @@ describe('SSH relay PTY incarnation exits', () => {
})
it('drops a stale exit before ownership cleanup and propagates a current incarnation', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const runtime = { onPtyData: vi.fn(), onPtyExit: vi.fn() }
const session = new SshRelaySession(
'target-1',
@@ -105,19 +99,13 @@ describe('SSH relay PTY incarnation exits', () => {
expect(deletePtyOwnership).not.toHaveBeenCalled()
expect(mockStore.markSshRemotePtyLease).not.toHaveBeenCalled()
expect(runtime.onPtyExit).not.toHaveBeenCalled()
expect(routeExternalPtyExit).not.toHaveBeenCalled()
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:exit', expect.anything())
const currentExit = {
id: 'ssh:target-1@@pty-reused',
code: 7,
incarnationId: 'current-incarnation'
}
onExit(currentExit)
onExit({ id: 'ssh:target-1@@pty-reused', code: 7, incarnationId: 'current-incarnation' })
expect(runtime.onPtyExit).toHaveBeenCalledWith(
'ssh:target-1@@pty-reused',
7,
'current-incarnation'
)
expect(routeExternalPtyExit).toHaveBeenCalledWith(currentExit)
})
})
@@ -53,11 +53,6 @@ vi.mock('../ipc/pty', () => ({
isCurrentPtyExit: vi.fn(() => true),
answerStartupTerminalColorQueriesForPty: vi.fn((_id: string, data: string) => data)
}))
vi.mock('../ipc/pty-renderer-delivery-router', () => ({
routeExternalPtyData: vi.fn(),
routeExternalPtyReplay: vi.fn(),
routeExternalPtyExit: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
registerSshFilesystemProvider: vi.fn(),
unregisterSshFilesystemProvider: vi.fn(),
@@ -75,7 +70,6 @@ const {
setPtyOwnership,
restorePtyIncarnation
} = await import('../ipc/pty')
const { routeExternalPtyReplay } = await import('../ipc/pty-renderer-delivery-router')
const APP_PTY_ID = 'ssh:target-1@@pty-live'
const INCARNATION_LEAF_ID = '11111111-1111-4111-8111-111111111111'
@@ -152,7 +146,7 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
})
it('does not restore a PTY whose matching exit shares the attach reply batch', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const incarnationId = 'incarnation-exited-during-attach'
const runtime = {
acceptPtyIncarnationForExit: vi.fn(),
@@ -192,11 +186,15 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
'pty-live',
'terminated'
)
expect(routeExternalPtyReplay).not.toHaveBeenCalled()
expect(
vi
.mocked(mockWindow.webContents.send)
.mock.calls.some(([channel]) => channel === 'pty:replay')
).toBe(false)
})
it('ignores an older incarnation exit while reconnecting a reused PTY id', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const currentIncarnationId = 'incarnation-current'
const runtime = {
acceptPtyIncarnationForExit: vi.fn(),
@@ -239,7 +237,7 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
expect(mockStore.persistPtyBinding).toHaveBeenCalledWith(
expect.objectContaining({ ptyId: APP_PTY_ID, incarnationId: currentIncarnationId })
)
expect(routeExternalPtyReplay).toHaveBeenCalledWith({
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:replay', {
id: APP_PTY_ID,
data: 'live-output'
})
+94 -24
View File
@@ -74,12 +74,6 @@ vi.mock('../ipc/pty', () => ({
isCurrentPtyExit: vi.fn(() => true)
}))
vi.mock('../ipc/pty-renderer-delivery-router', () => ({
routeExternalPtyData: vi.fn(),
routeExternalPtyReplay: vi.fn(),
routeExternalPtyExit: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
registerSshFilesystemProvider: vi.fn(),
unregisterSshFilesystemProvider: vi.fn(),
@@ -92,6 +86,12 @@ vi.mock('../providers/ssh-git-dispatch', () => ({
}))
const { deployAndLaunchRelay } = await import('./ssh-relay-deploy')
// Why: the hidden-delivery gate module is intentionally real (pure state, no
// electron deps) so the SSH parity tests exercise the same gate main uses.
const { markHiddenRendererPty, setRendererPtyDeliveryInterest } =
await import('../ipc/pty-hidden-delivery-gate')
const { _resetHiddenRendererPtyDeliveryGateForTest } =
await import('../ipc/pty-hidden-delivery-gate')
const { execCommand } = await import('./ssh-relay-deploy-helpers')
const { getRemoteHostPlatform } = await import('./ssh-remote-platform')
const {
@@ -106,8 +106,6 @@ const { registerSshFilesystemProvider, unregisterSshFilesystemProvider } =
await import('../providers/ssh-filesystem-dispatch')
const { registerSshGitProvider, unregisterSshGitProvider } =
await import('../providers/ssh-git-dispatch')
const { routeExternalPtyData, routeExternalPtyReplay, routeExternalPtyExit } =
await import('../ipc/pty-renderer-delivery-router')
describe('SshRelaySession', () => {
beforeEach(() => {
@@ -117,10 +115,80 @@ describe('SshRelaySession', () => {
muxRequestMock.mockResolvedValue([])
mockDeploySuccess()
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
_resetHiddenRendererPtyDeliveryGateForTest()
})
it('routes SSH PTY data and its captured producer credit through bounded delivery', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
it('drops hidden-gated PTY data after runtime ingestion with one restore marker', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const runtime = {
onPtyData: vi.fn(() => 99),
onPtyExit: vi.fn()
}
const session = new SshRelaySession(
'target-1',
getMainWindow,
mockStore,
mockPortForward,
runtime as never
)
await session.establish(mockConn)
const ptyProvider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as {
onData: ReturnType<typeof vi.fn>
}
const onData = ptyProvider.onData.mock.calls[0]?.[0] as (payload: {
id: string
data: string
}) => void
markHiddenRendererPty('ssh-pty-1')
onData({ id: 'ssh-pty-1', data: 'hidden ssh output' })
// Runtime ingestion still ran; renderer delivery shrank to one marker.
expect(runtime.onPtyData).toHaveBeenCalledWith(
'ssh-pty-1',
'hidden ssh output',
expect.any(Number),
'hidden ssh output'.length,
undefined
)
expect(mockWindow.webContents.send).toHaveBeenCalledTimes(1)
// Why out-of-band: an in-band empty pty:data sentinel is ambiguous with
// chunks fully consumed by renderer OSC-9999 stripping.
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:modelRestoreNeeded', {
id: 'ssh-pty-1',
reason: 'hidden-drop',
markerSeq: 99
})
onData({ id: 'ssh-pty-1', data: 'more hidden ssh output' })
expect(mockWindow.webContents.send).toHaveBeenCalledTimes(1)
// Delivery interest (renderer sidecars) suppresses the gate — parity with
// the local path in ipc/pty.ts.
setRendererPtyDeliveryInterest('ssh-pty-1', true)
onData({ id: 'ssh-pty-1', data: 'sidecar ssh bytes' })
expect(mockWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', {
id: 'ssh-pty-1',
data: 'sidecar ssh bytes',
seq: 99,
rawLength: 'sidecar ssh bytes'.length
})
// Non-hidden PTYs are unaffected.
onData({ id: 'ssh-pty-2', data: 'visible ssh output' })
expect(mockWindow.webContents.send).toHaveBeenLastCalledWith('pty:data', {
id: 'ssh-pty-2',
data: 'visible ssh output',
seq: 99,
rawLength: 'visible ssh output'.length
})
})
it('keeps hidden SSH delivery when the gate kill switch is off', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
;(mockStore as unknown as { getSettings: () => unknown }).getSettings = vi.fn(() => ({
terminalHiddenDeliveryGate: false
}))
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
const ptyProvider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as {
@@ -129,16 +197,15 @@ describe('SshRelaySession', () => {
const onData = ptyProvider.onData.mock.calls[0]?.[0] as (payload: {
id: string
data: string
upstreamCredit?: { charCount: number; acknowledge(chars: number): void }
}) => void
const upstreamCredit = { charCount: 16, acknowledge: vi.fn() }
onData({ id: 'ssh-pty-1', data: 'remote PTY bytes', upstreamCredit })
markHiddenRendererPty('ssh-pty-1')
onData({ id: 'ssh-pty-1', data: 'still delivered' })
expect(routeExternalPtyData).toHaveBeenCalledWith({
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: 'ssh-pty-1',
data: 'remote PTY bytes',
upstreamCredit
data: 'still delivered',
rawLength: 'still delivered'.length
})
})
@@ -412,7 +479,7 @@ describe('SshRelaySession', () => {
})
it('forwards reconnect replay after the attach attempt is still current', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.clearAllMocks()
@@ -428,14 +495,14 @@ describe('SshRelaySession', () => {
await session.reconnect(mockConn)
expect(routeExternalPtyReplay).toHaveBeenCalledWith({
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:replay', {
id: 'ssh:target-1@@pty-1',
data: 'restored-output'
})
})
it('drops identical reconnect replay payloads inside one reconnect burst', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.clearAllMocks()
@@ -452,8 +519,11 @@ describe('SshRelaySession', () => {
await session.reconnect(mockConn)
await session.reconnect(mockConn)
const replaySends = vi
.mocked(mockWindow.webContents.send)
.mock.calls.filter(([channel]) => channel === 'pty:replay')
expect(mockAttach).toHaveBeenCalledTimes(2)
expect(routeExternalPtyReplay).toHaveBeenCalledTimes(1)
expect(replaySends).toHaveLength(1)
})
it('establish re-attaches owned PTYs after explicit disconnect', async () => {
@@ -542,7 +612,7 @@ describe('SshRelaySession', () => {
})
it('does not expire a live reused relay id when attach rejects identity mismatch', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.clearAllMocks()
@@ -577,7 +647,7 @@ describe('SshRelaySession', () => {
expect(clearProviderPtyState).not.toHaveBeenCalledWith('ssh:target-1@@pty-1')
expect(deletePtyOwnership).not.toHaveBeenCalledWith('ssh:target-1@@pty-1')
expect(mockStore.markSshRemotePtyLease).not.toHaveBeenCalledWith('target-1', 'pty-1', 'expired')
expect(routeExternalPtyExit).not.toHaveBeenCalledWith({
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:exit', {
id: 'ssh:target-1@@pty-1',
code: -1
})
@@ -648,7 +718,7 @@ describe('SshRelaySession', () => {
})
it('invalidates and broadcasts remote PTYs that cannot reattach after relay reconnect', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.clearAllMocks()
@@ -671,7 +741,7 @@ describe('SshRelaySession', () => {
expect(mockAttach).toHaveBeenCalledWith('pty-live')
expect(clearProviderPtyState).toHaveBeenCalledWith('ssh:target-1@@pty-stale')
expect(deletePtyOwnership).toHaveBeenCalledWith('ssh:target-1@@pty-stale')
expect(routeExternalPtyExit).toHaveBeenCalledWith({
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:exit', {
id: 'ssh:target-1@@pty-stale',
code: -1
})
+53 -9
View File
@@ -37,10 +37,10 @@ import {
isCurrentPtyExit
} from '../ipc/pty'
import {
routeExternalPtyData,
routeExternalPtyExit,
routeExternalPtyReplay
} from '../ipc/pty-renderer-delivery-router'
recordHiddenRendererPtyDataDrop,
shouldDropHiddenRendererPtyData
} from '../ipc/pty-hidden-delivery-gate'
import type { PtyModelRestoreNeededEvent } from '../../shared/pty-model-restore-marker'
import {
registerSshFilesystemProvider,
unregisterSshFilesystemProvider,
@@ -919,10 +919,45 @@ export class SshRelaySession {
private wireUpPtyEvents(ptyProvider: SshPtyProvider): void {
ptyProvider.onData((payload) => {
routeExternalPtyData(payload)
const rawLength = payload.sequenceChars ?? payload.data.length
const seq = this.runtime?.onPtyData(
payload.id,
payload.data,
Date.now(),
rawLength,
payload.transformed
)
const win = this.getMainWindow()
if (!win || win.isDestroyed()) {
return
}
// Why: hidden-delivery gate parity with ipc/pty.ts — latch model-restore out-of-band, never an in-band pty:data sentinel (OSC-9999-only chunks strip to empty).
const store = this.store as { getSettings?: Store['getSettings'] }
if (shouldDropHiddenRendererPtyData(payload.id, store.getSettings?.())) {
const drop = recordHiddenRendererPtyDataDrop(payload.id, rawLength)
if (drop.shouldEmitRestoreMarker) {
win.webContents.send('pty:modelRestoreNeeded', {
id: payload.id,
reason: 'hidden-drop',
...(typeof seq === 'number' ? { markerSeq: seq } : {})
} satisfies PtyModelRestoreNeededEvent)
}
return
}
if (payload.data.length > 0 || payload.transformed) {
win.webContents.send('pty:data', {
...payload,
...(typeof seq === 'number' ? { seq } : {}),
rawLength,
...(payload.transformed ? { transformed: true } : {})
})
}
})
ptyProvider.onReplay((payload) => {
routeExternalPtyReplay(payload)
const win = this.getMainWindow()
if (win && !win.isDestroyed()) {
win.webContents.send('pty:replay', payload)
}
})
ptyProvider.onExit((payload) => {
const pendingReattach = this.pendingPtyReattaches.get(payload.id)
@@ -945,7 +980,10 @@ export class SshRelaySession {
this.forwardedReattachReplayByPty.delete(payload.id)
this.store.markSshRemotePtyLease(this.targetId, relayPtyId, 'terminated')
this.runtime?.onPtyExit(payload.id, payload.code, payload.incarnationId)
routeExternalPtyExit(payload)
const win = this.getMainWindow()
if (win && !win.isDestroyed()) {
win.webContents.send('pty:exit', payload)
}
}
private replayFingerprint(data: string): string {
@@ -970,7 +1008,10 @@ export class SshRelaySession {
if (!data || !this.shouldForwardReattachReplay(appPtyId, data)) {
return
}
routeExternalPtyReplay({ id: appPtyId, data })
const win = this.getMainWindow()
if (win && !win.isDestroyed()) {
win.webContents.send('pty:replay', { id: appPtyId, data })
}
}
private async reattachKnownPtys(shouldContinue: () => boolean): Promise<void> {
@@ -1084,7 +1125,10 @@ export class SshRelaySession {
this.forwardedReattachReplayByPty.delete(appPtyId)
this.store.markSshRemotePtyLease(this.targetId, ptyId, 'expired')
// Why: reattach failure means the remote process is gone; tell the renderer to clear the stale pane.
routeExternalPtyExit({ id: appPtyId, code: -1 })
const win = this.getMainWindow()
if (win && !win.isDestroyed()) {
win.webContents.send('pty:exit', { id: appPtyId, code: -1 })
}
} finally {
if (this.pendingPtyReattaches.get(appPtyId) === pendingReattach) {
this.pendingPtyReattaches.delete(appPtyId)
@@ -1,12 +1,8 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('fs', () => ({
existsSync: vi.fn()
}))
const readRelayVersionMarkerSyncMock = vi.hoisted(() => vi.fn())
vi.mock('../../shared/relay-version-marker', () => ({
readRelayVersionMarkerSync: readRelayVersionMarkerSyncMock
existsSync: vi.fn(),
readFileSync: vi.fn()
}))
vi.mock('./ssh-relay-deploy-helpers', () => ({
@@ -17,7 +13,7 @@ vi.mock('./ssh-connection-utils', () => ({
shellEscape: (s: string) => `'${s}'`
}))
import { existsSync } from 'node:fs'
import { existsSync, readFileSync } from 'node:fs'
import {
readLocalFullVersion,
computeRemoteRelayDir,
@@ -38,11 +34,11 @@ import {
import { execCommand } from './ssh-relay-deploy-helpers'
import { getRemoteHostPlatform } from './ssh-remote-platform'
import type { SshConnection } from './ssh-connection'
import { RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL } from './ssh-relay-base-directory-listing'
const conn = {} as SshConnection
const mockExec = vi.mocked(execCommand)
const mockExists = vi.mocked(existsSync)
const mockRead = vi.mocked(readFileSync)
function decodePowerShellCommand(command: string): string {
const match = command.match(/-EncodedCommand\s+([A-Za-z0-9+/=]+)/)
@@ -56,7 +52,7 @@ describe('readLocalFullVersion', () => {
it('returns trimmed contents of the .version file', () => {
mockExists.mockReturnValue(true)
readRelayVersionMarkerSyncMock.mockReturnValue('0.1.0+deadbeef')
mockRead.mockReturnValue('0.1.0+deadbeef\n')
expect(readLocalFullVersion('/local/relay')).toBe('0.1.0+deadbeef')
})
@@ -67,7 +63,7 @@ describe('readLocalFullVersion', () => {
it('throws when the .version file is empty', () => {
mockExists.mockReturnValue(true)
readRelayVersionMarkerSyncMock.mockReturnValue('')
mockRead.mockReturnValue(' \n')
expect(() => readLocalFullVersion('/local/relay')).toThrow(/is empty/)
})
})
@@ -513,9 +509,7 @@ describe('relay GC claim', () => {
const releaseScript = decodePowerShellCommand(mockExec.mock.calls[2]?.[1] ?? '')
expect(ownerScript).toContain('Set-Content -LiteralPath')
expect(ownerScript).toContain('.gc-claim/.gc-owner')
expect(releaseScript).toContain('[System.IO.File]::Open')
expect(releaseScript).toContain('New-Object byte[] 1025')
expect(releaseScript).not.toContain('Get-Content')
expect(releaseScript).toContain('Get-Content -LiteralPath')
expect(releaseScript).toContain('-cne')
expect(releaseScript).toContain('Remove-Item -LiteralPath')
expect(releaseScript).toContain("'RELEASED'")
@@ -576,16 +570,6 @@ describe('gcOldRelayVersions', () => {
).toBe(false)
})
it('does not inspect or delete entries from a capacity-limited listing', async () => {
mockExec.mockResolvedValueOnce(
`relay-0.1.0+aaa\n${RELAY_BASE_DIRECTORY_LISTING_LIMIT_SENTINEL}\n`
)
await gcOldRelayVersions(conn, '/home/u', '/home/u/.orca-remote/relay-0.1.0+bbb')
expect(mockExec).toHaveBeenCalledTimes(1)
})
it('cleans only strict POSIX orphan tombstones even with no relay candidates', async () => {
mockExec
.mockResolvedValueOnce(
+2 -7
View File
@@ -5,8 +5,7 @@
// See: docs/ssh-relay-versioned-install-dirs.md
import { join } from 'node:path'
import { existsSync } from 'node:fs'
import { readRelayVersionMarkerSync } from '../../shared/relay-version-marker'
import { existsSync, readFileSync } from 'node:fs'
import type { SshConnection } from './ssh-connection'
import { RELAY_REMOTE_DIR } from './relay-protocol'
import { execCommand } from './ssh-relay-deploy-helpers'
@@ -27,7 +26,6 @@ import {
removeRemoteTreeCommand,
writeRemoteEmptyFileCommand
} from './ssh-remote-commands'
import { isRelayBaseDirectoryListingLimited } from './ssh-relay-base-directory-listing'
import {
getRemoteHostPlatform,
isWindowsRemoteHost,
@@ -79,7 +77,7 @@ export function readLocalFullVersion(localRelayDir: string): string {
`This usually indicates a packaging or build problem; reinstall Orca.`
)
}
const v = readRelayVersionMarkerSync(versionFile)
const v = readFileSync(versionFile, 'utf-8').trim()
if (!v) {
throw new Error(
`Orca's local relay version marker at ${versionFile} is empty. ` +
@@ -192,9 +190,6 @@ export async function gcOldRelayVersions(
} catch {
return
}
if (isRelayBaseDirectoryListingLimited(listing)) {
return
}
const entries = listing
.split('\n')
.map((s) => s.trim())
@@ -9,7 +9,6 @@ import { spawn as nodeSpawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { getCanonicalUserDataPath } from '../persistence'
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
export type RemoteOrcaCliRequest = {
argv: string[]
@@ -227,7 +226,8 @@ export async function runHostOrcaCliPassthrough(
}
class CappedOutputCollector {
private readonly output = new GrowingByteBuffer()
private readonly chunks: Buffer[] = []
private bytes = 0
private truncated = false
constructor(private readonly maxBytes: number) {}
@@ -236,17 +236,19 @@ class CappedOutputCollector {
if (this.truncated) {
return
}
const remaining = this.maxBytes - this.output.byteLength
const remaining = this.maxBytes - this.bytes
if (chunk.length >= remaining) {
this.output.append(chunk.subarray(0, remaining))
this.chunks.push(chunk.subarray(0, remaining))
this.bytes = this.maxBytes
this.truncated = true
return
}
this.output.append(chunk)
this.chunks.push(chunk)
this.bytes += chunk.length
}
toString(): string {
const text = this.output.toString()
const text = Buffer.concat(this.chunks).toString('utf8')
return this.truncated ? `${text}\n[orca ssh cli] output truncated\n` : text
}
}
-9
View File
@@ -11,7 +11,6 @@ import {
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import { GENERATED_NODE_MANAGED_FILE_MAX_BYTES } from '../generated-node-bounded-file-reader'
import {
lockAgeSecondsCommand,
tryCreateInstallLockCommand,
@@ -173,11 +172,6 @@ describe('ssh remote command builders', () => {
expect(script).toContain('markerCount===0&&pipes.length===0')
expect(script).toContain('C:\\Program Files\\nodejs')
expect(script).not.toContain('Win32_Process')
expect(script).toContain(
`readOrcaManagedFileWithinLimit(fs, path, maxBytes = ${GENERATED_NODE_MANAGED_FILE_MAX_BYTES})`
)
expect(script).toContain('readOrcaManagedFileWithinLimit(fs,path.join(dir,name)).trim()')
expect(script).not.toContain('readFileSync')
expect(listRelayBaseDirsCommand(windows, 'C:/Users/me/.orca-remote')).toContain(
'-EncodedCommand'
)
@@ -249,9 +243,6 @@ describe('ssh remote command builders', () => {
expect(posixCommand).toContain('steal_generation + 1')
expect(posixCommand).not.toContain('.next.')
expect(posixCommand).toContain('trap')
expect(posixCommand).toContain('find "$steal_parent" -mindepth 1 -maxdepth 1')
expect(posixCommand).toContain('-exec rm -rf {} +')
expect(posixCommand).not.toContain('rm -rf "$steal_root".*')
expect(windowsScript).toContain('$lock.steal')
expect(windowsScript).toContain('$stealGeneration++')
expect(windowsScript).toContain('-gt 1200')
+40 -4
View File
@@ -1,6 +1,4 @@
import type { RemoteHostPlatform } from './ssh-remote-platform'
import { getRelayBaseDirectoryListingCommand } from './ssh-relay-base-directory-listing'
import { getWindowsRelayLivenessProbeSource } from './ssh-relay-liveness-probe-source'
import { isWindowsRemoteHost, joinRemotePath, remoteDirname } from './ssh-remote-platform'
import { powerShellCommand, powerShellLiteral, powerShellNativeArg } from './ssh-remote-powershell'
import { shellEscape } from './ssh-connection-utils'
@@ -105,7 +103,17 @@ export function probeRelayInstalledCommand(
}
export function listRelayBaseDirsCommand(host: RemoteHostPlatform, baseDir: string): string {
return getRelayBaseDirectoryListingCommand(host, baseDir)
if (!isWindowsRemoteHost(host)) {
return `ls -1 ${shellEscape(baseDir)} 2>/dev/null || true`
}
return powerShellCommand(
[
`$base = ${powerShellLiteral(baseDir)}`,
'if (Test-Path -LiteralPath $base -PathType Container) {',
'Get-ChildItem -LiteralPath $base -Directory | ForEach-Object { $_.Name }',
'}'
].join(' ')
)
}
export function probeDirectoryExistsCommand(host: RemoteHostPlatform, remotePath: string): string {
@@ -146,7 +154,35 @@ export function relayLivenessProbeCommand(
if (!windowsOptions) {
return powerShellCommand("'ALIVE'")
}
const js = getWindowsRelayLivenessProbeSource()
const js = [
'const fs=require("fs"),path=require("path"),net=require("net");',
'const [dir,...seed]=process.argv.slice(1);',
'const valid=/^\\\\\\\\[.?]\\\\pipe\\\\orca-relay-[0-9a-f]{20}$/i;',
'const pipes=[];',
'let markerCount=0;',
'for(const p of seed){if(valid.test(p)&&!pipes.includes(p))pipes.push(p)}',
'try{for(const name of fs.readdirSync(dir)){',
'if(!name.startsWith(".windows-active-pipe-"))continue;',
'markerCount++;',
'const p=fs.readFileSync(path.join(dir,name),"utf8").trim();',
'if(valid.test(p)&&!pipes.includes(p))pipes.push(p)',
'}}catch{}',
'if(markerCount===0&&pipes.length===0){process.stdout.write("ALIVE");process.exit(0)}',
'let i=0;',
'function done(ok){process.stdout.write(ok?"ALIVE":"WAITING")}',
'function next(){',
'const pipe=pipes[i++];',
'if(!pipe)return done(false);',
'const s=net.connect(pipe);',
'let settled=false;',
'function finish(ok){if(settled)return;settled=true;s.destroy();if(ok)done(true);else next()}',
's.setTimeout(200);',
's.on("connect",()=>finish(true));',
's.on("timeout",()=>finish(false));',
's.on("error",()=>finish(false));',
'}',
'next();'
].join('')
return commandWithNodePath(
host,
windowsOptions.nodePath,
@@ -1,91 +0,0 @@
import { execFileSync } from 'node:child_process'
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import {
buildPosixRemoteNodeCandidateProbe,
REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL,
REMOTE_NODE_CANDIDATE_MAX_COUNT,
REMOTE_NODE_CANDIDATE_MAX_UTF8_BYTES,
REMOTE_NODE_PROFILE_MAX_BYTES
} from './ssh-remote-node-candidate-probe'
describe('POSIX remote Node candidate probe', () => {
it('uses bounded profile reads, batched directory iteration, and bounded output', () => {
const script = buildPosixRemoteNodeCandidateProbe()
expect(script).toContain('dd if="$nvm_file" bs=1024 count=65')
expect(script).toContain(`-le ${REMOTE_NODE_PROFILE_MAX_BYTES}`)
expect(script).toContain(`find "$candidate_root" -mindepth 1 -maxdepth 1 ! -name '.*'`)
expect(script).toContain('-exec sh -c')
expect(script).toContain('{} +')
expect(script).toContain('| sort')
expect(script).toContain(`candidate_count>=${REMOTE_NODE_CANDIDATE_MAX_COUNT}`)
expect(script).toContain(`output_bytes+line_bytes>${REMOTE_NODE_CANDIDATE_MAX_UTF8_BYTES}`)
expect(script).toContain(REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL)
expect(script).not.toContain('/*/')
})
it.runIf(process.platform !== 'win32')(
'accepts an exact-limit profile and ignores its first byte of overflow',
() => {
const home = mkdtempSync(join(tmpdir(), 'orca-node-profile-limit-'))
try {
const nodePath = join(home, 'tilde-nvm', 'versions', 'node', 'v20', 'bin', 'node')
mkdirSync(join(home, 'tilde-nvm', 'versions', 'node', 'v20', 'bin'), {
recursive: true
})
writeFileSync(nodePath, '#!/bin/sh\nexit 0\n')
chmodSync(nodePath, 0o755)
const assignment = 'export NVM_DIR=~/tilde-nvm\n'
const exactProfile =
assignment + '#'.repeat(REMOTE_NODE_PROFILE_MAX_BYTES - assignment.length)
writeFileSync(join(home, '.profile'), exactProfile)
const script = buildPosixRemoteNodeCandidateProbe()
const environment = { ...process.env, HOME: home, NVM_DIR: '' }
const exactOutput = execFileSync('/bin/sh', ['-c', script], {
encoding: 'utf8',
env: environment
})
expect(exactOutput.split('\n')).toContain(nodePath)
writeFileSync(join(home, '.profile'), `${exactProfile}x`)
const oversizedOutput = execFileSync('/bin/sh', ['-c', script], {
encoding: 'utf8',
env: environment
})
expect(oversizedOutput.split('\n')).not.toContain(nodePath)
} finally {
rmSync(home, { recursive: true, force: true })
}
}
)
it.runIf(process.platform !== 'win32')(
'preserves lexical version ordering within each bounded manager directory',
() => {
const home = mkdtempSync(join(tmpdir(), 'orca-node-version-order-'))
try {
const nvmDir = join(home, 'nvm')
const newer = join(nvmDir, 'versions', 'node', 'v22', 'bin', 'node')
const older = join(nvmDir, 'versions', 'node', 'v18', 'bin', 'node')
for (const nodePath of [newer, older]) {
mkdirSync(join(nodePath, '..'), { recursive: true })
writeFileSync(nodePath, '#!/bin/sh\nexit 0\n')
chmodSync(nodePath, 0o755)
}
const output = execFileSync('/bin/sh', ['-c', buildPosixRemoteNodeCandidateProbe()], {
encoding: 'utf8',
env: { ...process.env, HOME: home, NVM_DIR: nvmDir }
}).split('\n')
expect(output.indexOf(older)).toBeLessThan(output.indexOf(newer))
} finally {
rmSync(home, { recursive: true, force: true })
}
}
)
})
@@ -1,133 +0,0 @@
export const REMOTE_NODE_PROFILE_MAX_BYTES = 64 * 1024
export const REMOTE_NODE_NVM_DIR_MAX_BYTES = 4 * 1024
export const REMOTE_NODE_CANDIDATE_MAX_COUNT = 256
export const REMOTE_NODE_CANDIDATE_MAX_UTF8_BYTES = 64 * 1024
export const REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL = '__ORCA_NODE_CANDIDATES_TOO_LARGE__'
type RemoteNodeCandidateProbeOptions = {
maxCandidates?: number
maxUtf8Bytes?: number
}
function positiveInteger(value: number | undefined, fallback: number, name: string): number {
const resolved = value ?? fallback
if (!Number.isSafeInteger(resolved) || resolved < 1) {
throw new Error(`${name} must be a positive integer`)
}
return resolved
}
export function isRemoteNodeCandidateProbeLimited(output: string): boolean {
return output.split(/\r?\n/).some((line) => line.trim() === REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL)
}
export function buildPosixRemoteNodeCandidateProbe(
options?: RemoteNodeCandidateProbeOptions
): string {
const maxCandidates = positiveInteger(
options?.maxCandidates,
REMOTE_NODE_CANDIDATE_MAX_COUNT,
'maxCandidates'
)
const maxUtf8Bytes = positiveInteger(
options?.maxUtf8Bytes,
REMOTE_NODE_CANDIDATE_MAX_UTF8_BYTES,
'maxUtf8Bytes'
)
return `
nvm_dirs=\${NVM_DIR:-"$HOME/.nvm"}
nvm_dirs_bytes=$(LC_ALL=C printf %s "$nvm_dirs" | wc -c | tr -d '[:space:]')
[ "\${nvm_dirs_bytes:-${REMOTE_NODE_NVM_DIR_MAX_BYTES + 1}}" -le ${REMOTE_NODE_NVM_DIR_MAX_BYTES} ] 2>/dev/null || nvm_dirs="$HOME/.nvm"
for nvm_file in "$HOME/.profile" "$HOME/.bash_profile" "$HOME/.bashrc" "$HOME/.zprofile" "$HOME/.zshrc"
do
[ -r "$nvm_file" ] || continue
profile_bytes=$(dd if="$nvm_file" bs=1024 count=65 2>/dev/null | wc -c | tr -d '[:space:]')
[ "\${profile_bytes:-${REMOTE_NODE_PROFILE_MAX_BYTES + 1}}" -le ${REMOTE_NODE_PROFILE_MAX_BYTES} ] 2>/dev/null || continue
nvm_dir_from_file=$(dd if="$nvm_file" bs=1024 count=64 2>/dev/null | sed -n 's/^[[:space:]]*export[[:space:]][[:space:]]*NVM_DIR[[:space:]]*=[[:space:]]*//p; s/^[[:space:]]*NVM_DIR[[:space:]]*=[[:space:]]*//p' | tail -n 1)
case "$nvm_dir_from_file" in
\\"*\\") nvm_dir_from_file=\${nvm_dir_from_file#\\"}; nvm_dir_from_file=\${nvm_dir_from_file%%\\"*} ;;
\\'*\\') nvm_dir_from_file=\${nvm_dir_from_file#\\'}; nvm_dir_from_file=\${nvm_dir_from_file%%\\'*} ;;
*) nvm_dir_from_file=\${nvm_dir_from_file%%[[:space:]]*} ;;
esac
case "$nvm_dir_from_file" in
'$HOME'*) nvm_dir_from_file="$HOME\${nvm_dir_from_file#'$HOME'}" ;;
"~/"*) nvm_dir_from_file="$HOME/\${nvm_dir_from_file#\\~/}" ;;
esac
nvm_dir_bytes=$(LC_ALL=C printf %s "$nvm_dir_from_file" | wc -c | tr -d '[:space:]')
[ "\${nvm_dir_bytes:-${REMOTE_NODE_NVM_DIR_MAX_BYTES + 1}}" -le ${REMOTE_NODE_NVM_DIR_MAX_BYTES} ] 2>/dev/null || continue
[ -n "$nvm_dir_from_file" ] && nvm_dirs="$nvm_dirs
$nvm_dir_from_file"
done
find_node_candidates() {
candidate_root=$1
candidate_suffix=$2
[ -d "$candidate_root" ] || return 0
find "$candidate_root" -mindepth 1 -maxdepth 1 ! -name '.*' -exec sh -c '
candidate_suffix=$1
shift
for candidate_dir
do
candidate=$candidate_dir/$candidate_suffix
[ -x "$candidate" ] && printf "%s\\n" "$candidate"
done
' sh "$candidate_suffix" {} + | LC_ALL=C awk '
{
line_bytes=length($0)+1
if(candidate_count>=${maxCandidates} || output_bytes+line_bytes>${maxUtf8Bytes}) {
print "${REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL}"
exit
}
print
candidate_count++
output_bytes+=line_bytes
}
' | sort
}
{
command -v node 2>/dev/null
printf '%s\\n' "$nvm_dirs" | while IFS= read -r nvm_dir
do
[ -n "$nvm_dir" ] || continue
find_node_candidates "$nvm_dir/versions/node" "bin/node"
done
for candidate in \\
/usr/local/bin/node \\
/opt/homebrew/bin/node \\
"$HOME/.local/bin/node" \\
"$HOME/.fnm/aliases/default/bin/node"
do
[ -x "$candidate" ] && printf '%s\\n' "$candidate"
done
find_node_candidates "$HOME/.fnm/node-versions" "installation/bin/node"
find_node_candidates "$HOME/.local/share/fnm/node-versions" "installation/bin/node"
candidate="$HOME/.local/share/mise/shims/node"; [ -x "$candidate" ] && printf '%s\\n' "$candidate"
find_node_candidates "$HOME/.local/share/mise/installs/node" "bin/node"
candidate="$HOME/.asdf/shims/node"; [ -x "$candidate" ] && printf '%s\\n' "$candidate"
find_node_candidates "$HOME/.asdf/installs/nodejs" "bin/node"
candidate="$HOME/.volta/bin/node"; [ -x "$candidate" ] && printf '%s\\n' "$candidate"
find_node_candidates "/usr/local/n/versions/node" "bin/node"
} | LC_ALL=C awk '
{
candidate=$0
if(candidate=="${REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL}") {
print candidate
exit
}
if(candidate=="" || seen[candidate]) next
line_bytes=length(candidate)+1
if(candidate_count>=${maxCandidates} || output_bytes+line_bytes>${maxUtf8Bytes}) {
print "${REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL}"
exit
}
seen[candidate]=1
print candidate
candidate_count++
output_bytes+=line_bytes
}
'
true
`
}
@@ -4,7 +4,6 @@ import os from 'node:os'
import path from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { SshConnection } from './ssh-connection'
import { REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL } from './ssh-remote-node-candidate-probe'
import { getRemoteHostPlatform } from './ssh-remote-platform'
const execCommandMock = vi.hoisted(() => vi.fn())
@@ -100,9 +99,7 @@ describe('resolveRemoteNodePath', () => {
await resolveRemoteNodePath(conn)
const callScript = execCommandMock.mock.calls[0]![1] as string
expect(callScript).toContain(
'find_node_candidates "$HOME/.local/share/mise/installs/node" "bin/node"'
)
expect(callScript).toContain('"$HOME/.local/share/mise/installs/node"/*/bin/node')
})
it('probes asdf install directories', async () => {
@@ -113,7 +110,7 @@ describe('resolveRemoteNodePath', () => {
await resolveRemoteNodePath(conn)
const callScript = execCommandMock.mock.calls[0]![1] as string
expect(callScript).toContain('find_node_candidates "$HOME/.asdf/installs/nodejs" "bin/node"')
expect(callScript).toContain('"$HOME/.asdf/installs/nodejs"/*/bin/node')
})
it('probes volta bin directory', async () => {
@@ -137,10 +134,10 @@ describe('resolveRemoteNodePath', () => {
const callScript = execCommandMock.mock.calls[0]![1] as string
expect(callScript).toContain('nvm_dirs=${NVM_DIR:-"$HOME/.nvm"}')
expect(callScript).toContain('NVM_DIR[[:space:]]*=')
expect(callScript).toContain('find_node_candidates "$nvm_dir/versions/node" "bin/node"')
expect(callScript).toContain('"$nvm_dir"/versions/node/*/bin/node')
})
it('streams quoted version-manager directories without shell globs', async () => {
it('quotes version-manager directory prefixes while leaving globs active', async () => {
execCommandMock
.mockResolvedValueOnce('/home/u/.fnm/node-versions/v20.11.0/installation/bin/node\n')
.mockResolvedValueOnce('v20.11.0\n')
@@ -148,17 +145,10 @@ describe('resolveRemoteNodePath', () => {
await resolveRemoteNodePath(conn)
const callScript = execCommandMock.mock.calls[0]![1] as string
expect(callScript).toContain(
'find_node_candidates "$HOME/.fnm/node-versions" "installation/bin/node"'
)
expect(callScript).toContain(
'find_node_candidates "$HOME/.local/share/fnm/node-versions" "installation/bin/node"'
)
expect(callScript).toContain(
'find_node_candidates "$HOME/.local/share/mise/installs/node" "bin/node"'
)
expect(callScript).toContain('find_node_candidates "$HOME/.asdf/installs/nodejs" "bin/node"')
expect(callScript).not.toContain('/*/')
expect(callScript).toContain('"$HOME/.fnm/node-versions"/*/installation/bin/node')
expect(callScript).toContain('"$HOME/.local/share/fnm/node-versions"/*/installation/bin/node')
expect(callScript).toContain('"$HOME/.local/share/mise/installs/node"/*/bin/node')
expect(callScript).toContain('"$HOME/.asdf/installs/nodejs"/*/bin/node')
})
it('probes fnm XDG data directory installs', async () => {
@@ -286,20 +276,6 @@ describe('resolveRemoteNodePath', () => {
})
})
it('falls back without probing a partial capacity-limited candidate inventory', async () => {
execCommandMock
.mockResolvedValueOnce(`/old/node\n${REMOTE_NODE_CANDIDATE_LIMIT_SENTINEL}\n`)
.mockResolvedValueOnce('/bin/bash')
.mockResolvedValueOnce('/home/u/.nvm/versions/node/v20.11.0/bin/node\n')
.mockResolvedValueOnce('v20.11.0\n')
await expect(resolveRemoteNodePath(conn)).resolves.toBe(
'/home/u/.nvm/versions/node/v20.11.0/bin/node'
)
expect(execCommandMock.mock.calls[1]?.[1]).toBe('echo "${SHELL:-/bin/sh}"')
})
it('falls back to the login shell when every path-probe candidate is too old', async () => {
execCommandMock
.mockResolvedValueOnce('/old/node\n') // path probe
+45 -8
View File
@@ -15,10 +15,6 @@ import {
} from './ssh-remote-node-toolchain-probe'
import { isSshSessionLimitError } from './ssh-session-limit-error'
import { buildSshLoginShellCommand } from './ssh-login-shell-command'
import {
buildPosixRemoteNodeCandidateProbe,
isRemoteNodeCandidateProbeLimited
} from './ssh-remote-node-candidate-probe'
// Why: the login-shell fallback catches custom PATH setups in ~/.profile that
// the path probes don't cover. Interactive configs (conda prompts, etc.) can
@@ -62,13 +58,54 @@ async function tryResolveViaKnownPaths(
conn: SshConnection,
options?: RemoteNodeResolutionOptions
): Promise<string | null> {
const script = buildPosixRemoteNodeCandidateProbe()
const script = `
command -v node 2>/dev/null
nvm_dirs=\${NVM_DIR:-"$HOME/.nvm"}
for nvm_file in "$HOME/.profile" "$HOME/.bash_profile" "$HOME/.bashrc" "$HOME/.zprofile" "$HOME/.zshrc"
do
[ -r "$nvm_file" ] || continue
nvm_dir_from_file=$(sed -n 's/^[[:space:]]*export[[:space:]][[:space:]]*NVM_DIR[[:space:]]*=[[:space:]]*//p; s/^[[:space:]]*NVM_DIR[[:space:]]*=[[:space:]]*//p' "$nvm_file" | tail -n 1)
case "$nvm_dir_from_file" in
\\"*\\") nvm_dir_from_file=\${nvm_dir_from_file#\\"}; nvm_dir_from_file=\${nvm_dir_from_file%%\\"*} ;;
\\'*\\') nvm_dir_from_file=\${nvm_dir_from_file#\\'}; nvm_dir_from_file=\${nvm_dir_from_file%%\\'*} ;;
*) nvm_dir_from_file=\${nvm_dir_from_file%%[[:space:]]*} ;;
esac
case "$nvm_dir_from_file" in
'$HOME'*) nvm_dir_from_file="$HOME\${nvm_dir_from_file#'$HOME'}" ;;
"~/"*) nvm_dir_from_file="$HOME/\${nvm_dir_from_file#\\~/}" ;;
esac
[ -n "$nvm_dir_from_file" ] && nvm_dirs="$nvm_dirs
$nvm_dir_from_file"
done
printf '%s\\n' "$nvm_dirs" | while IFS= read -r nvm_dir
do
[ -n "$nvm_dir" ] || continue
for candidate in "$nvm_dir"/versions/node/*/bin/node
do
[ -x "$candidate" ] && printf '%s\\n' "$candidate"
done
done
for candidate in \\
/usr/local/bin/node \\
/opt/homebrew/bin/node \\
"$HOME/.local/bin/node" \\
"$HOME/.fnm/aliases/default/bin/node" \\
"$HOME/.fnm/node-versions"/*/installation/bin/node \\
"$HOME/.local/share/fnm/node-versions"/*/installation/bin/node \\
"$HOME/.local/share/mise/shims/node" \\
"$HOME/.local/share/mise/installs/node"/*/bin/node \\
"$HOME/.asdf/shims/node" \\
"$HOME/.asdf/installs/nodejs"/*/bin/node \\
"$HOME/.volta/bin/node" \\
/usr/local/n/versions/node/*/bin/node
do
[ -x "$candidate" ] && printf '%s\\n' "$candidate"
done
true
`
try {
const result = await execCommandWithOptionalOptions(conn, script, signalOnlyOptions(options))
if (isRemoteNodeCandidateProbeLimited(result)) {
return null
}
const seen = new Set<string>()
for (const line of result.split('\n')) {
const candidate = line.trim()
-8
View File
@@ -70,17 +70,9 @@ describe('runRemoteOrcaCli', () => {
getUnreadMessages: vi.fn((handle: string) =>
messages.filter((message) => message.to_handle === handle && message.read_at === null)
),
countUnreadMessages: vi.fn(
(handle: string) =>
messages.filter((message) => message.to_handle === handle && message.read_at === null)
.length
),
getAllMessagesForHandle: vi.fn((handle: string) =>
messages.filter((message) => message.to_handle === handle)
),
countAllMessagesForHandle: vi.fn(
(handle: string) => messages.filter((message) => message.to_handle === handle).length
),
markAsRead: vi.fn((ids: string[]) => {
for (const message of messages) {
if (ids.includes(message.id)) {
@@ -1,432 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
MAX_GIT_RESPONSE_STREAM_BYTES,
MAX_GIT_RESPONSE_STREAM_CHUNKS,
STREAM_CHUNK_SIZE,
MessageType,
encodeFrame
} from './relay-protocol'
import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer'
import { readFileViaStream } from './ssh-filesystem-stream-reader'
import { requestGitStreamable } from './ssh-git-response-stream-reader'
import {
MAX_PRE_METADATA_STREAM_ENCODED_BYTES,
PreMetadataStreamFrameBuffer,
SshPreMetadataStreamBudget,
SshStreamAssemblyBudget
} from './ssh-stream-reader-memory'
type Notification = { method: string; params: Record<string, unknown> | undefined }
function createStreamMux(): {
mux: Record<string, unknown>
emit: (method: string, params: Record<string, unknown>) => void
resolveRequest: (value: unknown) => void
rejectRequest: (error: Error) => void
dispose: (reason: 'shutdown' | 'connection_lost') => void
notifications: Notification[]
} {
const handlers = new Map<string, Set<(params: Record<string, unknown>) => void>>()
const disposeHandlers = new Set<(reason: 'shutdown' | 'connection_lost') => void>()
const notifications: Notification[] = []
let resolveRequest!: (value: unknown) => void
let rejectRequest!: (error: Error) => void
const requestPromise = new Promise<unknown>((resolve, reject) => {
resolveRequest = resolve
rejectRequest = reject
})
const mux = {
request: vi.fn(() => requestPromise),
notify: vi.fn((method: string, params?: Record<string, unknown>) => {
notifications.push({ method, params })
}),
onNotificationByMethod: vi.fn(
(method: string, handler: (params: Record<string, unknown>) => void) => {
const current = handlers.get(method) ?? new Set()
current.add(handler)
handlers.set(method, current)
return () => current.delete(handler)
}
),
onDispose: vi.fn((handler: (reason: 'shutdown' | 'connection_lost') => void) => {
disposeHandlers.add(handler)
return () => disposeHandlers.delete(handler)
}),
isDisposed: vi.fn(() => false)
}
return {
mux,
emit: (method, params) => {
for (const handler of handlers.get(method) ?? []) {
handler(params)
}
},
resolveRequest,
rejectRequest,
dispose: (reason) => {
for (const handler of disposeHandlers) {
handler(reason)
}
},
notifications
}
}
async function flushRequestResolution(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
}
function encodeMuxResponse(requestId: number, result: unknown, sequence: number): Buffer {
return encodeFrame(
MessageType.Regular,
sequence,
0,
Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: requestId, result }))
)
}
afterEach(() => {
vi.useRealTimers()
})
describe('SSH stream assembly aggregate budget', () => {
it('bounds concurrent reservations and releases them idempotently', () => {
const budget = new SshStreamAssemblyBudget(10)
const releaseSix = budget.reserve(6)
const releaseFour = budget.reserve(4)
expect(releaseSix).not.toBeNull()
expect(releaseFour).not.toBeNull()
expect(budget.reserve(1)).toBeNull()
expect(budget.retainedBytes).toBe(10)
releaseSix?.()
releaseSix?.()
expect(budget.retainedBytes).toBe(4)
expect(budget.reserve(6)).not.toBeNull()
})
})
describe('SSH pre-metadata stream aggregate budget', () => {
it('bounds concurrent frame buffers by count and bytes', () => {
const budget = new SshPreMetadataStreamBudget(2, 5)
const first = new PreMetadataStreamFrameBuffer(budget)
const second = new PreMetadataStreamFrameBuffer(budget)
const third = new PreMetadataStreamFrameBuffer(budget)
expect(first.push({ kind: 'chunk', params: { streamId: 1, seq: 0, data: 'abc' } })).toBe(true)
expect(second.push({ kind: 'chunk', params: { streamId: 2, seq: 0, data: 'de' } })).toBe(true)
expect(third.push({ kind: 'end', params: { streamId: 3 } })).toBe(false)
expect(budget.retainedFrames).toBe(2)
expect(budget.retainedBytes).toBe(5)
first.clear()
expect(third.push({ kind: 'end', params: { streamId: 3 } })).toBe(true)
expect(budget.retainedFrames).toBe(2)
second.clear()
third.clear()
expect(budget.retainedFrames).toBe(0)
expect(budget.retainedBytes).toBe(0)
})
it('releases shared reservations on success, stream error, request timeout, and disconnect', async () => {
const budget = new SshPreMetadataStreamBudget(4, 64)
const fileHarness = createStreamMux()
const errorHarness = createStreamMux()
const gitHarness = createStreamMux()
const disconnectHarness = createStreamMux()
const fileResult = readFileViaStream(
fileHarness.mux as never,
'empty.txt',
undefined,
new SshStreamAssemblyBudget(1),
budget
)
const errorResult = readFileViaStream(
errorHarness.mux as never,
'error.txt',
undefined,
new SshStreamAssemblyBudget(1),
budget
)
const gitResult = requestGitStreamable(
gitHarness.mux as never,
'git.diff',
{},
undefined,
new SshStreamAssemblyBudget(1),
budget
)
const disconnectResult = readFileViaStream(
disconnectHarness.mux as never,
'disconnected.txt',
undefined,
new SshStreamAssemblyBudget(1),
budget
)
fileHarness.emit('fs.streamEnd', { streamId: 1 })
errorHarness.emit('fs.streamError', { streamId: 2, message: 'remote read failed' })
gitHarness.emit('git.responseEnd', { streamId: 3 })
disconnectHarness.emit('fs.streamEnd', { streamId: 4 })
expect(budget.retainedFrames).toBe(4)
const streamRejection = expect(errorResult).rejects.toThrow('remote read failed')
const gitRejection = expect(gitResult).rejects.toThrow(/timed out/)
const disconnectRejection = expect(disconnectResult).rejects.toMatchObject({
code: 'CONNECTION_LOST'
})
fileHarness.resolveRequest({ streamId: 1, totalSize: 0, isBinary: false })
errorHarness.resolveRequest({ streamId: 2, totalSize: 1, isBinary: false })
gitHarness.rejectRequest(new Error('Request "git.diff" timed out after 30ms'))
disconnectHarness.dispose('connection_lost')
await expect(fileResult).resolves.toEqual({ content: '', isBinary: false })
await streamRejection
await gitRejection
await disconnectRejection
expect(budget.retainedFrames).toBe(0)
expect(budget.retainedBytes).toBe(0)
})
})
describe('SSH Git response stream memory bounds', () => {
it('rejects and cancels an oversized stream marker', async () => {
const harness = createStreamMux()
const result = requestGitStreamable(harness.mux as never, 'git.diff', {})
harness.resolveRequest({
__orcaGitResponseStream: {
streamId: 7,
totalBytes: MAX_GIT_RESPONSE_STREAM_BYTES + 1,
chunkCount: 1
}
})
await expect(result).rejects.toThrow(/exceeds client limit/)
expect(harness.notifications).toContainEqual({
method: 'git.cancelResponseStream',
params: { streamId: 7 }
})
})
it('rejects an excessive declared chunk count', async () => {
const harness = createStreamMux()
const result = requestGitStreamable(harness.mux as never, 'git.diff', {})
harness.resolveRequest({
__orcaGitResponseStream: {
streamId: 8,
totalBytes: 1,
chunkCount: MAX_GIT_RESPONSE_STREAM_CHUNKS + 1
}
})
await expect(result).rejects.toThrow(/exceeds client limit/)
})
it('drops an oversized foreign frame received before the stream marker', async () => {
const harness = createStreamMux()
const result = requestGitStreamable(harness.mux as never, 'git.diff', {})
harness.emit('git.responseChunk', {
streamId: 99,
seq: 0,
data: 'A'.repeat(MAX_PRE_METADATA_STREAM_ENCODED_BYTES + 1)
})
const payload = Buffer.from('{"ok":true}')
harness.resolveRequest({
__orcaGitResponseStream: { streamId: 9, totalBytes: payload.length, chunkCount: 1 }
})
await flushRequestResolution()
harness.emit('git.responseChunk', { streamId: 9, seq: 0, data: payload.toString('base64') })
harness.emit('git.responseEnd', { streamId: 9 })
await expect(result).resolves.toEqual({ ok: true })
})
it('rejects an encoded chunk larger than the remaining declared bytes', async () => {
const harness = createStreamMux()
const result = requestGitStreamable(harness.mux as never, 'git.diff', {})
harness.resolveRequest({
__orcaGitResponseStream: { streamId: 10, totalBytes: 1, chunkCount: 1 }
})
await flushRequestResolution()
harness.emit('git.responseChunk', { streamId: 10, seq: 0, data: 'A'.repeat(1_000_000) })
await expect(result).rejects.toThrow(/exceeds 1 remaining bytes/)
})
it('reassembles a valid result without changing its value', async () => {
const harness = createStreamMux()
const expected = { answer: 'unchanged', count: 2 }
const payload = Buffer.from(JSON.stringify(expected))
const budget = new SshStreamAssemblyBudget(payload.length)
const result = requestGitStreamable(harness.mux as never, 'git.diff', {}, undefined, budget)
const first = payload.subarray(0, 7)
const second = payload.subarray(7)
harness.resolveRequest({
__orcaGitResponseStream: { streamId: 11, totalBytes: payload.length, chunkCount: 2 }
})
await flushRequestResolution()
expect(budget.retainedBytes).toBe(payload.length)
harness.emit('git.responseChunk', { streamId: 11, seq: 0, data: first.toString('base64') })
harness.emit('git.responseChunk', { streamId: 11, seq: 1, data: second.toString('base64') })
harness.emit('git.responseEnd', { streamId: 11 })
await expect(result).resolves.toEqual(expected)
expect(budget.retainedBytes).toBe(0)
})
it('rejects and cancels when the aggregate assembly budget is unavailable', async () => {
const harness = createStreamMux()
const budget = new SshStreamAssemblyBudget(1)
const held = budget.reserve(1)
const result = requestGitStreamable(harness.mux as never, 'git.diff', {}, undefined, budget)
harness.resolveRequest({
__orcaGitResponseStream: { streamId: 16, totalBytes: 1, chunkCount: 1 }
})
await expect(result).rejects.toThrow(/Active SSH stream assembly would exceed/)
expect(harness.notifications).toContainEqual({
method: 'git.cancelResponseStream',
params: { streamId: 16 }
})
held?.()
})
})
describe('SSH filesystem stream memory bounds', () => {
it('releases every active assembly immediately when the shared mux disconnects', async () => {
const dataHandlers: ((data: Buffer) => void)[] = []
const transport: MultiplexerTransport = {
write: vi.fn(),
onData: (handler) => dataHandlers.push(handler),
onClose: vi.fn(),
close: vi.fn()
}
const mux = new SshChannelMultiplexer(transport)
const budget = new SshStreamAssemblyBudget(2)
const first = readFileViaStream(mux, 'first.txt', undefined, budget)
const second = readFileViaStream(mux, 'second.txt', undefined, budget)
const firstRejection = expect(first).rejects.toMatchObject({ code: 'CONNECTION_LOST' })
const secondRejection = expect(second).rejects.toMatchObject({ code: 'CONNECTION_LOST' })
dataHandlers[0](
Buffer.concat([
encodeMuxResponse(1, { streamId: 21, totalSize: 1, isBinary: false }, 1),
encodeMuxResponse(2, { streamId: 22, totalSize: 1, isBinary: false }, 2)
])
)
await flushRequestResolution()
expect(budget.retainedBytes).toBe(2)
mux.dispose('connection_lost')
expect(budget.retainedBytes).toBe(0)
await firstRejection
await secondRejection
})
it('drops an oversized foreign frame received before file metadata', async () => {
const harness = createStreamMux()
const result = readFileViaStream(harness.mux as never, 'tiny.txt')
harness.emit('fs.streamChunk', {
streamId: 90,
seq: 0,
data: 'A'.repeat(MAX_PRE_METADATA_STREAM_ENCODED_BYTES + 1)
})
harness.resolveRequest({
streamId: 12,
totalSize: 1,
isBinary: false,
resultEncoding: 'utf-8'
})
await flushRequestResolution()
harness.emit('fs.streamChunk', {
streamId: 12,
seq: 0,
data: Buffer.from('a').toString('base64')
})
harness.emit('fs.streamEnd', { streamId: 12 })
await expect(result).resolves.toEqual({ content: 'a', isBinary: false })
})
it('validates encoded size before decoding a file chunk', async () => {
const harness = createStreamMux()
const result = readFileViaStream(harness.mux as never, 'tiny.txt')
harness.resolveRequest({ streamId: 13, totalSize: 1, isBinary: false })
await flushRequestResolution()
harness.emit('fs.streamChunk', { streamId: 13, seq: 0, data: 'A'.repeat(1_000_000) })
await expect(result).rejects.toThrow(/Encoded chunk length mismatch/)
expect(harness.notifications).toContainEqual({
method: 'fs.cancelStream',
params: { streamId: 13 }
})
})
it('cancels a file stream that stops making progress', async () => {
vi.useFakeTimers()
const harness = createStreamMux()
const result = readFileViaStream(harness.mux as never, 'stalled.txt', {
inactivityTimeoutMs: 50
})
harness.resolveRequest({ streamId: 14, totalSize: 1, isBinary: false })
await flushRequestResolution()
const rejection = expect(result).rejects.toThrow(/stalled/)
await vi.advanceTimersByTimeAsync(51)
await rejection
expect(harness.notifications).toContainEqual({
method: 'fs.cancelStream',
params: { streamId: 14 }
})
})
it('resets the inactivity deadline on progress and preserves valid content', async () => {
vi.useFakeTimers()
const harness = createStreamMux()
const first = Buffer.alloc(STREAM_CHUNK_SIZE, 0x61)
const second = Buffer.from('z')
const budget = new SshStreamAssemblyBudget(first.length + second.length)
const result = readFileViaStream(
harness.mux as never,
'progress.txt',
{ inactivityTimeoutMs: 50 },
budget
)
harness.resolveRequest({
streamId: 15,
totalSize: first.length + second.length,
isBinary: false,
resultEncoding: 'utf-8'
})
await flushRequestResolution()
expect(budget.retainedBytes).toBe(first.length + second.length)
await vi.advanceTimersByTimeAsync(40)
harness.emit('fs.streamChunk', { streamId: 15, seq: 0, data: first.toString('base64') })
await vi.advanceTimersByTimeAsync(40)
harness.emit('fs.streamChunk', { streamId: 15, seq: 1, data: second.toString('base64') })
harness.emit('fs.streamEnd', { streamId: 15 })
await expect(result).resolves.toEqual({
content: `${'a'.repeat(STREAM_CHUNK_SIZE)}z`,
isBinary: false
})
expect(budget.retainedBytes).toBe(0)
})
it('rejects and cancels when file assembly would exceed the aggregate budget', async () => {
const harness = createStreamMux()
const budget = new SshStreamAssemblyBudget(1)
const held = budget.reserve(1)
const result = readFileViaStream(harness.mux as never, 'tiny.txt', undefined, budget)
harness.resolveRequest({ streamId: 17, totalSize: 1, isBinary: false })
await expect(result).rejects.toThrow(/Active SSH stream assembly would exceed/)
expect(harness.notifications).toContainEqual({
method: 'fs.cancelStream',
params: { streamId: 17 }
})
held?.()
})
})
-205
View File
@@ -1,205 +0,0 @@
export const STREAM_READER_INACTIVITY_TIMEOUT_MS = 30_000
export const MAX_PRE_METADATA_STREAM_FRAMES = 64
export const MAX_PRE_METADATA_STREAM_ENCODED_BYTES = 8 * 1024 * 1024
export const MAX_SSH_PRE_METADATA_STREAM_FRAMES = 256
export const MAX_SSH_PRE_METADATA_STREAM_RETAINED_BYTES = 32 * 1024 * 1024
export const MAX_SSH_STREAM_ASSEMBLY_BYTES = 128 * 1024 * 1024
export type BufferedStreamFrame = {
kind: 'chunk' | 'end' | 'error'
params: Record<string, unknown>
}
type RetainedStreamFrame = {
frame: BufferedStreamFrame
encodedBytes: number
release: () => void
}
export class SshPreMetadataStreamBudget {
private frames = 0
private bytes = 0
constructor(
readonly maxFrames: number,
readonly maxBytes: number
) {}
reserve(bytes: number): (() => void) | null {
if (
!Number.isSafeInteger(bytes) ||
bytes < 0 ||
this.frames >= this.maxFrames ||
bytes > this.maxBytes - this.bytes
) {
return null
}
this.frames += 1
this.bytes += bytes
let released = false
return () => {
if (released) {
return
}
released = true
this.frames -= 1
this.bytes -= bytes
}
}
get retainedFrames(): number {
return this.frames
}
get retainedBytes(): number {
return this.bytes
}
}
export const defaultSshPreMetadataStreamBudget = new SshPreMetadataStreamBudget(
MAX_SSH_PRE_METADATA_STREAM_FRAMES,
MAX_SSH_PRE_METADATA_STREAM_RETAINED_BYTES
)
export class PreMetadataStreamFrameBuffer {
private frames: RetainedStreamFrame[] = []
private encodedBytes = 0
constructor(private readonly budget: SshPreMetadataStreamBudget) {}
push(frame: BufferedStreamFrame): boolean {
const retainedFrame = retainStreamFrameFields(frame)
const frameBytes = retainedStreamFrameBytes(retainedFrame)
if (frameBytes > MAX_PRE_METADATA_STREAM_ENCODED_BYTES) {
return false
}
while (
this.frames.length >= MAX_PRE_METADATA_STREAM_FRAMES ||
this.encodedBytes + frameBytes > MAX_PRE_METADATA_STREAM_ENCODED_BYTES
) {
this.shift()
}
let release = this.budget.reserve(frameBytes)
while (!release && this.frames.length > 0) {
this.shift()
release = this.budget.reserve(frameBytes)
}
if (!release) {
return false
}
this.frames.push({ frame: retainedFrame, encodedBytes: frameBytes, release })
this.encodedBytes += frameBytes
return true
}
shift(): BufferedStreamFrame | undefined {
const retained = this.frames.shift()
if (retained) {
this.encodedBytes -= retained.encodedBytes
retained.release()
}
return retained?.frame
}
get length(): number {
return this.frames.length
}
clear(): void {
while (this.frames.length > 0) {
this.shift()
}
}
}
function retainStreamFrameFields(frame: BufferedStreamFrame): BufferedStreamFrame {
const { params } = frame
if (frame.kind === 'chunk') {
return {
kind: frame.kind,
params: {
...(typeof params.streamId === 'number' ? { streamId: params.streamId } : {}),
...(typeof params.seq === 'number' ? { seq: params.seq } : {}),
...(typeof params.data === 'string' ? { data: params.data } : {})
}
}
}
if (frame.kind === 'error') {
return {
kind: frame.kind,
params: {
...(typeof params.streamId === 'number' ? { streamId: params.streamId } : {}),
...(typeof params.message === 'string' ? { message: params.message } : {}),
...(typeof params.code === 'string' ? { code: params.code } : {})
}
}
}
return {
kind: frame.kind,
params: typeof params.streamId === 'number' ? { streamId: params.streamId } : {}
}
}
function retainedStreamFrameBytes(frame: BufferedStreamFrame): number {
let bytes = 0
for (const value of Object.values(frame.params)) {
if (typeof value === 'string') {
bytes += Buffer.byteLength(value, 'utf-8')
}
}
return bytes
}
export class SshStreamAssemblyBudget {
private retained = 0
constructor(readonly maxBytes: number) {}
reserve(bytes: number): (() => void) | null {
if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > this.maxBytes - this.retained) {
return null
}
this.retained += bytes
let released = false
return () => {
if (released) {
return
}
released = true
this.retained -= bytes
}
}
get retainedBytes(): number {
return this.retained
}
}
export const defaultSshStreamAssemblyBudget = new SshStreamAssemblyBudget(
MAX_SSH_STREAM_ASSEMBLY_BYTES
)
export function base64EncodedLength(rawBytes: number): number {
return Math.ceil(rawBytes / 3) * 4
}
export function createStreamInactivityDeadline(
timeoutMs: number,
onTimeout: () => void
): { reset: () => void; clear: () => void } {
let timer: ReturnType<typeof setTimeout> | null = null
const clear = (): void => {
if (timer) {
clearTimeout(timer)
timer = null
}
}
return {
reset: () => {
clear()
timer = setTimeout(onTimeout, timeoutMs)
timer.unref?.()
},
clear
}
}
+1 -20
View File
@@ -1,4 +1,4 @@
import { mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { EventEmitter } from 'node:events'
@@ -37,7 +37,6 @@ import { spawnSystemSshPortForward } from './system-ssh-forward-process'
import { getRemoteHostPlatform } from './ssh-remote-platform'
import type { SshTarget } from '../../shared/ssh-types'
import type { SystemSshResolvedConfig } from './ssh-control-socket'
import { SSH_DIRECTORY_TRANSFER_LIMITS } from './ssh-directory-transfer-budget'
const SYSTEM_SSH_PATH =
process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh'
@@ -799,24 +798,6 @@ describe('spawnSystemSsh', () => {
)
})
it('rejects an oversized Windows upload file before starting SSH', async () => {
const localDir = mkdtempSync(join(tmpdir(), 'orca-system-ssh-upload-'))
const oversized = join(localDir, 'oversized.bin')
writeFileSync(oversized, '')
truncateSync(oversized, SSH_DIRECTORY_TRANSFER_LIMITS.maximumFileBytes + 1)
try {
await expect(
uploadDirectoryViaSystemSsh(createTarget(), localDir, 'C:/Users/me/.orca-remote/relay', {
hostPlatform: getRemoteHostPlatform('win32-x64')
})
).rejects.toMatchObject({ reason: 'file' })
expect(spawnMock).not.toHaveBeenCalled()
} finally {
rmSync(localDir, { recursive: true, force: true })
}
})
it('forces standalone SSH for Windows upload packages when requested', async () => {
const localDir = mkdtempSync(join(tmpdir(), 'orca-system-ssh-upload-'))
writeFileSync(join(localDir, 'relay.js'), 'console.log("relay")')
@@ -1,28 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
windowsRelayTailLogCommand,
WINDOWS_RELAY_LOG_TAIL_MAX_BYTES
} from './ssh-windows-log-tail-command'
function decodePowerShellCommand(command: string): string {
const match = command.match(/-EncodedCommand\s+([A-Za-z0-9+/=]+)/)
return match ? Buffer.from(match[1], 'base64').toString('utf16le') : ''
}
describe('Windows relay log tail command', () => {
it('reads a fixed byte tail without line materialization', () => {
const script = decodePowerShellCommand(
windowsRelayTailLogCommand('C:/Users/u/relay.log', 'C:/Users/u/relay.err.log')
)
expect(script).toContain(
`[Math]::Min([long]${WINDOWS_RELAY_LOG_TAIL_MAX_BYTES}, $stream.Length)`
)
expect(script).toContain('$stream.Seek(-[long]$readLength')
expect(script).toContain('$stream.Read($buffer, $offset, $readLength - $offset)')
expect(script).toContain('[System.IO.FileShare]::ReadWrite')
expect(script).toContain('--- stderr ---')
expect(script).not.toContain('Get-Content')
expect(script).not.toContain('-Tail 20')
})
})
@@ -1,31 +0,0 @@
import { powerShellCommand, powerShellLiteral } from './ssh-remote-powershell'
export const WINDOWS_RELAY_LOG_TAIL_MAX_BYTES = 64 * 1024
export function windowsRelayTailLogCommand(logFile: string, errFile: string): string {
const script = [
'function Read-OrcaLogTail {',
'param([string]$Path, [string]$Missing)',
'if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $Missing }',
'$stream = $null',
'try {',
'$stream = [System.IO.File]::Open($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)',
`$readLength = [int][Math]::Min([long]${WINDOWS_RELAY_LOG_TAIL_MAX_BYTES}, $stream.Length)`,
'$buffer = New-Object byte[] $readLength',
'$null = $stream.Seek(-[long]$readLength, [System.IO.SeekOrigin]::End)',
'$offset = 0',
'while ($offset -lt $readLength) {',
'$bytesRead = $stream.Read($buffer, $offset, $readLength - $offset)',
'if ($bytesRead -eq 0) { break }',
'$offset += $bytesRead',
'}',
'return [System.Text.Encoding]::UTF8.GetString($buffer, 0, $offset)',
"} catch { return '(unable to read log)' }",
'finally { if ($null -ne $stream) { $stream.Dispose() } }',
'}',
`[Console]::Out.Write((Read-OrcaLogTail ${powerShellLiteral(logFile)} '(no stdout log)'))`,
'[Console]::Out.Write("`n--- stderr ---`n")',
`[Console]::Out.Write((Read-OrcaLogTail ${powerShellLiteral(errFile)} '(no stderr log)'))`
].join('\n')
return powerShellCommand(script)
}
+21 -61
View File
@@ -1,10 +1,9 @@
import { spawn } from 'node:child_process'
import { constants } from 'node:fs'
import { lstat, open, opendir } from 'node:fs/promises'
import { lstat, open, readdir } from 'node:fs/promises'
import { join as pathJoin } from 'node:path'
import { pipeline } from 'node:stream/promises'
import type { SshTarget } from '../../shared/ssh-types'
import { stringifyJsonWithinByteLimit } from '../../shared/node-bounded-json-stringify'
import { shellEscape, wrapRemoteCommandForPosixShell } from './ssh-connection-utils'
import { findSystemSsh } from './system-ssh-binary'
import {
@@ -24,10 +23,6 @@ import {
type ProcessResult
} from './system-ssh-operation-lifecycle'
import { writeBufferViaSystemSsh } from './system-ssh-file-binary-transfer'
import {
SshDirectoryTransferBudget,
WINDOWS_SSH_UPLOAD_PACKAGE_MAX_BYTES
} from './ssh-directory-transfer-budget'
type SystemSshOperationOptions = SystemSshBuildArgsOptions & {
signal?: AbortSignal
@@ -118,9 +113,7 @@ async function uploadDirectoryViaSystemSshWindows(
localDir,
remoteDir,
hostPlatform,
options.signal,
new SshDirectoryTransferBudget(),
0
options.signal
)
await writeWindowsUploadPackageViaSystemSsh(target, entries, options)
}
@@ -140,42 +133,26 @@ async function collectWindowsUploadEntries(
localDir: string,
remoteDir: string,
hostPlatform: RemoteHostPlatform,
signal: AbortSignal | undefined,
budget: SshDirectoryTransferBudget,
depth: number
signal: AbortSignal | undefined
): Promise<WindowsUploadEntry[]> {
budget.recordPath(remoteDir, depth, { countEntry: depth !== 0 })
const entries: WindowsUploadEntry[] = [{ kind: 'directory', path: remoteDir }]
const directory = await opendir(localDir)
try {
for await (const entry of directory) {
throwIfAborted(signal)
const localPath = pathJoin(localDir, entry.name)
const remotePath = joinRemotePath(hostPlatform, remoteDir, entry.name)
const statResult = await lstat(localPath)
if (statResult.isSymbolicLink() || (!statResult.isFile() && !statResult.isDirectory())) {
continue
}
if (statResult.isDirectory()) {
entries.push(
...(await collectWindowsUploadEntries(
localPath,
remotePath,
hostPlatform,
signal,
budget,
depth + 1
))
)
continue
}
budget.recordPath(remotePath, depth + 1)
budget.recordFile(statResult.size)
const buffer = await readLocalUploadFile(localPath, statResult)
entries.push({ kind: 'file', path: remotePath, contentsBase64: buffer.toString('base64') })
const dirEntries = await readdir(localDir, { withFileTypes: true })
for (const entry of dirEntries) {
throwIfAborted(signal)
const localPath = pathJoin(localDir, entry.name)
const remotePath = joinRemotePath(hostPlatform, remoteDir, entry.name)
const statResult = await lstat(localPath)
if (statResult.isSymbolicLink() || (!statResult.isFile() && !statResult.isDirectory())) {
continue
}
} finally {
await directory.close().catch(() => undefined)
if (statResult.isDirectory()) {
entries.push(
...(await collectWindowsUploadEntries(localPath, remotePath, hostPlatform, signal))
)
continue
}
const buffer = await readLocalUploadFile(localPath, statResult)
entries.push({ kind: 'file', path: remotePath, contentsBase64: buffer.toString('base64') })
}
return entries
}
@@ -186,10 +163,6 @@ async function writeWindowsUploadPackageViaSystemSsh(
options: SystemSshOperationOptions
): Promise<void> {
throwIfAborted(options.signal)
const serialized = stringifyJsonWithinByteLimit(
entries,
WINDOWS_SSH_UPLOAD_PACKAGE_MAX_BYTES
).serialized
const channel = spawnSystemSshCommand(target, makeWindowsUploadPackageCommand(), {
wrapCommand: false,
...getSystemSshBuildArgsFromOperationOptions(options)
@@ -200,7 +173,7 @@ async function writeWindowsUploadPackageViaSystemSsh(
waitForChannelClose(channel, 'windows relay upload')
)
if (!options.signal?.aborted) {
channel.stdin.end(serialized)
channel.stdin.end(JSON.stringify(entries))
}
await closePromise
}
@@ -220,20 +193,7 @@ async function readLocalUploadFile(
) {
throw new Error(`File changed during upload: ${localPath}`)
}
const buffer = Buffer.allocUnsafe(openedStat.size)
let offset = 0
while (offset < buffer.length) {
const result = await handle.read(buffer, offset, buffer.length - offset, offset)
if (result.bytesRead === 0) {
throw new Error(`File changed during upload: ${localPath}`)
}
offset += result.bytesRead
}
const probe = Buffer.allocUnsafe(1)
if ((await handle.read(probe, 0, 1, offset)).bytesRead !== 0) {
throw new Error(`File changed during upload: ${localPath}`)
}
return buffer
return await handle.readFile()
} finally {
await handle.close()
}
@@ -34,7 +34,6 @@ import {
waitForSystemSshForwardStop
} from './system-ssh-forward-process'
import type { SshTarget } from '../../shared/ssh-types'
import { SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES } from './system-ssh-output-tail'
const SYSTEM_SSH_PATH =
process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh'
@@ -248,22 +247,6 @@ describe('system SSH forward process', () => {
await expect(pending).rejects.toThrow('bind: Address already in use')
})
it('keeps only a bounded stderr tail while waiting for forward startup', async () => {
vi.useFakeTimers()
const child = createFakeProcess()
connectMock.mockReturnValue(createFakeSocket())
const pending = waitForSystemSshForwardStartup(child as never, 3000)
child.stderr.emit(
'data',
Buffer.from(`HEAD${'x'.repeat(SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES)}TAIL`)
)
child.emit('exit', 255)
await expect(pending).rejects.toThrow('TAIL')
await expect(pending).rejects.not.toThrow('HEAD')
})
it('rejects startup when the ssh process emits an error', async () => {
vi.useFakeTimers()
const child = createFakeProcess()
+3 -4
View File
@@ -2,7 +2,6 @@ import { spawn, type ChildProcess } from 'node:child_process'
import { connect, createServer } from 'node:net'
import { buildSshArgs, findSystemSsh, type SystemSshBuildArgsOptions } from './ssh-system-fallback'
import type { SshTarget } from '../../shared/ssh-types'
import { SystemSshOutputTail } from './system-ssh-output-tail'
export const SYSTEM_SSH_FORWARD_STARTUP_GRACE_MS = 750
export const SYSTEM_SSH_FORWARD_LISTENER_PROBE_INTERVAL_MS = 50
@@ -104,7 +103,7 @@ export function waitForSystemSshForwardStartup(
localPort: number
): Promise<void> {
return new Promise((resolve, reject) => {
const stderr = new SystemSshOutputTail()
let stderr = ''
let settled = false
let probeTimer: ReturnType<typeof setTimeout> | null = null
let graceTimer: ReturnType<typeof setTimeout> | null = null
@@ -128,13 +127,13 @@ export function waitForSystemSshForwardStartup(
callback()
}
const onStderr = (chunk: Buffer): void => {
stderr.push(chunk)
stderr += chunk.toString('utf-8')
}
const onError = (error: Error): void => {
finish(() => reject(error))
}
const onExit = (code: number | null): void => {
finish(() => reject(systemSshForwardError(code, stderr.toString())))
finish(() => reject(systemSshForwardError(code, stderr)))
}
const scheduleProbe = (): void => {
probeTimer = setTimeout(() => {
@@ -1,50 +0,0 @@
import { EventEmitter } from 'node:events'
import { describe, expect, it } from 'vitest'
import { waitForChannelClose, waitForProcess } from './system-ssh-operation-lifecycle'
import { SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES } from './system-ssh-output-tail'
function createProcess(): EventEmitter & {
stderr: EventEmitter
} {
return Object.assign(new EventEmitter(), { stderr: new EventEmitter() })
}
function createChannel(): EventEmitter & {
stderr: EventEmitter
} {
return Object.assign(new EventEmitter(), { stderr: new EventEmitter() })
}
describe('system SSH operation output capture', () => {
it('returns a bounded stderr tail for successful child processes', async () => {
const process = createProcess()
const result = waitForProcess(process as never, 'test process')
process.stderr.emit(
'data',
Buffer.from(`HEAD${'x'.repeat(SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES)}TAIL`)
)
process.emit('close', 0)
await expect(result).resolves.toMatchObject({
label: 'test process',
stderr: expect.stringContaining('TAIL')
})
expect((await result).stderr).not.toContain('HEAD')
})
it('uses the bounded stderr tail in channel failure diagnostics', async () => {
const channel = createChannel()
const result = waitForChannelClose(channel as never, 'test channel')
channel.stderr.emit(
'data',
Buffer.from(`HEAD${'x'.repeat(SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES)}TAIL`)
)
channel.emit('close', 1, null)
await expect(result).rejects.toThrow('TAIL')
await expect(result).rejects.not.toThrow('HEAD')
expect(channel.stderr.listenerCount('data')).toBe(0)
})
})
@@ -1,6 +1,5 @@
import type { ChildProcess } from 'node:child_process'
import type { SystemSshCommandChannel } from './system-ssh-command'
import { SystemSshOutputTail } from './system-ssh-output-tail'
export type ProcessResult = { label: string; stderr: string }
@@ -9,7 +8,7 @@ export function waitForChannelClose(
label: string
): Promise<void> {
return new Promise((resolve, reject) => {
const stderr = new SystemSshOutputTail()
let stderr = ''
const cleanup = (): void => {
channel.stderr.off('data', onStderrData)
channel.off('error', onError)
@@ -20,7 +19,7 @@ export function waitForChannelClose(
fn(val as never)
}
const onStderrData = (data: Buffer): void => {
stderr.push(data)
stderr += data.toString('utf-8')
}
const onError = (err: Error): void => {
settle(reject, err)
@@ -28,7 +27,7 @@ export function waitForChannelClose(
const onClose = (code: number | null, signal?: NodeJS.Signals | null): void => {
if (code !== 0) {
const detail = code === null ? `signal ${signal ?? 'unknown'}` : `exit ${code}`
settle(reject, new Error(`${label} failed (${detail}): ${stderr.toString().trim()}`))
settle(reject, new Error(`${label} failed (${detail}): ${stderr.trim()}`))
return
}
settle(resolve)
@@ -42,7 +41,7 @@ export function waitForChannelClose(
export function waitForProcess(proc: ChildProcess, label: string): Promise<ProcessResult> {
return new Promise((resolve, reject) => {
const stderr = new SystemSshOutputTail()
let stderr = ''
const cleanup = (): void => {
proc.stderr?.off('data', onStderrData)
proc.off('error', onError)
@@ -53,17 +52,17 @@ export function waitForProcess(proc: ChildProcess, label: string): Promise<Proce
fn(val as never)
}
const onStderrData = (data: Buffer): void => {
stderr.push(data)
stderr += data.toString('utf-8')
}
const onError = (err: Error): void => {
settle(reject, err)
}
const onClose = (code: number | null): void => {
if (code !== 0) {
settle(reject, new Error(`${label} failed (exit ${code}): ${stderr.toString().trim()}`))
settle(reject, new Error(`${label} failed (exit ${code}): ${stderr.trim()}`))
return
}
settle(resolve, { label, stderr: stderr.toString() })
settle(resolve, { label, stderr })
}
proc.stderr?.on('data', onStderrData)
@@ -1,30 +0,0 @@
import { describe, expect, it } from 'vitest'
import { SystemSshOutputTail } from './system-ssh-output-tail'
describe('SystemSshOutputTail', () => {
it('preserves ordinary output exactly', () => {
const output = new SystemSshOutputTail(16)
output.push('first ')
output.push(Buffer.from('second'))
expect(output.toString()).toBe('first second')
})
it('keeps only the newest bytes after many chunks', () => {
const output = new SystemSshOutputTail(8)
for (const chunk of ['123', '456', '789', 'tail']) {
output.push(chunk)
}
expect(output.toString()).toBe('[earlier system SSH output truncated]\n6789tail')
})
it('copies a bounded slice instead of retaining a large chunk backing buffer', () => {
const output = new SystemSshOutputTail(4)
const large = Buffer.from('discard-prefix-tail')
output.push(large)
large.fill(0)
expect(output.toString()).toBe('[earlier system SSH output truncated]\ntail')
})
})
-37
View File
@@ -1,37 +0,0 @@
export const SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES = 64 * 1024
const TRUNCATION_NOTICE = '[earlier system SSH output truncated]\n'
export class SystemSshOutputTail {
private buffer = Buffer.alloc(0)
private truncated = false
constructor(private readonly maxBytes = SYSTEM_SSH_OUTPUT_TAIL_MAX_BYTES) {
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
throw new RangeError('System SSH output tail limit must be a non-negative safe integer')
}
}
push(value: Buffer | string): void {
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value)
if (chunk.byteLength >= this.maxBytes) {
const hadBufferedOutput = this.buffer.byteLength > 0
this.buffer = Buffer.from(chunk.subarray(chunk.byteLength - this.maxBytes))
this.truncated ||= hadBufferedOutput || chunk.byteLength > this.maxBytes
return
}
const combinedBytes = this.buffer.byteLength + chunk.byteLength
if (combinedBytes <= this.maxBytes) {
this.buffer = Buffer.concat([this.buffer, chunk], combinedBytes)
return
}
const discardBytes = combinedBytes - this.maxBytes
this.buffer = Buffer.concat([this.buffer.subarray(discardBytes), chunk], this.maxBytes)
this.truncated = true
}
toString(): string {
const text = this.buffer.toString('utf8')
return this.truncated ? `${TRUNCATION_NOTICE}${text}` : text
}
}
@@ -8,7 +8,6 @@ import type {
SshPortForwardProvider,
StartedPortForward
} from './ssh-port-forward-provider'
import { SystemSshOutputTail } from './system-ssh-output-tail'
export class SystemSshPortForwardProvider implements SshPortForwardProvider {
canHandle(conn: SshConnection): boolean {
@@ -34,9 +33,17 @@ export class SystemSshPortForwardProvider implements SshPortForwardProvider {
)
await forward.waitForStartup()
const stderr = new SystemSshOutputTail()
// Why: this stderr stays attached for the forward's whole lifetime but is
// only used to build the exit-error detail, so keep a bounded tail — a chatty
// remote sshd could otherwise grow it unbounded on a long-lived forward
// (mirrors MAX_RELAY_STARTUP_BUFFER_BYTES in ssh-relay-deploy-helpers).
const MAX_STDERR_TAIL_BYTES = 64 * 1024
let stderr = ''
const onStderr = (chunk: Buffer): void => {
stderr.push(chunk)
stderr += chunk.toString('utf-8')
if (stderr.length > MAX_STDERR_TAIL_BYTES) {
stderr = stderr.slice(-MAX_STDERR_TAIL_BYTES)
}
}
forward.process.stderr?.on('data', onStderr)
@@ -53,7 +60,7 @@ export class SystemSshPortForwardProvider implements SshPortForwardProvider {
forward.process.stderr?.off('data', onStderr)
options.onUnexpectedClose?.(entry, {
kind: 'unexpected-exit',
detail: systemSshForwardError(code, stderr.toString()).message
detail: systemSshForwardError(code, stderr).message
})
})