feat(ssh): bound relay PTY output end to end (#11005)

* docs: design SSH relay PTY backpressure

* fix(ssh): bound relay frame decoding

* fix(relay): bound PTY output publication

* fix(ssh): bound PTY model admission

* fix(ssh): settle closed model admissions

* feat(ssh): negotiate bounded PTY consumer sessions

* fix(ssh): fence exit on renderer settlement

* feat(ssh): track PTY source credit end to end

* fix(ssh): recover bounded PTY output across reconnect

* feat(ssh): complete relay PTY output backpressure

* fix(ssh): close final PTY source credit races

* docs(ssh): record final backpressure validation

* feat(ssh): complete relay PTY source-credit lifecycle

* test(ssh): complete provider notification fixture

* fix(ssh): preserve terminal source credit across rotation

* fix(ssh): fail closed on recovery cancellation

* fix(ssh): prioritize mux control writes after drain

* fix(ssh): retire canceled relay restore deliveries

* fix(ssh): order exit cancellation cleanup

* fix(ssh): gate provisional source activation

* test(ssh): register mux drain-priority coverage

* fix(ssh): type stale owner recovery mismatches

* fix(ssh): close projection replacement races

* fix(relay): contain streaming edge failures

* fix(ssh): secure relay endpoint credentials

* docs(ssh): reconcile final backpressure lifecycle

* fix(ssh): bound main IPC output lifecycle

* fix(ssh): close recovery ownership gaps

* docs(ssh): record exact artifact validation

* fix(ssh): reject reclaimed snapshot replacements

* fix(ssh): fence model admission across reconnect

* fix(ssh): contain migration failure per PTY

* docs(ssh): record final exact-head validation

* test(ssh): align deploy fixtures with credential publication

* feat(ssh): add per-target bounded output setting

* fix(ssh): close source recovery review gaps

* fix(ssh): latch source credit environment override

* feat(ssh): make PTY source credit the default

* docs(ssh): record always-on relay validation

* docs(ssh): bind validation to current main

* test(ssh): grant source credit in IPC fixture

* test(ssh): grant source credit in fake relay

---------

Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
Jinjing
2026-07-29 17:03:15 -07:00
committed by GitHub
co-authored by OrcaWin
parent c676b6aa3b
commit 5f7807497e
189 changed files with 34164 additions and 2410 deletions
+264
View File
@@ -0,0 +1,264 @@
import {
containFrameDecoderContinuation,
publishFrameDecoderError,
type DecodedFrame,
type FrameDecoderOptions
} from '../../shared/relay-frame-decoder-contract'
import { RelayFrameBuffer } from '../../shared/relay-frame-buffer'
export {
FrameDecoderContinuationError,
type DecodedFrame,
type FrameDecoderOptions
} from '../../shared/relay-frame-decoder-contract'
export const HEADER_LENGTH = 13
export const MAX_MESSAGE_SIZE = 16 * 1024 * 1024
export const FRAME_DECODER_MAX_FRAMES_PER_TURN = 64
export const FRAME_DECODER_MAX_BYTES_PER_TURN = MAX_MESSAGE_SIZE + HEADER_LENGTH
export const FRAME_DECODER_MAX_TURN_MS = 4,
FRAME_DECODER_MAX_RETAINED_BYTES = MAX_MESSAGE_SIZE + HEADER_LENGTH + 1024 * 1024
export class FrameDecoder {
private readonly buffer = new RelayFrameBuffer()
private oversizedPayloadBytesRemaining = 0
private onFrame: (frame: DecodedFrame) => void
private onError: ((err: Error) => void) | null
private maxFramesPerTurn: number
private maxBytesPerTurn: number
private maxTurnMs: number
private now: () => number
private schedule: (callback: () => void) => unknown
private cancelScheduled: (handle: unknown) => void
private pause: (() => void) | null
private resume: (() => void) | null
private continuationHandle: unknown
private continuationHandleAssigned = false
private continuationScheduled = false
private paused = false
private draining = false
private generation = 0
constructor(
onFrame: (frame: DecodedFrame) => void,
onError?: (err: Error) => void,
options: FrameDecoderOptions = {}
) {
this.onFrame = onFrame
this.onError = onError ?? null
this.maxFramesPerTurn = positiveLimit(
options.maxFramesPerTurn,
FRAME_DECODER_MAX_FRAMES_PER_TURN
)
this.maxBytesPerTurn = positiveLimit(options.maxBytesPerTurn, FRAME_DECODER_MAX_BYTES_PER_TURN)
this.maxTurnMs = positiveLimit(options.maxTurnMs, FRAME_DECODER_MAX_TURN_MS)
this.now = options.now ?? Date.now
this.schedule = options.schedule ?? ((callback) => setImmediate(callback))
this.cancelScheduled =
options.cancelScheduled ?? ((handle) => clearImmediate(handle as NodeJS.Immediate))
this.pause = options.pause ?? null
this.resume = options.resume ?? null
}
feed(chunk: Buffer | Uint8Array): void {
const buf = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
const retained = this.buffer.length + buf.length
if (retained > FRAME_DECODER_MAX_RETAINED_BYTES) {
this.reset()
publishFrameDecoderError(
this.onError,
new Error(`Frame decoder retained-input limit exceeded: ${retained}`)
)
return
}
if (buf.length > 0) {
this.buffer.append(buf)
}
if (!this.draining && !this.continuationScheduled) {
this.drainTurn()
}
}
reset(): void {
this.generation += 1
this.cancelContinuation()
this.buffer.clear()
this.oversizedPayloadBytesRemaining = 0
this.releasePause()
}
drain(): Buffer {
const out = this.buffer.drain()
this.reset()
return out
}
private drainTurn(): void {
if (this.draining) {
return
}
this.draining = true
const generation = this.generation
const startedAt = this.now()
let frames = 0
let bytes = 0
try {
while (generation === this.generation) {
if (
frames >= this.maxFramesPerTurn ||
bytes >= this.maxBytesPerTurn ||
(frames > 0 && this.now() - startedAt >= this.maxTurnMs)
) {
break
}
const discarded = this.discardOversizedPayload(bytes)
if (discarded > 0) {
bytes += discarded
continue
}
if (this.buffer.length < HEADER_LENGTH) {
break
}
const header = this.buffer.peek(HEADER_LENGTH)
const length = header.readUInt32BE(9)
if (length > MAX_MESSAGE_SIZE) {
this.buffer.discard(HEADER_LENGTH)
this.oversizedPayloadBytesRemaining = length
bytes += HEADER_LENGTH
publishFrameDecoderError(
this.onError,
new Error(`Frame payload too large: ${length} bytes — discarded`)
)
continue
}
const totalLength = HEADER_LENGTH + length
if (this.buffer.length < totalLength) {
break
}
if (frames > 0 && bytes + totalLength > this.maxBytesPerTurn) {
break
}
const framed = this.buffer.take(totalLength)
frames += 1
bytes += totalLength
this.onFrame({
type: framed[0],
id: framed.readUInt32BE(1),
ack: framed.readUInt32BE(5),
payload: framed.subarray(HEADER_LENGTH, totalLength)
})
}
} finally {
this.draining = false
}
if (generation !== this.generation) {
return
}
if (this.hasRunnableWork()) {
this.scheduleContinuation()
} else {
this.releasePause()
}
}
private discardOversizedPayload(bytes: number): number {
if (this.oversizedPayloadBytesRemaining === 0 || this.buffer.length === 0) {
return 0
}
const discarded = Math.min(
this.oversizedPayloadBytesRemaining,
this.buffer.length,
Math.max(1, this.maxBytesPerTurn - bytes)
)
this.buffer.discard(discarded)
this.oversizedPayloadBytesRemaining -= discarded
return discarded
}
private hasRunnableWork(): boolean {
if (this.oversizedPayloadBytesRemaining > 0) {
return this.buffer.length > 0
}
if (this.buffer.length < HEADER_LENGTH) {
return false
}
const length = this.buffer.peek(HEADER_LENGTH).readUInt32BE(9)
return length > MAX_MESSAGE_SIZE || this.buffer.length >= HEADER_LENGTH + length
}
private scheduleContinuation(): void {
if (this.continuationScheduled) {
return
}
const generation = this.generation
this.continuationScheduled = true
try {
this.acquirePause()
} catch (error) {
this.continuationScheduled = false
throw error
}
if (generation !== this.generation) {
this.continuationScheduled = false
return
}
try {
this.continuationHandle = this.schedule(() => {
if (!this.continuationScheduled || generation !== this.generation) {
return
}
this.continuationScheduled = false
this.continuationHandleAssigned = false
this.continuationHandle = undefined
try {
this.drainTurn()
} catch (error) {
containFrameDecoderContinuation(() => this.reset(), this.onError, error)
}
})
this.continuationHandleAssigned = true
} catch (error) {
this.continuationScheduled = false
this.continuationHandle = undefined
this.releasePause()
throw error
}
}
private cancelContinuation(): void {
if (!this.continuationScheduled) {
return
}
this.continuationScheduled = false
if (this.continuationHandleAssigned) {
this.cancelScheduled(this.continuationHandle)
}
this.continuationHandleAssigned = false
this.continuationHandle = undefined
}
private acquirePause(): void {
if (!this.paused) {
this.paused = true
try {
this.pause?.()
} catch (error) {
this.paused = false
throw error
}
}
}
private releasePause(): void {
if (this.paused) {
this.paused = false
this.resume?.()
}
}
}
const positiveLimit = (value: number | undefined, fallback: number): number =>
value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback
@@ -0,0 +1,263 @@
import { describe, expect, it, vi } from 'vitest'
import {
FrameDecoder,
FrameDecoderContinuationError,
FRAME_DECODER_MAX_RETAINED_BYTES,
HEADER_LENGTH,
MAX_MESSAGE_SIZE,
MessageType,
encodeFrame,
type DecodedFrame
} from './relay-protocol'
function createScheduler(): {
schedule: (callback: () => void) => number
cancel: (handle: unknown) => void
runNext: () => void
pending: () => number
} {
let nextHandle = 1
const callbacks = new Map<number, () => void>()
return {
schedule: (callback) => {
const handle = nextHandle++
callbacks.set(handle, callback)
return handle
},
cancel: (handle) => callbacks.delete(handle as number),
runNext: () => {
const entry = callbacks.entries().next().value as [number, () => void] | undefined
if (!entry) {
throw new Error('No decoder continuation scheduled')
}
callbacks.delete(entry[0])
entry[1]()
},
pending: () => callbacks.size
}
}
function frame(id: number, payload = `${id}`): Buffer {
return encodeFrame(MessageType.Regular, id, 0, Buffer.from(payload))
}
describe('FrameDecoder bounded turns', () => {
it('retains at most one maximum frame plus one MiB of partial input', () => {
expect(FRAME_DECODER_MAX_RETAINED_BYTES).toBe(MAX_MESSAGE_SIZE + HEADER_LENGTH + 1024 * 1024)
const maximumFrame = encodeFrame(MessageType.Regular, 1, 0, Buffer.alloc(MAX_MESSAGE_SIZE))
const acceptedError = vi.fn()
const accepted = new FrameDecoder(vi.fn(), acceptedError)
accepted.feed(Buffer.concat([maximumFrame, Buffer.alloc(1024 * 1024)]))
expect(acceptedError).not.toHaveBeenCalled()
expect(accepted.drain()).toHaveLength(1024 * 1024)
const excessError = vi.fn()
const excess = new FrameDecoder(vi.fn(), excessError)
excess.feed(Buffer.concat([maximumFrame, Buffer.alloc(1024 * 1024 + 1)]))
expect(excessError).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining('retained-input') })
)
expect(excess.drain()).toHaveLength(0)
})
it('fails closed when one delivered chunk exceeds retained-input capacity', () => {
const onError = vi.fn()
const decoder = new FrameDecoder(vi.fn(), onError)
decoder.feed(Buffer.alloc(FRAME_DECODER_MAX_RETAINED_BYTES + 1))
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining('retained-input') })
)
expect(decoder.drain()).toHaveLength(0)
})
it('emits the first frame synchronously and preserves order through self-pause', () => {
const scheduler = createScheduler()
const seen: number[] = []
let decoder: FrameDecoder
const pause = vi.fn(() => decoder.feed(frame(4)))
const resume = vi.fn()
decoder = new FrameDecoder((decoded) => seen.push(decoded.id), undefined, {
maxFramesPerTurn: 1,
schedule: scheduler.schedule,
cancelScheduled: scheduler.cancel,
pause,
resume
})
decoder.feed(Buffer.concat([frame(1), frame(2), frame(3)]))
expect(seen).toEqual([1])
expect(pause).toHaveBeenCalledTimes(1)
expect(scheduler.pending()).toBe(1)
scheduler.runNext()
scheduler.runNext()
scheduler.runNext()
expect(seen).toEqual([1, 2, 3, 4])
expect(pause).toHaveBeenCalledTimes(1)
expect(resume).toHaveBeenCalledTimes(1)
expect(scheduler.pending()).toBe(0)
})
it('bounds decoded bytes and time independently from the frame count', () => {
const byteScheduler = createScheduler()
const byteSeen: number[] = []
const first = frame(1, 'one')
const second = frame(2, 'two')
const byteDecoder = new FrameDecoder((decoded) => byteSeen.push(decoded.id), undefined, {
maxFramesPerTurn: 64,
maxBytesPerTurn: first.length,
schedule: byteScheduler.schedule,
cancelScheduled: byteScheduler.cancel
})
byteDecoder.feed(Buffer.concat([first, second]))
expect(byteSeen).toEqual([1])
byteScheduler.runNext()
expect(byteSeen).toEqual([1, 2])
const timeScheduler = createScheduler()
const timeSeen: number[] = []
let nowCalls = 0
const timeDecoder = new FrameDecoder((decoded) => timeSeen.push(decoded.id), undefined, {
maxFramesPerTurn: 64,
maxBytesPerTurn: MAX_MESSAGE_SIZE + HEADER_LENGTH,
maxTurnMs: 4,
now: () => (nowCalls++ === 0 ? 0 : 5),
schedule: timeScheduler.schedule,
cancelScheduled: timeScheduler.cancel
})
timeDecoder.feed(Buffer.concat([frame(3), frame(4)]))
expect(timeSeen).toEqual([3])
timeScheduler.runNext()
expect(timeSeen).toEqual([3, 4])
})
it('releases its pause epoch when continuation scheduling throws', () => {
const pause = vi.fn()
const resume = vi.fn()
const decoder = new FrameDecoder(() => {}, undefined, {
maxFramesPerTurn: 1,
pause,
resume,
schedule: () => {
throw new Error('scheduler unavailable')
}
})
expect(() => decoder.feed(Buffer.concat([frame(1), frame(2)]))).toThrow('scheduler unavailable')
expect(pause).toHaveBeenCalledTimes(1)
expect(resume).toHaveBeenCalledTimes(1)
decoder.reset()
expect(resume).toHaveBeenCalledTimes(1)
})
it('contains a throwing continuation, resets residue, and reports one typed error', () => {
const scheduler = createScheduler()
const seen: number[] = []
const onError = vi.fn()
const pause = vi.fn()
const resume = vi.fn()
const decoder = new FrameDecoder(
(decoded) => {
if (decoded.id === 2) {
throw new Error('frame owner failed')
}
seen.push(decoded.id)
},
onError,
{
maxFramesPerTurn: 1,
schedule: scheduler.schedule,
cancelScheduled: scheduler.cancel,
pause,
resume
}
)
decoder.feed(Buffer.concat([frame(1), frame(2), frame(3)]))
expect(() => scheduler.runNext()).not.toThrow()
expect(seen).toEqual([1])
expect(onError).toHaveBeenCalledExactlyOnceWith(expect.any(FrameDecoderContinuationError))
expect(onError.mock.calls[0]?.[0]).toMatchObject({
name: 'FrameDecoderContinuationError',
cause: expect.objectContaining({ message: 'frame owner failed' })
})
expect(pause).toHaveBeenCalledTimes(1)
expect(resume).toHaveBeenCalledTimes(1)
expect(scheduler.pending()).toBe(0)
expect(decoder.drain()).toHaveLength(0)
decoder.feed(frame(4))
expect(seen).toEqual([1, 4])
})
it('keeps reads active for partial frames and incrementally discards oversized payloads', () => {
const errors: Error[] = []
const seen: DecodedFrame[] = []
const pause = vi.fn()
const decoder = new FrameDecoder(
(decoded) => seen.push(decoded),
(error) => errors.push(error),
{ pause }
)
const valid = frame(2, 'complete')
decoder.feed(valid.subarray(0, HEADER_LENGTH + 2))
expect(seen).toHaveLength(0)
expect(pause).not.toHaveBeenCalled()
decoder.feed(valid.subarray(HEADER_LENGTH + 2))
expect(seen.map(({ id }) => id)).toEqual([2])
const oversizedHeader = Buffer.alloc(HEADER_LENGTH)
oversizedHeader[0] = MessageType.Regular
oversizedHeader.writeUInt32BE(3, 1)
oversizedHeader.writeUInt32BE(MAX_MESSAGE_SIZE + 1, 9)
decoder.feed(Buffer.concat([oversizedHeader, Buffer.alloc(32)]))
expect(errors).toHaveLength(1)
expect(pause).not.toHaveBeenCalled()
decoder.reset()
decoder.feed(frame(4, 'after-reset'))
expect(seen.map(({ id }) => id)).toEqual([2, 4])
})
it('drain and reset cancel continuation ownership without replaying residue', () => {
const scheduler = createScheduler()
const seen: number[] = []
const resume = vi.fn()
const cancel = vi.fn(scheduler.cancel)
const decoder = new FrameDecoder((decoded) => seen.push(decoded.id), undefined, {
maxFramesPerTurn: 1,
schedule: scheduler.schedule,
cancelScheduled: cancel,
resume
})
const second = frame(2, 'residue')
decoder.feed(Buffer.concat([frame(1), second]))
const residue = decoder.drain()
expect(seen).toEqual([1])
expect(residue.equals(second)).toBe(true)
expect(cancel).toHaveBeenCalledTimes(1)
expect(resume).toHaveBeenCalledTimes(1)
expect(scheduler.pending()).toBe(0)
decoder.feed(Buffer.concat([frame(3), frame(4)]))
decoder.reset()
expect(cancel).toHaveBeenCalledTimes(2)
expect(scheduler.pending()).toBe(0)
decoder.feed(frame(5))
expect(seen).toEqual([1, 3, 5])
})
})
+22 -147
View File
@@ -3,17 +3,34 @@
// See design-ssh-support.md § JSON-RPC Protocol Specification.
import { DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS } from '../../shared/ssh-types'
import {
FrameDecoder,
FrameDecoderContinuationError,
HEADER_LENGTH,
MAX_MESSAGE_SIZE,
FRAME_DECODER_MAX_FRAMES_PER_TURN,
FRAME_DECODER_MAX_BYTES_PER_TURN,
FRAME_DECODER_MAX_TURN_MS,
FRAME_DECODER_MAX_RETAINED_BYTES
} from './relay-frame-decoder'
export {
FrameDecoder,
FrameDecoderContinuationError,
HEADER_LENGTH,
MAX_MESSAGE_SIZE,
FRAME_DECODER_MAX_FRAMES_PER_TURN,
FRAME_DECODER_MAX_BYTES_PER_TURN,
FRAME_DECODER_MAX_TURN_MS,
FRAME_DECODER_MAX_RETAINED_BYTES
}
export type { DecodedFrame, FrameDecoderOptions } from './relay-frame-decoder'
export const RELAY_VERSION = '0.1.0'
export const RELAY_SENTINEL = `ORCA-RELAY v${RELAY_VERSION} READY\n`
export const RELAY_SENTINEL_TIMEOUT_MS = 10_000
export const RELAY_REMOTE_DIR = '.orca-remote'
// ── Framing constants (VS Code ProtocolConstants) ───────────────────
export const HEADER_LENGTH = 13
export const MAX_MESSAGE_SIZE = 16 * 1024 * 1024 // 16 MB
/** Message type byte. */
export const MessageType = {
Regular: 1,
@@ -155,148 +172,6 @@ export function encodeKeepAliveFrame(id: number, ack: number): Buffer {
return encodeFrame(MessageType.KeepAlive, id, ack, Buffer.alloc(0))
}
export type DecodedFrame = {
type: number
id: number
ack: number
payload: Buffer
}
/**
* Incremental frame parser. Feed it chunks of data; it emits complete frames.
*/
export class FrameDecoder {
// Why: feed() runs on the Electron main thread for every SSH channel data
// event. Rebuilding one contiguous buffer per feed (Buffer.concat) re-copies
// every already-buffered byte for each incoming ~32KB TCP chunk — O(n²) per
// large frame (a 340KB fs.streamChunk frame cost ~2MB of memcpy). A chunk
// list assembles each frame exactly once instead.
private chunks: Buffer[] = []
private bufferedLength = 0
private onFrame: (frame: DecodedFrame) => void
private onError: ((err: Error) => void) | null
constructor(onFrame: (frame: DecodedFrame) => void, onError?: (err: Error) => void) {
this.onFrame = onFrame
this.onError = onError ?? null
}
feed(chunk: Buffer | Uint8Array): void {
const buf = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
if (buf.length > 0) {
this.chunks.push(buf)
this.bufferedLength += buf.length
}
while (this.bufferedLength >= HEADER_LENGTH) {
const header = this.peekBytes(HEADER_LENGTH)
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) {
this.discardBytes(totalLength)
const err = new Error(`Frame payload too large: ${length} bytes — discarded`)
if (this.onError) {
this.onError(err)
}
continue
}
const framed = this.takeBytes(totalLength)
const frame: DecodedFrame = {
type: framed[0],
id: framed.readUInt32BE(1),
ack: framed.readUInt32BE(5),
payload: framed.subarray(HEADER_LENGTH, totalLength)
}
this.onFrame(frame)
}
}
reset(): void {
this.chunks = []
this.bufferedLength = 0
}
/** View of the first `count` buffered bytes without consuming them. */
private peekBytes(count: number): Buffer {
const first = this.chunks[0]
if (first.length >= count) {
return first
}
const out = Buffer.allocUnsafe(count)
let copied = 0
for (const part of this.chunks) {
copied += part.copy(out, copied, 0, Math.min(part.length, count - copied))
if (copied >= count) {
break
}
}
return out
}
/** Consume and return the first `count` buffered bytes (single copy). */
private takeBytes(count: number): Buffer {
const first = this.chunks[0]
if (first.length === count) {
this.chunks.shift()
this.bufferedLength -= count
return first
}
if (first.length > count) {
this.chunks[0] = first.subarray(count)
this.bufferedLength -= count
return first.subarray(0, count)
}
const out = Buffer.allocUnsafe(count)
let copied = 0
while (copied < count) {
const part = this.chunks[0]
const take = Math.min(part.length, count - copied)
part.copy(out, copied, 0, take)
copied += take
if (take === part.length) {
this.chunks.shift()
} else {
this.chunks[0] = part.subarray(take)
}
}
this.bufferedLength -= count
return out
}
/** Consume the first `count` buffered bytes without assembling them. */
private discardBytes(count: number): void {
let remaining = count
while (remaining > 0) {
const part = this.chunks[0]
if (part.length <= remaining) {
this.chunks.shift()
remaining -= part.length
} else {
this.chunks[0] = part.subarray(remaining)
remaining = 0
}
}
this.bufferedLength -= count
}
}
/**
* Parse a JSON-RPC message from a frame payload.
*/
export function parseJsonRpcMessage(payload: Buffer): JsonRpcMessage {
const text = payload.toString('utf-8')
const msg = JSON.parse(text) as JsonRpcMessage
@@ -0,0 +1,203 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer'
import { encodeFrame, encodeKeepAliveFrame, HEADER_LENGTH, MessageType } from './relay-protocol'
type MockTransport = MultiplexerTransport & {
data: (chunk: Buffer) => void
written: Buffer[]
pauseReads: ReturnType<typeof vi.fn>
resumeReads: ReturnType<typeof vi.fn>
}
type MuxInternals = {
nextOutgoingSeq: number
highestAckedBySelf: number
lastReceivedAt: number
decoderReadPaused: boolean
unackedTimestamps: Map<number, number>
}
function createTransport(): MockTransport {
let onData: (chunk: Buffer) => void = () => {}
const written: Buffer[] = []
const pauseReads = vi.fn()
const resumeReads = vi.fn()
return {
write: (data) => {
written.push(data)
},
onData: (callback) => {
onData = callback
},
onClose: () => {},
pauseReads,
resumeReads,
data: (chunk) => onData(chunk),
written
}
}
function internals(mux: SshChannelMultiplexer): MuxInternals {
return mux as unknown as MuxInternals
}
describe('SshChannelMultiplexer backpressure hardening', () => {
let transport: MockTransport
let mux: SshChannelMultiplexer
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(0)
transport = createTransport()
mux = new SshChannelMultiplexer(transport)
})
afterEach(() => {
mux.dispose()
vi.restoreAllMocks()
vi.useRealTimers()
})
it('clamps ack=0xffffffff and deletes only retained sequence keys', () => {
mux.notify('one')
mux.notify('two')
const state = internals(mux)
const deleteSpy = vi.spyOn(state.unackedTimestamps, 'delete')
transport.data(encodeKeepAliveFrame(1, 0xffffffff))
expect(deleteSpy).toHaveBeenCalledTimes(2)
expect(state.unackedTimestamps.size).toBe(0)
expect(state.highestAckedBySelf).toBe(state.nextOutgoingSeq - 1)
})
it('caps timestamps while preserving a reserved liveness entry', () => {
for (let i = 0; i < 5000; i += 1) {
mux.notify('bounded')
}
const state = internals(mux)
expect(state.unackedTimestamps.size).toBe(4095)
expect(state.unackedTimestamps.has(1)).toBe(true)
void mux.probeLiveness(60_000)
expect(state.unackedTimestamps.size).toBe(4096)
void mux.probeLiveness(60_000)
expect(state.unackedTimestamps.size).toBe(4096)
})
it('suppresses timeout while self-paused and rebases both clocks on resume', () => {
mux.dispose()
const continuations: (() => void)[] = []
vi.spyOn(globalThis, 'setImmediate').mockImplementation(
(callback: (...args: never[]) => void) => {
continuations.push(callback)
return {} as NodeJS.Immediate
}
)
transport = createTransport()
mux = new SshChannelMultiplexer(transport)
mux.notify('tracked')
const incoming = Buffer.concat(
Array.from({ length: 65 }, (_, index) => encodeKeepAliveFrame(index + 1, 0))
)
transport.data(incoming)
const state = internals(mux)
expect(state.decoderReadPaused).toBe(true)
expect(transport.pauseReads).toHaveBeenCalledTimes(1)
expect(continuations).toHaveLength(1)
vi.advanceTimersByTime(25_000)
expect(mux.isDisposed()).toBe(false)
continuations.shift()!()
const resumedAt = Date.now()
expect(state.decoderReadPaused).toBe(false)
expect(transport.resumeReads).toHaveBeenCalledTimes(1)
expect(state.lastReceivedAt).toBe(resumedAt)
expect(new Set(state.unackedTimestamps.values())).toEqual(new Set([resumedAt]))
})
it('keeps frame dispatch ordered across a decoder continuation', () => {
const seen: number[] = []
mux.onNotification((_method, params) => seen.push(params.index as number))
const frames = Array.from({ length: 65 }, (_, index) => {
const payload = Buffer.from(
JSON.stringify({ jsonrpc: '2.0', method: 'ordered', params: { index } })
)
return encodeFrame(MessageType.Regular, index + 1, 0, payload)
})
transport.data(Buffer.concat(frames))
expect(seen).toEqual(Array.from({ length: 64 }, (_, index) => index))
vi.runAllTicks()
vi.advanceTimersByTime(0)
expect(seen).toEqual(Array.from({ length: 65 }, (_, index) => index))
})
it('prioritizes source ACK and control while preserving FIFO and ordinary progress', async () => {
mux.dispose()
const written: Buffer[] = []
let drain = (): void => {}
let deliver = (_data: Buffer): void => {}
transport = {
write: (data) => {
written.push(data)
return written.length !== 1
},
onDrain: (callback) => {
drain = callback
},
onData: (callback) => {
deliver = callback
},
onClose: vi.fn(),
pauseReads: vi.fn<() => void>(),
resumeReads: vi.fn<() => void>(),
data: vi.fn<(chunk: Buffer) => void>(),
written,
close: vi.fn()
}
mux = new SshChannelMultiplexer(transport)
mux.onRequest('client.control', () => ({ accepted: true }))
const controller = new AbortController()
mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-1' })
mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-2' })
mux.notify('pty.data', { id: 'pty-1', data: 'ordinary-3' })
mux.notify('pty.ackData', { acknowledgements: [] })
const request = mux.request('fs.scan', {}, { signal: controller.signal })
controller.abort()
mux.notify('pty.exit', { id: 'pty-1', code: 0 })
const remoteRequest = Buffer.from(
JSON.stringify({ jsonrpc: '2.0', id: 91, method: 'client.control' })
)
deliver(encodeFrame(MessageType.Regular, 1, 0, remoteRequest))
await Promise.resolve()
await Promise.resolve()
expect(written).toHaveLength(1)
drain()
const payloads = written.map((frame) =>
JSON.parse(frame.subarray(HEADER_LENGTH, HEADER_LENGTH + frame.readUInt32BE(9)).toString())
)
expect(
payloads.map((payload) =>
payload.method === 'pty.data'
? `pty.data:${payload.params.data}`
: (payload.method ?? `response:${payload.id}`)
)
).toEqual([
'pty.data:ordinary-1',
'pty.ackData',
'fs.scan',
'rpc.cancel',
'pty.exit',
'pty.data:ordinary-2',
'response:91',
'pty.data:ordinary-3'
])
await expect(request).rejects.toMatchObject({ name: 'AbortError' })
})
})
@@ -0,0 +1,93 @@
import { describe, expect, it, vi } from 'vitest'
import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer'
function transportHarness(): {
transport: MultiplexerTransport
settlements: ((result: { ok: true } | { ok: false; error: Error }) => void)[]
} {
const settlements: ((result: { ok: true } | { ok: false; error: Error }) => void)[] = []
return {
transport: {
write: (_data, onSettled) => {
if (onSettled) {
settlements.push(onSettled)
}
},
supportsWriteSettlement: true,
onData: vi.fn(),
onClose: vi.fn()
},
settlements
}
}
describe('SshChannelMultiplexer notification settlement', () => {
it('reports publication only from the transport write callback', () => {
const harness = transportHarness()
const mux = new SshChannelMultiplexer(harness.transport)
const settled = vi.fn()
mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled)
expect(settled).not.toHaveBeenCalled()
harness.settlements[0]({ ok: true })
expect(settled).toHaveBeenCalledWith({ ok: true })
mux.dispose()
})
it('reports a synchronous write failure without publishing success', () => {
const error = new Error('write failed')
const mux = new SshChannelMultiplexer({
write: () => {
throw error
},
supportsWriteSettlement: true,
onData: vi.fn(),
onClose: vi.fn()
})
const settled = vi.fn()
mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled)
expect(settled).toHaveBeenCalledWith({ ok: false, error })
expect(mux.isDisposed()).toBe(true)
})
it('settles once when a hostile transport invokes its callback and then throws', () => {
const mux = new SshChannelMultiplexer({
write: (_data, onSettled) => {
onSettled?.({ ok: true })
throw new Error('late throw')
},
supportsWriteSettlement: true,
onData: vi.fn(),
onClose: vi.fn()
})
const settled = vi.fn()
mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled)
expect(settled).toHaveBeenCalledOnce()
expect(settled).toHaveBeenCalledWith({ ok: true })
})
it('fails an unsettled publication when the multiplexer is disposed', () => {
const close = vi.fn()
const mux = new SshChannelMultiplexer({
write: () => false,
supportsWriteSettlement: true,
onDrain: vi.fn(),
onData: vi.fn(),
onClose: vi.fn(),
close
})
const settled = vi.fn()
mux.notifyWithSettlement('pty.ackData', { acknowledgements: [] }, settled)
expect(settled).not.toHaveBeenCalled()
mux.dispose()
expect(settled).toHaveBeenCalledWith({
ok: false,
error: expect.objectContaining({ code: 'DISPOSED' })
})
expect(close).toHaveBeenCalledOnce()
})
})
+63 -1
View File
@@ -12,7 +12,9 @@ function createMockTransport(): MultiplexerTransport & {
const written: Buffer[] = []
return {
write: (data: Buffer) => written.push(data),
write: (data: Buffer) => {
written.push(data)
},
onData: (cb) => dataCallbacks.push(cb),
onClose: (cb) => closeCallbacks.push(cb),
dataCallbacks,
@@ -69,6 +71,7 @@ type MuxInternals = {
disposeHandlers: unknown[]
lastReceivedAt: number
unackedTimestamps: Map<number, number>
writerSaturated: boolean
}
function getMuxInternals(instance: SshChannelMultiplexer): MuxInternals {
@@ -123,6 +126,28 @@ describe('SshChannelMultiplexer', () => {
await expect(promise).rejects.toThrow('PTY allocation failed')
})
it('runs beforeResolve before an adjacent notification in the same decoder turn', async () => {
const order: string[] = []
mux.onNotification(() => order.push('notification'))
const promise = mux.request(
'pty.attach',
{ id: 'pty-1' },
{
beforeResolve: () => order.push('beforeResolve')
}
)
transport.dataCallbacks[0](
Buffer.concat([
makeResponseFrame(1, { incarnationId: 'incarnation-1' }, 1),
makeNotificationFrame('pty.data', { id: 'pty-1', data: 'first' }, 2)
])
)
expect(order).toEqual(['beforeResolve', 'notification'])
await expect(promise).resolves.toEqual({ incarnationId: 'incarnation-1' })
})
it('times out after 30s with no response', async () => {
const promise = mux.request('pty.spawn')
@@ -328,6 +353,43 @@ describe('SshChannelMultiplexer', () => {
vi.advanceTimersByTime(25_000)
expect(mux.isDisposed()).toBe(true)
})
it('suppresses false death while locally saturated and rebases both clocks on drain', () => {
mux.dispose()
let drain = (): void => {}
const written: Buffer[] = []
const saturatedTransport: MultiplexerTransport = {
write: (data) => {
written.push(data)
return false
},
supportsWriteSettlement: true,
onDrain: (callback) => {
drain = callback
},
onData: vi.fn(),
onClose: vi.fn()
}
mux = new SshChannelMultiplexer(saturatedTransport)
vi.advanceTimersByTime(5_000)
expect(getMuxInternals(mux).writerSaturated).toBe(true)
vi.advanceTimersByTime(25_000)
expect(mux.isDisposed()).toBe(false)
expect(written).toHaveLength(1)
drain()
const resumedAt = Date.now()
const internals = getMuxInternals(mux)
expect(internals.writerSaturated).toBe(false)
expect(internals.lastReceivedAt).toBe(resumedAt)
expect(new Set(internals.unackedTimestamps.values())).toEqual(new Set([resumedAt]))
vi.advanceTimersByTime(20_000)
expect(mux.isDisposed()).toBe(false)
vi.advanceTimersByTime(5_000)
expect(mux.isDisposed()).toBe(true)
})
})
describe('wake guard (timer pause across system sleep, #7773)', () => {
+140 -38
View File
@@ -14,26 +14,36 @@ import {
type JsonRpcResponse,
type JsonRpcNotification
} from './relay-protocol'
import {
SshMultiplexerTransportWriter,
type MultiplexerTransport,
type MultiplexerWriteSettlement,
type MultiplexerWriterLane
} from './ssh-multiplexer-transport-writer'
export type MultiplexerTransport = {
write: (data: Buffer) => void
onData: (cb: (data: Buffer) => void) => void
onClose: (cb: () => void) => void
close?: () => void
}
export type { MultiplexerTransport, MultiplexerWriteSettlement }
type PendingRequest = {
resolve: (result: unknown) => void
reject: (error: Error) => void
beforeResolve?: (result: unknown) => void
timer: ReturnType<typeof setTimeout>
cleanup: () => void
}
export type SshMultiplexerRequestOptions = {
signal?: AbortSignal
timeoutMs?: number
beforeResolve?: (result: unknown) => void
}
export type NotificationHandler = (method: string, params: Record<string, unknown>) => void
export type MethodNotificationHandler = (params: Record<string, unknown>) => void
export type RequestHandler = (params: Record<string, unknown>) => Promise<unknown> | unknown
const REQUEST_TIMEOUT_MS = 30_000
const MAX_ORDINARY_UNACKED_TIMESTAMPS = 4095
const MAX_UNACKED_TIMESTAMPS = MAX_ORDINARY_UNACKED_TIMESTAMPS + 1
// Why: a tick gap far beyond the interval means the process was paused
// (system sleep, App Nap timer throttling) — not that the link is dead (#7773).
const WAKE_GAP_MS = KEEPALIVE_SEND_MS * 3
@@ -41,6 +51,7 @@ const WAKE_GAP_MS = KEEPALIVE_SEND_MS * 3
export class SshChannelMultiplexer {
private decoder: FrameDecoder
private transport: MultiplexerTransport
private writer: SshMultiplexerTransportWriter
private nextRequestId = 1
private nextOutgoingSeq = 1
private highestReceivedSeq = 0
@@ -56,6 +67,8 @@ export class SshChannelMultiplexer {
private disposeHandlers: ((reason: 'shutdown' | 'connection_lost') => void)[] = []
private connectionHealthTimer: ReturnType<typeof setInterval> | null = null
private disposed = false
private decoderReadPaused = false
private writerSaturated = false
// Track the oldest unacked outgoing message timestamp
private unackedTimestamps = new Map<number, number>()
@@ -66,10 +79,19 @@ export class SshChannelMultiplexer {
constructor(transport: MultiplexerTransport) {
this.transport = transport
this.writer = new SshMultiplexerTransportWriter(
transport,
(error) => this.handleProtocolError(error),
(saturated) => this.handleWriterSaturationChange(saturated)
)
this.decoder = new FrameDecoder(
(frame) => this.handleFrame(frame),
(err) => this.handleProtocolError(err)
(err) => this.handleProtocolError(err),
{
pause: () => this.pauseDecoderReads(),
resume: () => this.resumeDecoderReads()
}
)
transport.onData((data) => {
@@ -158,7 +180,7 @@ export class SshChannelMultiplexer {
async request(
method: string,
params?: Record<string, unknown>,
options?: { signal?: AbortSignal; timeoutMs?: number }
options?: SshMultiplexerRequestOptions
): Promise<unknown> {
if (this.disposed) {
throw new Error('Multiplexer disposed')
@@ -215,7 +237,13 @@ export class SshChannelMultiplexer {
if (options?.signal) {
options.signal.addEventListener('abort', onAbort, { once: true })
}
this.pendingRequests.set(id, { resolve, reject, timer, cleanup })
this.pendingRequests.set(id, {
resolve,
reject,
beforeResolve: options?.beforeResolve,
timer,
cleanup
})
this.sendMessage(msg)
})
}
@@ -237,6 +265,25 @@ export class SshChannelMultiplexer {
this.sendMessage(msg)
}
notifyWithSettlement(
method: string,
params: Record<string, unknown> | undefined,
onSettled: (result: { ok: true } | { ok: false; error: Error }) => void
): void {
if (this.disposed) {
onSettled({ ok: false, error: new Error('Multiplexer disposed') })
return
}
this.sendMessage(
{
jsonrpc: '2.0',
method,
...(params !== undefined ? { params } : {})
},
onSettled
)
}
/**
* Send a fresh keepalive and resolve true when any frame arrives before the
* timeout. Used on system resume to distinguish a link that survived sleep
@@ -297,6 +344,9 @@ export class SshChannelMultiplexer {
this.pendingRequests.delete(id)
}
const writerError = new Error(errorMessage) as Error & { code: string }
writerError.code = errorCode
this.writer.dispose(writerError)
this.unackedTimestamps.clear()
// Why: relay teardown can race with late provider registration; disposed
// muxes must not retain provider/session closures through subscribers.
@@ -321,34 +371,27 @@ export class SshChannelMultiplexer {
// ── Private ───────────────────────────────────────────────────────
private sendMessage(msg: JsonRpcMessage): void {
private sendMessage(
msg: JsonRpcMessage,
onSettled?: (result: MultiplexerWriteSettlement) => void
): void {
const seq = this.nextOutgoingSeq++
const frame = encodeJsonRpcFrame(msg, seq, this.highestReceivedSeq)
this.unackedTimestamps.set(seq, Date.now())
try {
this.transport.write(frame)
} catch (err) {
// Why: a remote reboot can make the SSH channel's stdin throw EPIPE
// from a timer/request path. Scope it to this mux instead of letting
// the Electron main process treat it as an uncaught exception.
this.handleProtocolError(err)
}
this.trackOutgoingTimestamp(seq, false)
this.writer.enqueue(frame, messageLane(msg), onSettled)
}
private sendKeepAlive(): void {
if (this.disposed) {
return
}
const seq = this.nextOutgoingSeq++
const seq = this.nextOutgoingSeq
const frame = encodeKeepAliveFrame(seq, this.highestReceivedSeq)
this.unackedTimestamps.set(seq, Date.now())
try {
this.transport.write(frame)
} catch (err) {
// Why: keepalive runs on an interval; without catching transport
// write failures here, a dead SSH host can terminate the whole app.
this.handleProtocolError(err)
if (!this.writer.enqueue(frame, 'liveness')) {
return
}
this.nextOutgoingSeq++
this.trackOutgoingTimestamp(seq, true)
}
private handleFrame(frame: DecodedFrame): void {
@@ -363,12 +406,16 @@ export class SshChannelMultiplexer {
this.highestReceivedSeq = frame.id
}
// Process ack from remote: discard timestamps for acked messages
if (frame.ack > this.highestAckedBySelf) {
for (let i = this.highestAckedBySelf + 1; i <= frame.ack; i++) {
this.unackedTimestamps.delete(i)
// Header ACKs are untrusted uint32 values; work stays proportional to the
// bounded set of sequence keys we actually retained.
const acknowledgedSeq = Math.min(frame.ack, this.nextOutgoingSeq - 1)
if (acknowledgedSeq > this.highestAckedBySelf) {
for (const seq of this.unackedTimestamps.keys()) {
if (seq <= acknowledgedSeq) {
this.unackedTimestamps.delete(seq)
}
}
this.highestAckedBySelf = frame.ack
this.highestAckedBySelf = acknowledgedSeq
}
if (frame.type === MessageType.KeepAlive) {
@@ -440,7 +487,12 @@ export class SshChannelMultiplexer {
Object.defineProperty(err, 'data', { value: msg.error.data })
pending.reject(err)
} else {
pending.resolve(msg.result)
try {
pending.beforeResolve?.(msg.result)
pending.resolve(msg.result)
} catch (error) {
pending.reject(error instanceof Error ? error : new Error(String(error)))
}
}
}
@@ -495,15 +547,12 @@ export class SshChannelMultiplexer {
// before this tick's fresh probe, then allow the next full window.
const resumedAfterWake = sinceLastTick > WAKE_GAP_MS
if (resumedAfterWake) {
this.lastReceivedAt = now
for (const seq of this.unackedTimestamps.keys()) {
this.unackedTimestamps.set(seq, now)
}
this.rebaseHealthClocks(now)
}
this.sendKeepAlive()
if (this.disposed || resumedAfterWake) {
if (this.disposed || resumedAfterWake || this.decoderReadPaused || this.writerSaturated) {
return
}
@@ -529,4 +578,57 @@ export class SshChannelMultiplexer {
console.warn(`[ssh-mux] Protocol error: ${err instanceof Error ? err.message : String(err)}`)
this.dispose('connection_lost')
}
private trackOutgoingTimestamp(seq: number, liveness: boolean): void {
const limit = liveness ? MAX_UNACKED_TIMESTAMPS : MAX_ORDINARY_UNACKED_TIMESTAMPS
if (this.unackedTimestamps.size < limit) {
this.unackedTimestamps.set(seq, Date.now())
}
}
private pauseDecoderReads(): void {
if (this.disposed || this.decoderReadPaused) {
return
}
this.decoderReadPaused = true
try {
this.transport.pauseReads?.()
} catch (error) {
this.handleProtocolError(error)
}
}
private resumeDecoderReads(): void {
if (!this.decoderReadPaused) {
return
}
this.decoderReadPaused = false
if (this.disposed) {
return
}
this.rebaseHealthClocks(Date.now())
try {
this.transport.resumeReads?.()
} catch (error) {
this.handleProtocolError(error)
}
}
private handleWriterSaturationChange(saturated: boolean): void {
this.writerSaturated = saturated
if (!saturated && !this.disposed) {
this.rebaseHealthClocks(Date.now())
}
}
private rebaseHealthClocks(now: number): void {
this.lastReceivedAt = now
for (const seq of this.unackedTimestamps.keys()) {
this.unackedTimestamps.set(seq, now)
}
}
}
function messageLane(msg: JsonRpcMessage): MultiplexerWriterLane {
return 'method' in msg && msg.method === 'pty.data' ? 'ordinary' : 'control'
}
@@ -0,0 +1,284 @@
import { EventEmitter } from 'node:events'
import { describe, expect, it, vi } from 'vitest'
import {
MULTIPLEXER_CONTROL_RESERVE_BYTES,
MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES,
SshMultiplexerTransportWriter,
type MultiplexerTransport,
type MultiplexerWriteSettlement
} from './ssh-multiplexer-transport-writer'
type WriterHarness = {
transport: MultiplexerTransport
drain: () => void
writes: Buffer[]
callbacks: ((result: MultiplexerWriteSettlement) => void)[]
removeDrain: ReturnType<typeof vi.fn>
}
function transportHarness(writeResults: (boolean | void)[]): WriterHarness {
const emitter = new EventEmitter()
const writes: Buffer[] = []
const callbacks: ((result: MultiplexerWriteSettlement) => void)[] = []
const removeDrain = vi.fn()
return {
transport: {
write: (data, onSettled) => {
writes.push(data)
callbacks.push(onSettled!)
return writeResults.shift()
},
supportsWriteSettlement: true,
onDrain: (callback) => {
emitter.on('drain', callback)
return () => {
removeDrain()
emitter.off('drain', callback)
}
},
onData: vi.fn(),
onClose: vi.fn()
},
drain: () => emitter.emit('drain'),
writes,
callbacks,
removeDrain
}
}
describe('SshMultiplexerTransportWriter', () => {
it('selects queued control before ordinary backlog at the drain boundary', () => {
const harness = transportHarness([false, true, true, true])
const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn())
writer.enqueue(Buffer.from('ordinary-1'), 'ordinary')
writer.enqueue(Buffer.from('ordinary-2'), 'ordinary')
writer.enqueue(Buffer.from('ordinary-3'), 'ordinary')
writer.enqueue(Buffer.from('control'), 'control')
expect(harness.writes.map(String)).toEqual(['ordinary-1'])
harness.drain()
expect(harness.writes.map(String)).toEqual([
'ordinary-1',
'control',
'ordinary-2',
'ordinary-3'
])
writer.dispose()
})
it('preserves FIFO within each lane and prevents ordinary starvation', () => {
const harness = transportHarness([false, ...Array<boolean>(8).fill(true)])
const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn())
writer.enqueue(Buffer.from('ordinary-1'), 'ordinary')
writer.enqueue(Buffer.from('ordinary-2'), 'ordinary')
for (let index = 1; index <= 6; index++) {
writer.enqueue(Buffer.from(`control-${index}`), 'control')
}
harness.drain()
expect(harness.writes.map(String)).toEqual([
'ordinary-1',
'control-1',
'control-2',
'control-3',
'control-4',
'ordinary-2',
'control-5',
'control-6'
])
writer.dispose()
})
it('waits for drain and settles each write once', () => {
const harness = transportHarness([false, true, true])
const failed = vi.fn()
const writer = new SshMultiplexerTransportWriter(harness.transport, failed)
const settlements = [vi.fn(), vi.fn(), vi.fn()]
writer.enqueue(Buffer.from('ordinary-1'), 'ordinary', settlements[0])
writer.enqueue(Buffer.from('control'), 'control', settlements[1])
writer.enqueue(Buffer.from('ordinary-2'), 'ordinary', settlements[2])
expect(harness.writes.map(String)).toEqual(['ordinary-1'])
harness.callbacks[0]({ ok: true })
expect(settlements[0]).toHaveBeenCalledWith({ ok: true })
expect(harness.writes.map(String)).toEqual(['ordinary-1'])
harness.drain()
expect(harness.writes.map(String)).toEqual(['ordinary-1', 'control', 'ordinary-2'])
harness.callbacks[1]({ ok: true })
harness.callbacks[2]({ ok: true })
expect(settlements.every((settle) => settle.mock.calls.length === 1)).toBe(true)
expect(failed).not.toHaveBeenCalled()
})
it('allows one coalesced liveness bypass per saturated write settlement', () => {
const harness = transportHarness([false, true, true, true])
const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn())
writer.enqueue(Buffer.from('ordinary-1'), 'ordinary')
writer.enqueue(Buffer.from('ordinary-2'), 'ordinary')
expect(writer.enqueue(Buffer.from('liveness-1'), 'liveness')).toBe(true)
expect(writer.enqueue(Buffer.from('liveness-coalesced'), 'liveness')).toBe(false)
expect(harness.writes.map(String)).toEqual(['ordinary-1', 'liveness-1'])
harness.callbacks[1]({ ok: true })
expect(writer.enqueue(Buffer.from('liveness-2'), 'liveness')).toBe(true)
expect(harness.writes.map(String)).toEqual(['ordinary-1', 'liveness-1', 'liveness-2'])
harness.drain()
expect(harness.writes.map(String)).toEqual([
'ordinary-1',
'liveness-1',
'liveness-2',
'ordinary-2'
])
writer.dispose()
})
it('reports saturated epochs and their drain boundary exactly once', () => {
const harness = transportHarness([false])
const saturation = vi.fn()
const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn(), saturation)
writer.enqueue(Buffer.from('ordinary'), 'ordinary')
writer.enqueue(Buffer.from('queued'), 'ordinary')
expect(saturation.mock.calls).toEqual([[true]])
harness.drain()
expect(saturation.mock.calls).toEqual([[true], [false]])
writer.dispose()
})
it('keeps a full ordinary lane from consuming the control reserve', () => {
const harness = transportHarness([false, true, true])
const writer = new SshMultiplexerTransportWriter(harness.transport, vi.fn())
expect(writer.enqueue(Buffer.alloc(1), 'ordinary')).toBe(true)
expect(writer.enqueue(Buffer.alloc(MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES - 1), 'ordinary')).toBe(
true
)
expect(writer.enqueue(Buffer.alloc(MULTIPLEXER_CONTROL_RESERVE_BYTES), 'control')).toBe(true)
expect(harness.writes).toHaveLength(1)
harness.drain()
expect(harness.writes).toHaveLength(3)
writer.dispose()
})
it('fails all retained writes once when a callback reports an error', () => {
const harness = transportHarness([false])
const failed = vi.fn()
const writer = new SshMultiplexerTransportWriter(harness.transport, failed)
const first = vi.fn()
const queued = vi.fn()
const error = new Error('broken pipe')
writer.enqueue(Buffer.from('first'), 'ordinary', first)
writer.enqueue(Buffer.from('queued'), 'control', queued)
harness.callbacks[0]({ ok: false, error })
harness.callbacks[0]({ ok: true })
expect(first).toHaveBeenCalledOnce()
expect(first).toHaveBeenCalledWith({ ok: false, error })
expect(queued).toHaveBeenCalledWith({ ok: false, error })
expect(failed).toHaveBeenCalledWith(error)
expect(harness.removeDrain).toHaveBeenCalledOnce()
})
it('closes on queue overflow and rejects the overflowing write', () => {
const harness = transportHarness([false])
const failed = vi.fn()
const writer = new SshMultiplexerTransportWriter(harness.transport, failed)
const retained = vi.fn()
const overflow = vi.fn()
writer.enqueue(Buffer.alloc(MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES), 'ordinary', retained)
expect(writer.enqueue(Buffer.alloc(1), 'ordinary', overflow)).toBe(false)
expect(overflow).toHaveBeenCalledWith({
ok: false,
error: expect.objectContaining({ message: expect.stringContaining('bounded capacity') })
})
expect(retained).toHaveBeenCalledWith({
ok: false,
error: expect.objectContaining({ message: expect.stringContaining('bounded capacity') })
})
expect(failed).toHaveBeenCalledOnce()
})
it('settles legacy callback-less transports on acceptance and drain', () => {
const emitter = new EventEmitter()
const write = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(undefined)
const transport: MultiplexerTransport = {
write,
onDrain: (callback) => {
emitter.on('drain', callback)
},
onData: vi.fn(),
onClose: vi.fn()
}
const writer = new SshMultiplexerTransportWriter(transport, vi.fn())
const first = vi.fn()
const second = vi.fn()
writer.enqueue(Buffer.from('first'), 'ordinary', first)
writer.enqueue(Buffer.from('second'), 'control', second)
expect(first).not.toHaveBeenCalled()
expect(second).not.toHaveBeenCalled()
emitter.emit('drain')
expect(first).toHaveBeenCalledWith({ ok: true })
expect(second).toHaveBeenCalledWith({ ok: true })
})
it('does not miss a drain emitted synchronously by a hostile transport', () => {
let drain = (): void => {}
const write = vi.fn(() => {
drain()
return false
})
const writer = new SshMultiplexerTransportWriter(
{
write,
onDrain: (callback) => {
drain = callback
},
onData: vi.fn(),
onClose: vi.fn()
},
vi.fn()
)
const first = vi.fn()
const second = vi.fn()
writer.enqueue(Buffer.from('first'), 'ordinary', first)
writer.enqueue(Buffer.from('second'), 'control', second)
expect(write).toHaveBeenCalledTimes(2)
expect(first).toHaveBeenCalledWith({ ok: true })
expect(second).toHaveBeenCalledWith({ ok: true })
})
it('fails deterministically when write(false) has no drain source', () => {
const failed = vi.fn()
const writer = new SshMultiplexerTransportWriter(
{
write: () => false,
onData: vi.fn(),
onClose: vi.fn()
},
failed
)
const settled = vi.fn()
expect(writer.enqueue(Buffer.from('data'), 'ordinary', settled)).toBe(true)
expect(settled).toHaveBeenCalledWith({
ok: false,
error: expect.objectContaining({ message: expect.stringContaining('without drain support') })
})
expect(failed).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,270 @@
import { HEADER_LENGTH, MAX_MESSAGE_SIZE } from './relay-protocol'
import { SshMultiplexerWriterLaneScheduler } from './ssh-multiplexer-writer-lane-scheduler'
export type MultiplexerWriteSettlement = { ok: true } | { ok: false; error: Error }
export type MultiplexerTransport = {
write: (data: Buffer, onSettled?: (result: MultiplexerWriteSettlement) => void) => boolean | void
onData: (cb: (data: Buffer) => void) => void
onClose: (cb: () => void) => void
onDrain?: (cb: () => void) => void | (() => void)
supportsWriteSettlement?: boolean
pauseReads?: () => void
resumeReads?: () => void
close?: () => void
}
export type MultiplexerWriterLane = 'ordinary' | 'control' | 'liveness'
type WriterEntry = {
data: Buffer
lane: MultiplexerWriterLane
onSettled: (result: MultiplexerWriteSettlement) => void
settled: boolean
}
export const MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES = 2 * 1024 * 1024
export const MULTIPLEXER_CONTROL_RESERVE_BYTES = MAX_MESSAGE_SIZE + HEADER_LENGTH
const ORDINARY_QUEUE_MAX_FRAMES = 2048
const CONTROL_QUEUE_MAX_FRAMES = 512
function onceSettlement(
callback: (result: MultiplexerWriteSettlement) => void
): (result: MultiplexerWriteSettlement) => void {
let settled = false
return (result) => {
if (settled) {
return
}
settled = true
callback(result)
}
}
export class SshMultiplexerTransportWriter {
private readonly scheduler = new SshMultiplexerWriterLaneScheduler<WriterEntry>()
private readonly inFlight = new Set<WriterEntry>()
private readonly settleOnDrain = new Set<WriterEntry>()
private ordinaryBytes = 0
private controlBytes = 0
private ordinaryFrames = 0
private controlFrames = 0
private saturated = false
private writing = false
private drainObservedDuringWrite = false
private pumping = false
private closed = false
private livenessOutstanding = false
private removeDrainListener: (() => void) | null = null
constructor(
private readonly transport: MultiplexerTransport,
private readonly onFailure: (error: Error) => void,
private readonly onSaturationChange: (saturated: boolean) => void = () => {}
) {
if (transport.onDrain) {
const remove = transport.onDrain(() => this.handleDrain())
this.removeDrainListener = typeof remove === 'function' ? remove : null
}
}
enqueue(
data: Buffer,
lane: MultiplexerWriterLane,
onSettled: (result: MultiplexerWriteSettlement) => void = () => {}
): boolean {
const settle = onceSettlement(onSettled)
if (this.closed) {
settle({ ok: false, error: new Error('Multiplexer writer is closed') })
return false
}
if (lane === 'liveness' && this.livenessOutstanding) {
return false
}
const admissionError = this.admissionError(data.length, lane)
if (admissionError) {
settle({ ok: false, error: admissionError })
this.fail(admissionError)
return false
}
const entry = { data, lane, onSettled: settle, settled: false }
this.retain(entry)
if (lane === 'liveness' && this.saturated) {
this.writeEntry(entry)
} else {
this.scheduler.enqueue(entry, lane)
this.pump()
}
return true
}
dispose(error = new Error('Multiplexer writer disposed')): void {
if (this.closed) {
return
}
this.closed = true
this.saturated = false
this.removeDrainListener?.()
this.removeDrainListener = null
for (const entry of this.scheduler.clear()) {
this.release(entry, { ok: false, error })
}
for (const entry of Array.from(this.inFlight)) {
this.release(entry, { ok: false, error })
}
this.settleOnDrain.clear()
}
private admissionError(bytes: number, lane: MultiplexerWriterLane): Error | null {
const byteLimit =
lane === 'ordinary' ? MULTIPLEXER_ORDINARY_QUEUE_MAX_BYTES : MULTIPLEXER_CONTROL_RESERVE_BYTES
const retainedBytes = lane === 'ordinary' ? this.ordinaryBytes : this.controlBytes
const frameLimit = lane === 'ordinary' ? ORDINARY_QUEUE_MAX_FRAMES : CONTROL_QUEUE_MAX_FRAMES
const retainedFrames = lane === 'ordinary' ? this.ordinaryFrames : this.controlFrames
if (retainedBytes + bytes <= byteLimit && retainedFrames < frameLimit) {
return null
}
return new Error(`Multiplexer ${lane} write queue exceeded its bounded capacity`)
}
private pump(): void {
if (this.pumping || this.closed || this.saturated) {
return
}
this.pumping = true
try {
while (!this.closed && !this.saturated) {
const entry = this.scheduler.select()
if (!entry) {
return
}
this.writeEntry(entry)
}
} finally {
this.pumping = false
}
}
private writeEntry(entry: WriterEntry): void {
this.inFlight.add(entry)
let callbackResult: MultiplexerWriteSettlement | undefined
let writeReturned = false
const onWriteSettled = (result: MultiplexerWriteSettlement): void => {
if (!writeReturned) {
callbackResult = result
return
}
this.handleWriteSettlement(entry, result)
}
try {
this.writing = true
this.drainObservedDuringWrite = false
const accepted = this.transport.write(entry.data, onWriteSettled)
this.writing = false
writeReturned = true
if (accepted === false) {
if (!this.transport.onDrain) {
throw new Error('Multiplexer transport returned write(false) without drain support')
}
this.setSaturated(!this.drainObservedDuringWrite)
if (this.transport.supportsWriteSettlement !== true && this.saturated) {
this.settleOnDrain.add(entry)
} else if (this.transport.supportsWriteSettlement !== true) {
this.handleWriteSettlement(entry, { ok: true })
}
} else if (this.transport.supportsWriteSettlement !== true) {
this.handleWriteSettlement(entry, { ok: true })
}
if (callbackResult) {
this.handleWriteSettlement(entry, callbackResult)
}
} catch (error) {
this.writing = false
writeReturned = true
if (callbackResult) {
this.handleWriteSettlement(entry, callbackResult)
}
this.fail(error instanceof Error ? error : new Error(String(error)))
}
}
private handleWriteSettlement(entry: WriterEntry, result: MultiplexerWriteSettlement): void {
if (entry.settled) {
return
}
this.release(entry, result)
if (!result.ok) {
this.fail(result.error)
return
}
this.pump()
}
private handleDrain(): void {
if (this.closed) {
return
}
if (this.writing) {
this.drainObservedDuringWrite = true
return
}
if (!this.saturated) {
return
}
this.setSaturated(false)
for (const entry of Array.from(this.settleOnDrain)) {
this.release(entry, { ok: true })
}
this.settleOnDrain.clear()
this.pump()
}
private retain(entry: WriterEntry): void {
if (entry.lane === 'ordinary') {
this.ordinaryBytes += entry.data.length
this.ordinaryFrames++
} else {
this.controlBytes += entry.data.length
this.controlFrames++
}
if (entry.lane === 'liveness') {
this.livenessOutstanding = true
}
}
private release(entry: WriterEntry, result: MultiplexerWriteSettlement): void {
if (entry.settled) {
return
}
entry.settled = true
this.inFlight.delete(entry)
this.settleOnDrain.delete(entry)
if (entry.lane === 'ordinary') {
this.ordinaryBytes -= entry.data.length
this.ordinaryFrames--
} else {
this.controlBytes -= entry.data.length
this.controlFrames--
}
if (entry.lane === 'liveness') {
this.livenessOutstanding = false
}
entry.onSettled(result)
}
private setSaturated(saturated: boolean): void {
if (this.saturated === saturated) {
return
}
this.saturated = saturated
this.onSaturationChange(saturated)
}
private fail(error: Error): void {
if (this.closed) {
return
}
this.dispose(error)
this.onFailure(error)
}
}
@@ -0,0 +1,73 @@
import type { MultiplexerWriterLane } from './ssh-multiplexer-transport-writer'
const CONTROL_WRITES_BEFORE_ORDINARY = 4
type LaneQueue<T> = {
entries: T[]
head: number
}
function createLaneQueue<T>(): LaneQueue<T> {
return { entries: [], head: 0 }
}
function hasEntries<T>(queue: LaneQueue<T>): boolean {
return queue.head < queue.entries.length
}
function shift<T>(queue: LaneQueue<T>): T | undefined {
const entry = queue.entries[queue.head]
if (entry === undefined) {
return undefined
}
queue.head += 1
if (queue.head === queue.entries.length) {
queue.entries.length = 0
queue.head = 0
}
return entry
}
function clear<T>(queue: LaneQueue<T>): T[] {
const entries = queue.entries.slice(queue.head)
queue.entries.length = 0
queue.head = 0
return entries
}
export class SshMultiplexerWriterLaneScheduler<T extends object> {
private readonly ordinary = createLaneQueue<T>()
private readonly control = createLaneQueue<T>()
private readonly liveness = createLaneQueue<T>()
private controlWritesSinceOrdinary = 0
enqueue(entry: T, lane: MultiplexerWriterLane): void {
this[lane].entries.push(entry)
}
select(): T | undefined {
const liveness = shift(this.liveness)
if (liveness) {
return liveness
}
if (
hasEntries(this.control) &&
(!hasEntries(this.ordinary) ||
this.controlWritesSinceOrdinary < CONTROL_WRITES_BEFORE_ORDINARY)
) {
this.controlWritesSinceOrdinary += 1
return shift(this.control)
}
const ordinary = shift(this.ordinary)
if (ordinary) {
this.controlWritesSinceOrdinary = 0
return ordinary
}
return shift(this.control)
}
clear(): T[] {
this.controlWritesSinceOrdinary = 0
return [...clear(this.liveness), ...clear(this.control), ...clear(this.ordinary)]
}
}
@@ -0,0 +1,140 @@
import { describe, expect, it, vi } from 'vitest'
import type { SshChannelMultiplexer } from './ssh-channel-multiplexer'
import { openSshPtyConsumerSession } from './ssh-pty-consumer-session'
function muxReturning(result: unknown): {
mux: SshChannelMultiplexer
request: ReturnType<typeof vi.fn>
} {
const request = vi.fn().mockResolvedValue(result)
return { mux: { request } as unknown as SshChannelMultiplexer, request }
}
function legacyOwnerGrant(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
protocolVersion: 1,
serverBuildId: 'build-a',
clientGeneration: 3,
role: 'session-owner',
ownerGeneration: 7,
ownerLease: 'lease-a',
...overrides
}
}
describe('openSshPtyConsumerSession', () => {
it('makes openClient the one request needed for token-free legacy readiness', async () => {
const { mux, request } = muxReturning(legacyOwnerGrant())
await expect(
openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a'
})
).resolves.toEqual({
mode: 'negotiated',
clientInstanceId: 'client-a',
clientGeneration: 3,
ownerGeneration: 7,
ownerLease: 'lease-a'
})
expect(request).toHaveBeenCalledWith(
'pty.openClient',
{
protocolVersion: 1,
clientInstanceId: 'client-a',
requestedRole: 'session-owner'
},
{ timeoutMs: 10_000 }
)
})
it('carries recovery generation and lease on reconnect', async () => {
const { mux, request } = muxReturning(
legacyOwnerGrant({ ownerGeneration: 8, ownerLease: 'lease-b' })
)
await openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a',
resume: { ownerGeneration: 7, ownerLease: 'lease-a' }
})
expect(request.mock.calls[0][1]).toMatchObject({
resume: { ownerGeneration: 7, ownerLease: 'lease-a' }
})
})
it('rejects a prior or mismatched relay build', async () => {
const { mux } = muxReturning(legacyOwnerGrant({ serverBuildId: 'old-build' }))
await expect(
openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a'
})
).rejects.toThrow('session contract mismatch')
})
it('does not silently downgrade when V1 was offered', async () => {
const { mux } = muxReturning(legacyOwnerGrant())
await expect(
openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a',
outputFlowControl: { requestedWindowSu: 64 }
})
).rejects.toThrow('did not grant')
})
it('rejects an unoffered V1 capability in a legacy session', async () => {
const { mux } = muxReturning(
legacyOwnerGrant({
capabilities: { outputFlowControl: { version: 1, windowSu: 64 } }
})
)
await expect(
openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a'
})
).rejects.toThrow('unoffered')
})
it('uses explicit token-free fallback only for same-build method-not-found', async () => {
const error = Object.assign(new Error('Method not found: pty.openClient'), { code: -32601 })
const request = vi.fn().mockRejectedValue(error)
const mux = { request } as unknown as SshChannelMultiplexer
await expect(
openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a',
allowSameBuildLegacyFallback: true,
outputFlowControl: { requestedWindowSu: 64 }
})
).resolves.toEqual({
mode: 'legacy-fallback',
clientInstanceId: 'client-a',
serverBuildId: 'build-a'
})
})
it.each([
Object.assign(new Error('timeout'), { code: 'TIMEOUT' }),
Object.assign(new Error('auth failed'), { code: -32000 }),
Object.assign(new Error('method missing'), { code: -32601 })
])('does not downgrade an unproved or non-method-not-found error', async (error) => {
const request = vi.fn().mockRejectedValue(error)
const mux = { request } as unknown as SshChannelMultiplexer
await expect(
openSshPtyConsumerSession(mux, {
clientInstanceId: 'client-a',
expectedServerBuildId: 'build-a',
allowSameBuildLegacyFallback: error.code !== -32601
})
).rejects.toBe(error)
})
})
+143
View File
@@ -0,0 +1,143 @@
import {
PTY_CONSUMER_SESSION_PROTOCOL_VERSION,
type PtyConsumerSessionGrant
} from '../../shared/pty-consumer-session'
import { DEFAULT_PTY_SOURCE_WINDOW_SU } from '../../shared/pty-source-credit-contract'
import type { SshChannelMultiplexer } from './ssh-channel-multiplexer'
export const SSH_PTY_OPEN_CLIENT_METHOD = 'pty.openClient'
export const SSH_PTY_OPEN_CLIENT_TIMEOUT_MS = 10_000
export type SshPtyConsumerOwnerState = {
mode: 'negotiated'
clientInstanceId: string
clientGeneration: number
ownerGeneration: number
ownerLease: string
outputFlowControl?: {
version: 1
windowSu: number
}
}
export type SshPtyLegacyFallbackState = {
mode: 'legacy-fallback'
clientInstanceId: string
serverBuildId: string
}
export type SshPtyConsumerSessionState = SshPtyConsumerOwnerState | SshPtyLegacyFallbackState
export type OpenSshPtyConsumerSessionOptions = {
clientInstanceId: string
expectedServerBuildId: string | undefined
resume?: Pick<SshPtyConsumerOwnerState, 'ownerGeneration' | 'ownerLease'>
outputFlowControl?: {
requestedWindowSu: number
}
allowSameBuildLegacyFallback?: boolean
}
function validateGrant(
value: unknown,
options: OpenSshPtyConsumerSessionOptions
): PtyConsumerSessionGrant {
if (typeof value !== 'object' || value === null) {
throw new Error('Remote relay returned an invalid pty.openClient grant')
}
if (!options.expectedServerBuildId) {
throw new Error('Local relay build identity is unavailable')
}
const grant = value as Partial<PtyConsumerSessionGrant>
if (
grant.protocolVersion !== PTY_CONSUMER_SESSION_PROTOCOL_VERSION ||
grant.serverBuildId !== options.expectedServerBuildId
) {
throw new Error(
`Remote relay session contract mismatch — expected build ${options.expectedServerBuildId}, got ${grant.serverBuildId ?? 'unknown'}`
)
}
if (
!Number.isSafeInteger(grant.clientGeneration) ||
grant.clientGeneration! <= 0 ||
grant.role !== 'session-owner' ||
!Number.isSafeInteger(grant.ownerGeneration) ||
grant.ownerGeneration! <= 0 ||
typeof grant.ownerLease !== 'string' ||
grant.ownerLease.length === 0
) {
throw new Error('Remote relay did not grant an authenticated PTY session owner')
}
const requestedFlow = options.outputFlowControl
const grantedFlow = grant.capabilities?.outputFlowControl
if (requestedFlow) {
if (
grantedFlow?.version !== 1 ||
!Number.isSafeInteger(grantedFlow.windowSu) ||
grantedFlow.windowSu <= 0 ||
grantedFlow.windowSu > requestedFlow.requestedWindowSu
) {
throw new Error('Remote relay did not grant the offered PTY output-flow-control capability')
}
} else if (grantedFlow) {
throw new Error('Remote relay granted an unoffered PTY output-flow-control capability')
}
return grant as PtyConsumerSessionGrant
}
export async function openSshPtyConsumerSession(
mux: SshChannelMultiplexer,
options: OpenSshPtyConsumerSessionOptions
): Promise<SshPtyConsumerSessionState> {
let result: unknown
try {
result = await mux.request(
SSH_PTY_OPEN_CLIENT_METHOD,
{
protocolVersion: PTY_CONSUMER_SESSION_PROTOCOL_VERSION,
clientInstanceId: options.clientInstanceId,
requestedRole: 'session-owner',
...(options.resume ? { resume: options.resume } : {}),
...(options.outputFlowControl
? {
capabilities: {
outputFlowControl: {
versions: [1],
requestedWindowSu: options.outputFlowControl.requestedWindowSu
}
}
}
: {})
},
{ timeoutMs: SSH_PTY_OPEN_CLIENT_TIMEOUT_MS }
)
} catch (error) {
const code = (error as { code?: unknown })?.code
if (
code === -32601 &&
options.allowSameBuildLegacyFallback === true &&
typeof options.expectedServerBuildId === 'string' &&
options.expectedServerBuildId.length > 0
) {
return Object.freeze({
mode: 'legacy-fallback',
clientInstanceId: options.clientInstanceId,
serverBuildId: options.expectedServerBuildId
})
}
throw error
}
const grant = validateGrant(result, options)
return {
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: grant.clientGeneration,
ownerGeneration: grant.ownerGeneration!,
ownerLease: grant.ownerLease!,
...(grant.capabilities?.outputFlowControl
? { outputFlowControl: grant.capabilities.outputFlowControl }
: {})
}
}
export const SSH_PTY_SOURCE_WINDOW_SU = DEFAULT_PTY_SOURCE_WINDOW_SU
@@ -0,0 +1,43 @@
import { describe, expect, it } from 'vitest'
import { SshPtyRecoveryRetentionBudget } from './ssh-pty-recovery-retention-budget'
describe('SshPtyRecoveryRetentionBudget', () => {
it('bounds fragmented recovery by per-PTY and session source, charged bytes, and frames', () => {
const budget = new SshPtyRecoveryRetentionBudget({
perPtySourceSu: 4,
perPtyBytes: 300,
perPtyFrames: 2,
sessionSourceSu: 6,
sessionBytes: 500,
sessionFrames: 3
})
expect(budget.tryRetain('pty-1', 'aa', 2)).toBe(true)
expect(budget.tryRetain('pty-1', 'bb', 2)).toBe(true)
expect(budget.tryRetain('pty-1', 'c', 0)).toBe(false)
expect(budget.tryRetain('pty-2', 'cc', 2)).toBe(true)
expect(budget.snapshot()).toEqual({ sourceSu: 6, bytes: 396, frames: 3, ptys: 2 })
expect(budget.tryRetain('pty-2', 'd', 1)).toBe(false)
budget.release('pty-1')
expect(budget.snapshot()).toEqual({ sourceSu: 2, bytes: 132, frames: 1, ptys: 1 })
expect(budget.tryRetain('pty-2', 'dd', 2)).toBe(true)
})
it('charges UTF-16 storage plus one record before aggregate admission', () => {
const budget = new SshPtyRecoveryRetentionBudget({
perPtySourceSu: 100,
perPtyBytes: 1_000,
perPtyFrames: 10,
sessionSourceSu: 100,
sessionBytes: 500,
sessionFrames: 10
})
expect(budget.tryRetain('pty-1', '\u0000'.repeat(64), 1)).toBe(true)
expect(budget.snapshot().bytes).toBe(256)
expect(budget.tryRetain('pty-2', '\u0000'.repeat(64), 1)).toBe(false)
expect(budget.snapshot()).toEqual({ sourceSu: 1, bytes: 256, frames: 1, ptys: 1 })
})
})
@@ -0,0 +1,95 @@
import { DEFAULT_PTY_SOURCE_WINDOW_SU } from '../../shared/pty-source-credit-contract'
import { chargedPtyRetainedStringBytes } from '../../shared/pty-retained-string-memory'
export const SSH_PTY_RECOVERY_PER_PTY_MAX_SOURCE_SU = DEFAULT_PTY_SOURCE_WINDOW_SU
export const SSH_PTY_RECOVERY_PER_PTY_MAX_BYTES = 2 * 1024 * 1024
export const SSH_PTY_RECOVERY_PER_PTY_MAX_FRAMES = 1_024
export const SSH_PTY_RECOVERY_SESSION_MAX_SOURCE_SU = 50 * DEFAULT_PTY_SOURCE_WINDOW_SU
export const SSH_PTY_RECOVERY_SESSION_MAX_BYTES = 64 * 1024 * 1024
export const SSH_PTY_RECOVERY_SESSION_MAX_FRAMES = 64 * 1_024
export type SshPtyRecoveryRetentionLimits = Readonly<{
perPtySourceSu: number
perPtyBytes: number
perPtyFrames: number
sessionSourceSu: number
sessionBytes: number
sessionFrames: number
}>
type RetainedPty = {
sourceSu: number
bytes: number
frames: number
}
const DEFAULT_LIMITS: SshPtyRecoveryRetentionLimits = Object.freeze({
perPtySourceSu: SSH_PTY_RECOVERY_PER_PTY_MAX_SOURCE_SU,
perPtyBytes: SSH_PTY_RECOVERY_PER_PTY_MAX_BYTES,
perPtyFrames: SSH_PTY_RECOVERY_PER_PTY_MAX_FRAMES,
sessionSourceSu: SSH_PTY_RECOVERY_SESSION_MAX_SOURCE_SU,
sessionBytes: SSH_PTY_RECOVERY_SESSION_MAX_BYTES,
sessionFrames: SSH_PTY_RECOVERY_SESSION_MAX_FRAMES
})
export class SshPtyRecoveryRetentionBudget {
private readonly retainedByPty = new Map<string, RetainedPty>()
private sourceSu = 0
private bytes = 0
private frames = 0
constructor(private readonly limits: SshPtyRecoveryRetentionLimits = DEFAULT_LIMITS) {}
tryRetain(ptyId: string, data: string, sourceSu: number): boolean {
if (!Number.isSafeInteger(sourceSu) || sourceSu < 0) {
return false
}
const retained = this.retainedByPty.get(ptyId) ?? { sourceSu: 0, bytes: 0, frames: 0 }
const chargedBytes = chargedPtyRetainedStringBytes(data)
if (
retained.sourceSu + sourceSu > this.limits.perPtySourceSu ||
retained.bytes + chargedBytes > this.limits.perPtyBytes ||
retained.frames + 1 > this.limits.perPtyFrames ||
this.sourceSu + sourceSu > this.limits.sessionSourceSu ||
this.bytes + chargedBytes > this.limits.sessionBytes ||
this.frames + 1 > this.limits.sessionFrames
) {
return false
}
retained.sourceSu += sourceSu
retained.bytes += chargedBytes
retained.frames++
this.retainedByPty.set(ptyId, retained)
this.sourceSu += sourceSu
this.bytes += chargedBytes
this.frames++
return true
}
release(ptyId: string): void {
const retained = this.retainedByPty.get(ptyId)
if (!retained) {
return
}
this.retainedByPty.delete(ptyId)
this.sourceSu -= retained.sourceSu
this.bytes -= retained.bytes
this.frames -= retained.frames
}
clear(): void {
this.retainedByPty.clear()
this.sourceSu = 0
this.bytes = 0
this.frames = 0
}
snapshot(): Readonly<{ sourceSu: number; bytes: number; frames: number; ptys: number }> {
return Object.freeze({
sourceSu: this.sourceSu,
bytes: this.bytes,
frames: this.frames,
ptys: this.retainedByPty.size
})
}
}
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest'
import { SshPtyRetiredSourceDeliveries } from './ssh-pty-retired-source-deliveries'
const source = (deliveryToken: string, relayPtyId = 'pty-1') => ({
relayPtyId,
deliveryToken,
clientGeneration: 2,
ownerGeneration: 3
})
describe('SshPtyRetiredSourceDeliveries', () => {
it('retains only the latest canceled token for each ordered PTY stream', () => {
const retired = new SshPtyRetiredSourceDeliveries()
for (let token = 0; token < 10_000; token++) {
retired.retire(1, source(`token-${token}`))
}
expect(retired.size).toBe(1)
expect(retired.has(1, source('token-9999'))).toBe(true)
expect(retired.has(1, source('token-9998'))).toBe(false)
})
it('retires state at the next activation or PTY exit boundary', () => {
const retired = new SshPtyRetiredSourceDeliveries()
retired.retire(1, source('old-token'))
retired.retire(1, source('other-token', 'pty-2'))
retired.activate('pty-1')
expect(retired.has(1, source('old-token'))).toBe(false)
expect(retired.has(1, source('other-token', 'pty-2'))).toBe(true)
expect(retired.size).toBe(1)
})
})
@@ -0,0 +1,36 @@
import type { SshPtySourceFrame } from '../providers/ssh-pty-source-frame'
type SourceDeliveryIdentity = Pick<
SshPtySourceFrame,
'relayPtyId' | 'deliveryToken' | 'clientGeneration' | 'ownerGeneration'
>
export class SshPtyRetiredSourceDeliveries {
private readonly keyByRelayPtyId = new Map<string, string>()
has(providerGeneration: number, source: SourceDeliveryIdentity): boolean {
return (
this.keyByRelayPtyId.get(source.relayPtyId) === sourceDeliveryKey(providerGeneration, source)
)
}
retire(providerGeneration: number, source: SourceDeliveryIdentity): void {
this.keyByRelayPtyId.set(source.relayPtyId, sourceDeliveryKey(providerGeneration, source))
}
activate(relayPtyId: string): void {
this.keyByRelayPtyId.delete(relayPtyId)
}
clear(): void {
this.keyByRelayPtyId.clear()
}
get size(): number {
return this.keyByRelayPtyId.size
}
}
function sourceDeliveryKey(providerGeneration: number, source: SourceDeliveryIdentity): string {
return `${providerGeneration}\0${source.clientGeneration}\0${source.ownerGeneration}\0${source.deliveryToken}`
}
@@ -104,7 +104,7 @@ describe('cross-version isolation', () => {
//
// We feed enough exec results to walk through the deploy: platform,
// $HOME, isRelayAlreadyInstalled probe, lock acquire, upload (no exec),
// npm install, finalize, socket probe, socket poll, then GC scan.
// npm install, finalize, socket probe, credential publication, socket poll, then GC scan.
const responses: string[] = [
'__ORCA_REMOTE_PLATFORM__ Linux x86_64', // tagged POSIX platform probe
'/home/u', // echo $HOME
@@ -122,6 +122,7 @@ describe('cross-version isolation', () => {
'', // rm -f probe-stderr (best-effort cleanup after probe resolved)
'', // touch .install-complete (finalizeInstall)
'DEAD', // launch socket probe
'', // publish the per-launch credential
'READY', // socket poll
'', // release .install-lock after relay liveness is observable
// GC scan begins here
+36 -3
View File
@@ -9,13 +9,17 @@ import {
RELAY_EXIT_CODE_VERSION_MISMATCH
} from './ssh-relay-version-mismatch-error'
function createMockChannel(): ClientChannel {
type MockChannel = ClientChannel & {
stdin: EventEmitter & { write: ReturnType<typeof vi.fn> }
}
function createMockChannel(): MockChannel {
return Object.assign(new EventEmitter(), {
stderr: Object.assign(new EventEmitter(), { resume: vi.fn() }),
stdin: { write: vi.fn() },
stdin: Object.assign(new EventEmitter(), { write: vi.fn(() => true) }),
close: vi.fn(),
resume: vi.fn()
}) as unknown as ClientChannel
}) as unknown as MockChannel
}
// execCommand only rejects with Error; narrow the caught reason (its resolve
@@ -204,6 +208,35 @@ describe('waitForSentinel', () => {
expect(Buffer.concat(chunks)).toEqual(postSentinelPayload)
expect(channel.close).not.toHaveBeenCalled()
})
it.each(['ssh2 channel', 'system-SSH child stdio'])(
'forwards write(false), callback settlement, and drain for a %s',
async (shape) => {
const channel = createMockChannel()
if (shape.startsWith('system')) {
Object.assign(channel, { _process: new EventEmitter() })
}
const callback = vi.fn()
const drain = vi.fn()
channel.stdin.write.mockImplementation((...args: unknown[]) => {
const onWritten = args.find((arg) => typeof arg === 'function') as (
error?: Error | null
) => void
onWritten(null)
return false
})
const transportPromise = waitForSentinel(channel)
channel.emit('data', Buffer.from(RELAY_SENTINEL))
const transport = await transportPromise
transport.onDrain?.(drain)
expect(transport.write(Buffer.from('frame'), callback)).toBe(false)
expect(callback).toHaveBeenCalledWith({ ok: true })
channel.stdin.emit('drain')
expect(drain).toHaveBeenCalledOnce()
expect(transport.supportsWriteSettlement).toBe(true)
}
)
})
describe('execCommand', () => {
+12 -1
View File
@@ -214,7 +214,16 @@ export function waitForSentinel(
pendingAfterSentinel = afterSentinel
}
const transport: MultiplexerTransport = {
write: (buf: Buffer) => channel.stdin.write(buf),
write: (buf: Buffer, onSettled) => {
return channel.stdin.write(buf, (error?: Error | null) => {
onSettled?.(error ? { ok: false, error } : { ok: true })
})
},
supportsWriteSettlement: true,
onDrain: (cb) => {
channel.stdin.on('drain', cb)
return () => channel.stdin.off('drain', cb)
},
onData: (cb) => {
dataCallbacks.push(cb)
// Why: deliver buffered post-sentinel data to the first
@@ -233,6 +242,8 @@ export function waitForSentinel(
cb()
}
},
pauseReads: () => channel.pause(),
resumeReads: () => channel.resume(),
close: () => {
channel.close()
}
+38 -21
View File
@@ -52,6 +52,10 @@ vi.mock('./ssh-remote-node-resolution', () => ({
resolveRemoteNodePath: vi.fn().mockResolvedValue('/usr/bin/node')
}))
vi.mock('./ssh-relay-endpoint-credential', () => ({
writeRelayEndpointCredential: vi.fn().mockResolvedValue(undefined)
}))
// Why: the versioned-install modules shell out for install state, locking,
// and GC. Stub them so deploy tests need no real SSH connection.
vi.mock('./ssh-relay-versioned-install', () => ({
@@ -97,13 +101,11 @@ function decodePowerShellCommand(command: string): string | null {
return match ? Buffer.from(match[1], 'base64').toString('utf16le') : null
}
function extractWindowsSockPath(script: string): string {
return /--sock-path\s+'([^']+)'/.exec(script)?.[1] ?? ''
}
const extractWindowsSockPath = (script: string): string =>
/--sock-path\s+'([^']+)'/.exec(script)?.[1] ?? ''
function extractWindowsMarkerPath(script: string): string {
return /-LiteralPath\s+'([^']*\.windows-active-pipe[^']*)'/.exec(script)?.[1] ?? ''
}
const extractWindowsMarkerPath = (script: string): string =>
/-LiteralPath\s+'([^']*\.windows-active-pipe[^']*)'/.exec(script)?.[1] ?? ''
function makeMockConnection(): SshConnection {
return {
@@ -115,6 +117,7 @@ function makeMockConnection(): SshConnection {
stdout: { on: vi.fn() },
close: vi.fn()
}),
writeFile: vi.fn().mockResolvedValue(undefined),
sftp: vi.fn().mockResolvedValue({
mkdir: vi.fn((_p: string, cb: (err: Error | null) => void) => cb(null)),
createWriteStream: vi.fn().mockReturnValue({
@@ -130,6 +133,10 @@ function makeMockConnection(): SshConnection {
} as unknown as SshConnection
}
function queueLaunchNamespaceAndDeadSocketProbe(): void {
vi.mocked(execCommand).mockResolvedValueOnce('').mockResolvedValueOnce('DEAD')
}
describe('deployAndLaunchRelay', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -141,7 +148,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64') // tagged POSIX platform probe
mockExecCommand.mockResolvedValueOnce('/home/user') // echo $HOME
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
await deployAndLaunchRelay(conn)
@@ -159,7 +166,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
mockExecCommand.mockResolvedValueOnce('/home/user')
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
const progress: string[] = []
@@ -179,6 +186,7 @@ describe('deployAndLaunchRelay', () => {
.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
.mockResolvedValueOnce('/home/user')
.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK')
.mockResolvedValueOnce('') // launch namespace marker
.mockResolvedValueOnce('ALIVE')
.mockRejectedValueOnce(unconfirmedCleanup)
@@ -195,7 +203,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
mockExecCommand.mockResolvedValueOnce('/home/user')
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK')
mockExecCommand.mockResolvedValueOnce('DEAD')
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY')
await deployAndLaunchRelay(conn)
@@ -240,7 +248,7 @@ describe('deployAndLaunchRelay', () => {
// Drain the rest of the happy path so a failed assertion does not leave
// the deploy promise pending until the overall deploy timeout.
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
releaseRemoteHome('/home/user')
deployError = await deployPromise.then(
@@ -278,7 +286,7 @@ describe('deployAndLaunchRelay', () => {
expect(resolveRemoteNodePath).not.toHaveBeenCalled()
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
releaseRemoteHome('/home/user')
await deployPromise
@@ -318,7 +326,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockRejectedValueOnce(sessionLimitError) // concurrent node path probe
mockExecCommand.mockResolvedValueOnce('/home/user') // sequential fallback $HOME
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
await deployAndLaunchRelay(conn)
@@ -348,7 +356,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('/home/user') // concurrent install-state $HOME
mockExecCommand.mockResolvedValueOnce('/home/user') // sequential fallback $HOME
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
await deployAndLaunchRelay(conn)
@@ -458,20 +466,20 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('/home/user') // sequential fallback $HOME
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe
mockExecCommand.mockResolvedValueOnce('DEAD') // socket probe
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY') // socket poll
releaseRemoteHome('/home/user')
await deployPromise
expect(resolveRemoteNodePath).toHaveBeenCalledTimes(2)
})
it('defaults fresh relays to keep-alive-until-reset', async () => {
it('defaults fresh relays to keep-alive-until-reset without rollout artifacts', async () => {
const conn = makeMockConnection()
const mockExecCommand = vi.mocked(execCommand)
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
mockExecCommand.mockResolvedValueOnce('/home/user')
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK')
mockExecCommand.mockResolvedValueOnce('DEAD')
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY')
await deployAndLaunchRelay(conn)
@@ -482,6 +490,8 @@ describe('deployAndLaunchRelay', () => {
.find((cmd) => cmd.includes('--detached'))
expect(launchCommand).toContain(`--grace-time ${DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS}`)
expect(launchCommand).not.toContain('--pty-source-credit-v1')
expect(launchCommand).not.toContain('.pty-source-credit-policy')
})
it('allows an unlimited SSH disconnect grace window', async () => {
@@ -490,7 +500,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
mockExecCommand.mockResolvedValueOnce('/home/user')
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK')
mockExecCommand.mockResolvedValueOnce('DEAD')
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY')
await deployAndLaunchRelay(conn, undefined, 0, 'target-a')
@@ -501,6 +511,8 @@ describe('deployAndLaunchRelay', () => {
.find((cmd) => cmd.includes('--detached'))
expect(launchCommand).toContain('--grace-time 0')
expect(launchCommand).not.toContain('--pty-source-credit-v1')
expect(launchCommand).not.toContain('.pty-source-credit-policy')
})
it('clamps configured SSH disconnect grace to the seven-day maximum', async () => {
@@ -509,7 +521,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
mockExecCommand.mockResolvedValueOnce('/home/user')
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK')
mockExecCommand.mockResolvedValueOnce('DEAD')
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY')
await deployAndLaunchRelay(conn, undefined, MAX_SSH_RELAY_GRACE_PERIOD_SECONDS + 1, 'target-a')
@@ -528,7 +540,7 @@ describe('deployAndLaunchRelay', () => {
mockExecCommand.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64')
mockExecCommand.mockResolvedValueOnce('/home/user')
mockExecCommand.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK')
mockExecCommand.mockResolvedValueOnce('DEAD')
queueLaunchNamespaceAndDeadSocketProbe()
mockExecCommand.mockResolvedValueOnce('READY')
await deployAndLaunchRelay(conn)
@@ -659,6 +671,7 @@ describe('deployAndLaunchRelay', () => {
setTimeout(() => resolve('ORCA-NATIVE-DEPS-OK'), 899_900)
)
)
.mockResolvedValueOnce('') // launch namespace marker
.mockResolvedValueOnce('DEAD')
.mockImplementationOnce((_conn, _command, options) => {
return new Promise<string>((_resolve, reject) => {
@@ -685,9 +698,9 @@ describe('deployAndLaunchRelay', () => {
expect(result).toBeInstanceOf(Error)
expect((result as Error).message).toBe('Relay deployment timed out after 900s')
expect(launchChannel.close).toHaveBeenCalledTimes(1)
expect(mockExecCommand).toHaveBeenCalledTimes(5)
expect(mockExecCommand).toHaveBeenCalledTimes(6)
await vi.advanceTimersByTimeAsync(10_000)
expect(mockExecCommand).toHaveBeenCalledTimes(5)
expect(mockExecCommand).toHaveBeenCalledTimes(6)
} finally {
vi.useRealTimers()
}
@@ -701,11 +714,13 @@ describe('deployAndLaunchRelay', () => {
.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64') // tagged POSIX platform probe A
.mockResolvedValueOnce('/home/user') // $HOME A
.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe A
.mockResolvedValueOnce('') // launch namespace marker A
.mockResolvedValueOnce('DEAD') // probe A
.mockResolvedValueOnce('READY') // poll A
.mockResolvedValueOnce('__ORCA_REMOTE_PLATFORM__ Linux x86_64') // tagged POSIX platform probe B
.mockResolvedValueOnce('/home/user') // $HOME B
.mockResolvedValueOnce('ORCA-NATIVE-DEPS-OK') // native deps probe B
.mockResolvedValueOnce('') // launch namespace marker B
.mockResolvedValueOnce('DEAD') // probe B
.mockResolvedValueOnce('READY') // poll B
@@ -766,6 +781,8 @@ describe('deployAndLaunchRelay', () => {
'"C:/Users/me user/.orca-remote/relay-0.1.0+abcdef012345/agent-hooks/orca-relay-'
)
expect(launchScript).toContain('--endpoint-dir')
expect(launchScript).not.toContain('--pty-source-credit-v1')
expect(launchScript).not.toContain('.pty-source-credit-policy')
expect(launchScript).not.toContain('\\\\.\\pipe\\agent-hooks')
const waitScript = decodedScripts.find((script) => script.includes('deadline=Date.now()')) ?? ''
expect(waitScript).toContain('setTimeout(attempt,intervalMs)')
+96 -26
View File
@@ -11,6 +11,7 @@ import {
isUnconfirmedSshCommandTermination
} from './ssh-relay-deploy-helpers'
import { uploadRelayDirectory, writeRelayFile } from './ssh-relay-install-transfers'
import { writeRelayEndpointCredential } from './ssh-relay-endpoint-credential'
import {
createRelayInstallMarkerCommand,
createRelayInstallNamespace,
@@ -75,12 +76,14 @@ import {
export type RelayDeployResult = {
transport: MultiplexerTransport
serverBuildId?: string
platform: RelayPlatform
hostPlatform?: RemoteHostPlatform
remoteHome?: string
remoteRelayDir?: string
nodePath?: string
sockPath?: string
credentialFile?: string
}
class RelayDirectoryGcConflictError extends Error {
@@ -324,6 +327,7 @@ async function deployAndLaunchRelayAttempt(
let ownsInstallLock = false
let launchGcClaimToken: string | undefined
let launchNamespace: RelayInstallNamespace | undefined
if (alreadyInstalled) {
const launchFence = await repairInstalledNativeDeps(
conn,
@@ -336,6 +340,7 @@ async function deployAndLaunchRelayAttempt(
)
ownsInstallLock = launchFence.ownsInstallLock
launchGcClaimToken = launchFence.gcClaimToken
launchNamespace = launchFence.sftpNamespace
deploySignal?.throwIfAborted()
} else {
// Why: serialize concurrent first-installs via a host-native exclusive lock; the loser polls to re-check installed or steal a stale lock.
@@ -348,7 +353,7 @@ async function deployAndLaunchRelayAttempt(
signal: deploySignal
}))
) {
const installNamespace = createInstallNamespaceIfSupported(
launchNamespace = createInstallNamespaceIfSupported(
conn,
hostPlatform,
homeRelativeRelayDir
@@ -363,7 +368,7 @@ async function deployAndLaunchRelayAttempt(
fullVersion,
hostPlatform,
deploySignal,
installNamespace
launchNamespace
)
console.log('[ssh-relay] Upload complete')
@@ -377,7 +382,7 @@ async function deployAndLaunchRelayAttempt(
nodePath,
deploySignal,
[],
installNamespace
launchNamespace
)
console.log('[ssh-relay] Native deps installed')
@@ -434,12 +439,14 @@ async function deployAndLaunchRelayAttempt(
return {
transport: launched.transport,
serverBuildId: fullVersion,
platform,
hostPlatform,
remoteHome,
remoteRelayDir,
nodePath: launched.nodePath,
sockPath: launched.sockPath
sockPath: launched.sockPath,
credentialFile: launched.credentialFile
}
}
@@ -592,7 +599,11 @@ async function repairInstalledNativeDeps(
nodePath: string,
homeRelativeRelayDir: string,
signal?: AbortSignal
): Promise<{ ownsInstallLock: boolean; gcClaimToken?: string }> {
): Promise<{
ownsInstallLock: boolean
gcClaimToken?: string
sftpNamespace?: RelayInstallNamespace
}> {
const initialProbe = await probeRequiredNativeDeps(
conn,
remoteDir,
@@ -627,7 +638,27 @@ async function repairInstalledNativeDeps(
: undefined
if (initialProbe.available) {
// Why: even a healthy reconnect stays fenced until launch liveness is observable, or cross-version GC can rename after this probe.
return { ownsInstallLock: lockResult === 'acquired', gcClaimToken }
if (lockResult !== 'acquired') {
return { ownsInstallLock: false, gcClaimToken }
}
try {
return {
ownsInstallLock: true,
sftpNamespace: await createRelayLaunchNamespace(
conn,
hostPlatform,
remoteDir,
homeRelativeRelayDir,
signal
)
}
} catch (err) {
signal?.throwIfAborted()
console.warn(
`[ssh-relay] Launch namespace marker is unconfirmed at ${remoteDir}; deferring lock ownership to stale recovery`
)
return { ownsInstallLock: !isUnconfirmedSshCommandTermination(err) }
}
}
// Why: an already-installed relay can launch degraded, so native-deps repair is best-effort — lock contention and failures must not abort the connection.
@@ -641,9 +672,10 @@ async function repairInstalledNativeDeps(
try {
// Why: older complete relay dirs predate @parcel/watcher; re-probe under the lock so only one reconnect mutates the dir.
const probe = await probeRequiredNativeDeps(conn, remoteDir, hostPlatform, nodePath, signal)
let repairNamespace: RelayInstallNamespace | undefined
if (!probe.available) {
// Why: only stamp ownership once the locked recheck proves this connection is the one about to write.
const repairNamespace = await createRepairInstallMarker(
repairNamespace = await createRelayLaunchNamespace(
conn,
hostPlatform,
remoteDir,
@@ -662,7 +694,7 @@ async function repairInstalledNativeDeps(
)
await finalizeInstall(conn, remoteDir, hostPlatform, { signal, releaseLock: false })
}
return { ownsInstallLock: true }
return { ownsInstallLock: true, sftpNamespace: repairNamespace }
} catch (err) {
const terminationUnconfirmed = isUnconfirmedSshCommandTermination(err)
// Why: hold a confirmed-failure lock through degraded launch so GC can't move the relay before liveness is visible.
@@ -677,10 +709,10 @@ async function repairInstalledNativeDeps(
}
/**
* Stamp this connection as the install owner during repair. Marker creation is
* best-effort: without it the writes simply keep using the shell path.
* Stamp this connection as the launch writer while it owns the install lock.
* Confirmed marker failures fall back to shell-path credential generation.
*/
async function createRepairInstallMarker(
async function createRelayLaunchNamespace(
conn: SshConnection,
hostPlatform: RemoteHostPlatform,
remoteDir: string,
@@ -1157,7 +1189,12 @@ async function launchRelay(
graceTimeSeconds?: number,
relayInstanceId?: string,
signal?: AbortSignal
): Promise<{ transport: MultiplexerTransport; nodePath: string; sockPath: string }> {
): Promise<{
transport: MultiplexerTransport
nodePath: string
sockPath: string
credentialFile: string
}> {
// Why: graceTimeSeconds comes from user-editable SshTarget config; floor+clamp to an integer prevents shell injection if the type ever loosened.
const requestedGraceTime = Math.floor(graceTimeSeconds ?? DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS)
const graceTime =
@@ -1173,21 +1210,23 @@ async function launchRelay(
const sockName = relaySocketNameForInstanceId(relayInstanceId)
const sockFile = relayEndpointForHost(hostPlatform, remoteDir, sockName)
const endpointDir = relayHookEndpointDirForHost(hostPlatform, remoteDir, sockFile)
const credentialFile = joinRemotePath(hostPlatform, remoteDir, `${sockName}.credential`)
if (isWindowsRemoteHost(hostPlatform)) {
const activePipeMarkerPath = windowsActivePipeMarkerPath(hostPlatform, remoteDir, sockName)
const activeEndpoint = (await readWindowsActiveRelayEndpoint(
const discoveredActiveEndpoint = await readWindowsActiveRelayEndpoint(
conn,
hostPlatform,
remoteDir,
activePipeMarkerPath,
signal
)) ?? {
)
const activeEndpoint = discoveredActiveEndpoint ?? {
sockPath: sockFile,
endpointDir
}
const fallbackEndpoint = buildWindowsRelayFallbackEndpoint(hostPlatform, remoteDir, sockName)
return launchWindowsRelay(
const launched = await launchWindowsRelay(
conn,
hostPlatform,
{
@@ -1197,10 +1236,12 @@ async function launchRelay(
endpointDir: activeEndpoint.endpointDir,
graceTime,
activePipeMarkerPath,
reconnectFallback: fallbackEndpoint
reconnectFallback: fallbackEndpoint,
credentialFile
},
signal
)
return { ...launched, credentialFile }
}
// Why: after a restart the relay may still be alive in its grace period; --connect to its socket preserves PTY state and scrollback.
@@ -1215,12 +1256,12 @@ async function launchRelay(
console.log('[ssh-relay] Existing relay socket found, attempting reconnect...')
try {
const channel = await conn.exec(
`cd ${escapedDir} && ${escapedNode} relay.js --connect --sock-path ${shellEscape(sockFile)}`,
`cd ${escapedDir} && ${escapedNode} relay.js --connect --sock-path ${shellEscape(sockFile)} --credential-file ${shellEscape(credentialFile)}`,
{ signal }
)
const transport = await waitForSentinel(channel, signal)
console.log('[ssh-relay] Reconnected to existing relay via socket')
return { transport, nodePath, sockPath: sockFile }
return { transport, nodePath, sockPath: sockFile, credentialFile }
} catch (err) {
signal?.throwIfAborted()
console.warn(
@@ -1249,8 +1290,11 @@ async function launchRelay(
// Why: relay must outlive the SSH connection so PTY sessions survive app restarts — nohup + </dev/null + & detach it from the exec channel.
// Why: execCommand would block on channel close that backgrounded children never allow; fire-and-forget via conn.exec, the socket poll detects readiness.
const logFile = `${remoteDir}/relay.log`
await writeRelayEndpointCredential(conn, hostPlatform, nodePath, credentialFile, {
signal
})
// Why: --log-file lets the relay rotate relay.log in-process; the shell redirect stays to capture pre-JS boot/crash output.
const launchCmd = `cd ${escapedDir} && nohup ${escapedNode} relay.js --detached --grace-time ${graceTime} --sock-path ${shellEscape(sockFile)} --log-file ${shellEscape(logFile)} > ${shellEscape(logFile)} 2>&1 </dev/null &`
const launchCmd = `cd ${escapedDir} && chmod 600 ${shellEscape(credentialFile)} && nohup ${escapedNode} relay.js --detached --grace-time ${graceTime} --sock-path ${shellEscape(sockFile)} --credential-file ${shellEscape(credentialFile)} --log-file ${shellEscape(logFile)} > ${shellEscape(logFile)} 2>&1 </dev/null &`
const launchChannel = await conn.exec(launchCmd, { signal })
launchChannel.on('data', () => {})
launchChannel.on('error', () => {})
@@ -1300,10 +1344,15 @@ async function launchRelay(
// Why: backgrounded relay's stdout goes to a log file, not the exec channel; --connect bridges this channel to its Unix socket.
const channel = await conn.exec(
`cd ${escapedDir} && ${escapedNode} relay.js --connect --sock-path ${shellEscape(sockFile)}`,
`cd ${escapedDir} && ${escapedNode} relay.js --connect --sock-path ${shellEscape(sockFile)} --credential-file ${shellEscape(credentialFile)}`,
{ signal }
)
return { transport: await waitForSentinel(channel, signal), nodePath, sockPath: sockFile }
return {
transport: await waitForSentinel(channel, signal),
nodePath,
sockPath: sockFile,
credentialFile
}
}
function waitForRelayPoll(delayMs: number, signal?: AbortSignal): Promise<void> {
@@ -1398,6 +1447,7 @@ type WindowsRelayLaunchOptions = {
nodePath: string
graceTime: number
activePipeMarkerPath: string
credentialFile: string
} & WindowsRelayEndpoint & {
reconnectFallback?: WindowsRelayEndpoint
}
@@ -1467,6 +1517,13 @@ async function launchWindowsRelay(
const logFile = joinRemotePath(hostPlatform, launchOpts.remoteDir, 'relay.log')
const errFile = joinRemotePath(hostPlatform, launchOpts.remoteDir, 'relay.err.log')
await writeRelayEndpointCredential(
conn,
hostPlatform,
launchOpts.nodePath,
launchOpts.credentialFile,
{ signal }
)
await execHostCommand(
conn,
hostPlatform,
@@ -1478,7 +1535,8 @@ async function launchWindowsRelay(
launchOpts.endpointDir,
launchOpts.graceTime,
logFile,
errFile
errFile,
launchOpts.credentialFile
),
{ signal }
)
@@ -1529,11 +1587,18 @@ async function connectWindowsRelay(
remoteDir: string
nodePath: string
sockPath: string
credentialFile: string
},
signal?: AbortSignal
): Promise<MultiplexerTransport> {
const channel = await conn.exec(
windowsRelayConnectCommand(hostPlatform, opts.nodePath, opts.remoteDir, opts.sockPath),
windowsRelayConnectCommand(
hostPlatform,
opts.nodePath,
opts.remoteDir,
opts.sockPath,
opts.credentialFile
),
{ wrapCommand: false, signal }
)
return waitForSentinel(channel, signal)
@@ -1543,13 +1608,14 @@ function windowsRelayConnectCommand(
hostPlatform: RemoteHostPlatform,
nodePath: string,
remoteDir: string,
sockPath: string
sockPath: string,
credentialFile: string
): string {
return commandWithNodePath(
hostPlatform,
nodePath,
remoteDir,
`& ${powerShellLiteral(nodePath)} relay.js --connect --sock-path ${powerShellLiteral(sockPath)}`
`& ${powerShellLiteral(nodePath)} relay.js --connect --sock-path ${powerShellLiteral(sockPath)} --credential-file ${powerShellLiteral(credentialFile)}`
)
}
@@ -1561,7 +1627,8 @@ function windowsRelayLaunchCommand(
endpointDir: string,
graceTime: number,
logFile: string,
errFile: string
errFile: string,
credentialFile: string
): string {
const relayScript = joinRemotePath(hostPlatform, remoteDir, 'relay.js')
// Why: Windows sshd kills the exec channel's process tree on close; WMI re-parents the detached relay to survive.
@@ -1574,6 +1641,8 @@ function windowsRelayLaunchCommand(
String(graceTime),
'--sock-path',
quoted(sockPath),
'--credential-file',
quoted(credentialFile),
'--endpoint-dir',
quoted(endpointDir),
// Why: --log-file owns rotation; shell redirects still capture pre-JS boot/crash output.
@@ -1588,6 +1657,7 @@ function windowsRelayLaunchCommand(
nodePath,
remoteDir,
[
`& icacls.exe ${powerShellLiteral(credentialFile)} /inheritance:r /grant:r "$($env:USERNAME):(R,W)" | Out-Null`,
`$result = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${powerShellLiteral(wmiCommandLine)}; CurrentDirectory = ${powerShellLiteral(remoteDir)} }`,
`if ($result.ReturnValue -ne 0) { throw "Win32_Process.Create failed with $($result.ReturnValue)" }`
].join('; ')
@@ -0,0 +1,50 @@
import { Buffer } from 'node:buffer'
import { describe, expect, it } from 'vitest'
import { relayEndpointCredentialWriteCommand } from './ssh-relay-endpoint-credential'
import { getRemoteHostPlatform } from './ssh-remote-platform'
function decodePowerShellCommand(command: string): string {
const encoded = command.match(/-EncodedCommand\s+([A-Za-z0-9+/=]+)/)?.[1]
if (!encoded) {
throw new Error(`Expected an encoded PowerShell command: ${command}`)
}
return Buffer.from(encoded, 'base64').toString('utf16le')
}
describe('relay endpoint credential writes', () => {
it('publishes a POSIX credential only from a restrictive temporary file', () => {
const command = relayEndpointCredentialWriteCommand(
getRemoteHostPlatform('linux-x64'),
'/opt/orca node/bin/node',
'/home/me user/.orca-remote/relay.sock.credential'
)
expect(command).toContain('{flag:"wx",mode:0o600}')
expect(command).toContain('fs.writeFileSync(t,')
expect(command).not.toContain('fs.writeFileSync(p,')
expect(command.indexOf('fs.writeFileSync(t,')).toBeLessThan(
command.indexOf('fs.renameSync(t,p)')
)
expect(command).toContain("'/home/me user/.orca-remote/relay.sock.credential'")
})
it('creates a Windows credential with its owner-only ACL before publication', () => {
const script = decodePowerShellCommand(
relayEndpointCredentialWriteCommand(
getRemoteHostPlatform('win32-x64'),
'C:/Program Files/nodejs/node.exe',
'C:/Users/me user/.orca-remote/relay.sock.credential'
)
)
expect(script).toContain("$path = 'C:/Users/me user/.orca-remote/relay.sock.credential'")
expect(script).toContain('$security.SetAccessRuleProtection($true,$false)')
expect(script).toContain('[System.IO.FileStream]::new($tempPath')
expect(script).toContain('[System.IO.FileOptions]::WriteThrough,$security)')
expect(script.indexOf('[System.IO.FileStream]::new')).toBeLessThan(
script.indexOf('[System.IO.File]::Move($tempPath,$path)')
)
expect(script).not.toContain('Set-Acl')
expect(script).not.toContain('icacls')
})
})
@@ -0,0 +1,61 @@
import type { SshConnection } from './ssh-connection'
import { shellEscape } from './ssh-connection-utils'
import { execCommand } from './ssh-relay-deploy-helpers'
import { isWindowsRemoteHost, type RemoteHostPlatform } from './ssh-remote-platform'
import { powerShellCommand, powerShellLiteral } from './ssh-remote-powershell'
const POSIX_CREDENTIAL_SCRIPT =
'const fs=require("fs"),crypto=require("crypto"),p=process.argv[1],' +
't=p+"."+process.pid+"."+crypto.randomBytes(8).toString("hex")+".tmp";' +
'try{' +
'fs.writeFileSync(t,crypto.randomBytes(32).toString("base64url"),{flag:"wx",mode:0o600});' +
'fs.renameSync(t,p)' +
'}finally{try{fs.unlinkSync(t)}catch(e){if(e.code!=="ENOENT")throw e}}'
export function relayEndpointCredentialWriteCommand(
hostPlatform: RemoteHostPlatform,
nodePath: string,
credentialFile: string
): string {
if (!isWindowsRemoteHost(hostPlatform)) {
return `${shellEscape(nodePath)} -e ${shellEscape(POSIX_CREDENTIAL_SCRIPT)} ${shellEscape(credentialFile)}`
}
return powerShellCommand(
[
'$ErrorActionPreference = "Stop"',
`$path = ${powerShellLiteral(credentialFile)}`,
'$tempPath = $path + "." + [Guid]::NewGuid().ToString("N") + ".tmp"',
'$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User',
'$security = [System.Security.AccessControl.FileSecurity]::new()',
'$security.SetOwner($identity)',
'$security.SetAccessRuleProtection($true,$false)',
'$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity,[System.Security.AccessControl.FileSystemRights]::FullControl,[System.Security.AccessControl.AccessControlType]::Allow)',
'$security.AddAccessRule($rule)',
'$random = [byte[]]::new(32)',
'$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()',
'try { $rng.GetBytes($random) } finally { $rng.Dispose() }',
'$credential = [Convert]::ToBase64String($random).TrimEnd("=").Replace("+","-").Replace("/","_")',
'$data = [System.Text.UTF8Encoding]::new($false).GetBytes($credential)',
'$stream = [System.IO.FileStream]::new($tempPath,[System.IO.FileMode]::CreateNew,[System.Security.AccessControl.FileSystemRights]::Write,[System.IO.FileShare]::None,4096,[System.IO.FileOptions]::WriteThrough,$security)',
'try { $stream.Write($data,0,$data.Length) } finally { $stream.Dispose() }',
'try { [System.IO.File]::Delete($path); [System.IO.File]::Move($tempPath,$path) } finally { [System.IO.File]::Delete($tempPath) }'
].join('; ')
)
}
export async function writeRelayEndpointCredential(
conn: SshConnection,
hostPlatform: RemoteHostPlatform,
nodePath: string,
credentialFile: string,
options?: { signal?: AbortSignal }
): Promise<void> {
await execCommand(
conn,
relayEndpointCredentialWriteCommand(hostPlatform, nodePath, credentialFile),
{
wrapCommand: !isWindowsRemoteHost(hostPlatform),
signal: options?.signal
}
)
}
+2 -1
View File
@@ -69,7 +69,8 @@ function makeConnection(): SshConnection {
}
return {
canRunConcurrentExecCommands: vi.fn().mockReturnValue(true),
exec: vi.fn().mockResolvedValue(channel)
exec: vi.fn().mockResolvedValue(channel),
writeFile: vi.fn().mockResolvedValue(undefined)
} as unknown as SshConnection
}
@@ -71,6 +71,7 @@ export function makeRepairToolchainSkipExecResponses(): ExecResponse[] {
'', // cat probe stderr
'', // rm -f probe stderr
'DEAD',
'', // publish the per-launch credential
'READY'
]
}
@@ -80,7 +81,7 @@ export function decodePowerShellCommand(command: string): string | null {
return match ? Buffer.from(match[1], 'base64').toString('utf16le') : null
}
// Happy-path exec order: uname, $HOME, mkdir, chmod node, npm install, chmod prebuilds, probe, [cat stderr + rm if MISSING], [rebuild → chmod → re-probe if MISSING], DEAD, READY.
// Happy-path exec order ends with socket probe, credential publication, then readiness poll.
// When the probe rejects (SSH channel close or vanished install dir), the catch skips both stderr-capture and the rm.
// A failed npm install takes one of the two early branches below instead, which never reach `probe`.
export function makeExecResponses(opts: {
@@ -134,6 +135,7 @@ export function makeExecResponses(opts: {
'', // cat probe stderr
'', // rm -f probe stderr
'DEAD',
'', // publish the per-launch credential
'READY'
]
}
@@ -176,6 +178,6 @@ export function makeExecResponses(opts: {
slots.push('') // rm -f stderr after rebuild probe
}
}
slots.push('DEAD', 'READY')
slots.push('DEAD', '', 'READY')
return slots
}
@@ -567,6 +567,7 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
'MISSING\n', // rebuilt native process still cannot load
'', // no persisted active pipe marker
'WAITING',
'', // publish the per-launch credential
'', // WMI relay launch
'READY',
'' // persist active pipe marker
@@ -661,6 +662,7 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
'ORCA-NPTY-PROBE-OK\n',
'', // rm probe stderr
'DEAD',
'', // publish the per-launch credential
'READY'
])
@@ -712,6 +714,7 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
'', // SFTP-namespace install-owner marker (repair)
{ reject: 'npm ERR! network ETIMEDOUT' }, // npm install fails (offline)
'DEAD',
'', // remote credential generation after degraded repair
'READY'
])
@@ -739,6 +742,7 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
})
)
.mockResolvedValueOnce('DEAD')
.mockResolvedValueOnce('') // remote credential generation after degraded repair
.mockResolvedValueOnce('READY')
await deployAndLaunchRelay(conn)
@@ -880,7 +884,14 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
vi.mocked(isRelayAlreadyInstalled).mockResolvedValue(true)
vi.mocked(tryAcquireRelayRepairLock).mockResolvedValueOnce(lockResult)
const conn = makeMockConnection(sftpCapture)
feed(['__ORCA_REMOTE_PLATFORM__ Linux x86_64', '/home/u', 'MISSING', 'DEAD', 'READY'])
feed([
'__ORCA_REMOTE_PLATFORM__ Linux x86_64',
'/home/u',
'MISSING',
'DEAD',
'', // remote credential generation without a namespace marker
'READY'
])
await deployAndLaunchRelay(conn)
@@ -899,7 +910,9 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
'__ORCA_REMOTE_PLATFORM__ Linux x86_64',
'/home/u',
'ORCA-NATIVE-DEPS-OK',
'', // launch namespace marker
'DEAD',
'', // publish the per-launch credential
'READY'
])
@@ -922,7 +935,9 @@ describe('installNativeDeps (via deployAndLaunchRelay)', () => {
'__ORCA_REMOTE_PLATFORM__ Linux x86_64',
'/home/u',
'ORCA-NATIVE-DEPS-OK',
'', // launch namespace marker
'DEAD',
'', // publish the per-launch credential
'READY'
])
@@ -15,6 +15,7 @@ import {
import { agentHookServer, _internals as agentHookInternals } from '../agent-hooks/server'
import { getSshPtyProvider } from '../ipc/pty'
import { toAppSshPtyId } from '../providers/ssh-pty-id'
import { DEFAULT_PTY_SOURCE_WINDOW_SU } from '../../shared/pty-source-credit-contract'
const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({
getCohortAtEmitMock: vi.fn(),
@@ -97,6 +98,21 @@ function createFakeRelay(): FakeRelay {
})
relayFeed = (data) => dispatcher.feed(data)
dispatcher.onRequest('pty.openClient', async (params) => ({
protocolVersion: 1,
serverBuildId: 'test-relay-build',
clientGeneration: 1,
role: 'session-owner',
ownerGeneration:
typeof (params.resume as { ownerGeneration?: unknown } | undefined)?.ownerGeneration ===
'number'
? (params.resume as { ownerGeneration: number }).ownerGeneration + 1
: 1,
ownerLease: 'test-owner-lease',
capabilities: {
outputFlowControl: { version: 1, windowSu: DEFAULT_PTY_SOURCE_WINDOW_SU }
}
}))
dispatcher.onRequest('session.resolveHome', async (params) => ({
resolvedPath: params.path === '~' ? '/home/orca' : params.path
}))
@@ -224,6 +240,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
const events: CapturedStatus[] = []
@@ -277,8 +294,16 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
const initialRelay = createFakeRelay()
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay)
.mockResolvedValueOnce({ transport: initialRelay.transport, platform: 'linux-x64' })
.mockResolvedValueOnce({ transport: relay.transport, platform: 'linux-x64' })
.mockResolvedValueOnce({
transport: initialRelay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
.mockResolvedValueOnce({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
const clearListener = vi.fn()
agentHookServer.setPaneStatusClearListener(clearListener)
session = createSession('conn-clear')
@@ -318,6 +343,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
)
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
const events: CapturedStatus[] = []
@@ -345,6 +371,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
const events: CapturedStatus[] = []
@@ -375,6 +402,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
@@ -434,6 +462,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
const ingestSpy = vi.spyOn(agentHookServer, 'ingestRemote')
@@ -488,6 +517,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
@@ -535,6 +565,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => {
relay = createFakeRelay()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: relay.transport,
serverBuildId: 'test-relay-build',
platform: 'linux-x64'
})
@@ -1,19 +1,65 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SshRelaySession } from './ssh-relay-session'
import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures'
import {
createMismatchedOwnerRecoveryError,
createMockDeps,
mockDeploySuccess
} from './ssh-relay-session-test-fixtures'
const { muxRequestMock } = vi.hoisted(() => ({ muxRequestMock: vi.fn() }))
const {
acceptOutputDataMock,
muxRequestMock,
onNotificationByMethodMock,
notifyWithSettlementMock,
openConsumerSessionMock,
pauseAdapterMock,
muxDisposeMock,
attachForReconnectMock,
beginMigrationMock,
ptyDataHandlerRef
} = vi.hoisted(() => ({
acceptOutputDataMock: vi.fn().mockResolvedValue(undefined),
muxRequestMock: vi.fn(),
onNotificationByMethodMock: vi.fn(),
notifyWithSettlementMock: vi.fn(),
openConsumerSessionMock: vi.fn(),
pauseAdapterMock: vi.fn(),
muxDisposeMock: vi.fn(),
attachForReconnectMock: vi.fn().mockResolvedValue({}),
beginMigrationMock: vi.fn(() => ({
byPty: new Map(),
completion: Promise.resolve()
})),
ptyDataHandlerRef: { current: undefined as undefined | ((payload: unknown) => void) }
}))
vi.mock('./ssh-relay-deploy', () => ({ deployAndLaunchRelay: vi.fn() }))
vi.mock('./ssh-pty-consumer-session', () => ({
openSshPtyConsumerSession: openConsumerSessionMock
}))
vi.mock('../ipc/ssh-pty-output-intake-registry', () => ({
acceptSshPtyOutputData: acceptOutputDataMock,
acceptSshPtyOutputExit: vi.fn().mockResolvedValue(undefined),
allocateSshPtyProviderGeneration: vi.fn(() => 23),
beginSshPtyOutputGenerationMigration: beginMigrationMock,
closeSshPtyOutputGeneration: vi.fn(),
getSshPtyAcceptedSourceCheckpoints: vi.fn(() => []),
installSshPtySourceAckPublisher: vi.fn(() => () => {}),
installSshPtySourceCancellationPublisher: vi.fn(() => () => {}),
applySshPtySourceCancellationProof: vi.fn(),
applySshPtySourceRecoveryCancellationProof: vi.fn()
}))
vi.mock('./ssh-channel-multiplexer', () => ({
SshChannelMultiplexer: class MockSshChannelMultiplexer {
notify = vi.fn()
notifyWithSettlement = notifyWithSettlementMock
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = onNotificationByMethodMock.mockImplementation(() => () => {})
onRequest = vi.fn().mockReturnValue(() => {})
onDispose = vi.fn().mockReturnValue(() => {})
dispose = vi.fn()
dispose = muxDisposeMock
isDisposed = vi.fn().mockReturnValue(false)
}
}))
@@ -26,11 +72,15 @@ vi.mock('../providers/ssh-pty-provider', () => ({
isSshPtyNotFoundError: vi.fn().mockReturnValue(false),
isSshPtyIdentityMismatchError: vi.fn().mockReturnValue(false),
SshPtyProvider: class MockSshPtyProvider {
onData = vi.fn().mockReturnValue(() => {})
onData = vi.fn().mockImplementation((handler) => {
ptyDataHandlerRef.current = handler
return () => {}
})
onReplay = vi.fn().mockReturnValue(() => {})
onExit = vi.fn().mockReturnValue(() => {})
attach = vi.fn().mockResolvedValue(undefined)
attachForReconnect = vi.fn().mockResolvedValue({})
attachForReconnect = attachForReconnectMock
setPtyDeliveryPauseAdapter = pauseAdapterMock
dispose = vi.fn()
}
}))
@@ -53,6 +103,7 @@ vi.mock('../ipc/pty', () => ({
clearPtyOwnershipForConnection: vi.fn(),
clearProviderPtyState: vi.fn(),
deletePtyOwnership: vi.fn(),
restorePtyIncarnation: vi.fn(),
setPtyOwnership: vi.fn()
}))
@@ -67,15 +118,251 @@ vi.mock('../providers/ssh-git-dispatch', () => ({
unregisterSshGitProvider: vi.fn()
}))
const { registerSshPtyProvider } = await import('../ipc/pty')
const {
clearProviderPtyState,
clearPtyOwnershipForConnection,
deletePtyOwnership,
getSshPtyProvider,
getPtyIdsForConnection,
registerSshPtyProvider,
setPtyOwnership
} = await import('../ipc/pty')
const { closeSshPtyOutputGeneration } = await import('../ipc/ssh-pty-output-intake-registry')
const { applySshPtySourceCancellationProof } = await import('../ipc/ssh-pty-output-intake-registry')
const { applySshPtySourceRecoveryCancellationProof } =
await import('../ipc/ssh-pty-output-intake-registry')
const { getSshPtyAcceptedSourceCheckpoints } = await import('../ipc/ssh-pty-output-intake-registry')
const { installSshPtySourceAckPublisher } = await import('../ipc/ssh-pty-output-intake-registry')
const { deployAndLaunchRelay } = await import('./ssh-relay-deploy')
describe('SshRelaySession data delivery', () => {
beforeEach(() => {
vi.clearAllMocks()
ptyDataHandlerRef.current = undefined
attachForReconnectMock.mockResolvedValue({})
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([])
vi.mocked(applySshPtySourceCancellationProof).mockReturnValue(true)
vi.mocked(applySshPtySourceRecoveryCancellationProof).mockReturnValue(true)
openConsumerSessionMock.mockImplementation(async (_mux, options) => ({
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: 1,
ownerGeneration: 1,
ownerLease: 'test-owner-lease',
...(options.outputFlowControl
? {
outputFlowControl: { version: 1, windowSu: options.outputFlowControl.requestedWindowSu }
}
: {})
}))
muxRequestMock.mockResolvedValue([])
mockDeploySuccess()
})
async function runRecoverySequence(args: {
targetId: string
recoveryEndSu: number
recoveryFrame?: readonly [startSu: number, endSu: number]
liveFrame?: readonly [startSu: number, endSu: number]
}) {
muxRequestMock.mockImplementation(async (method) =>
method === 'pty.cancelDelivery'
? { canceled: true, sentEndSu: args.recoveryEndSu, creditedEndSu: 4 }
: []
)
let generation = 0
openConsumerSessionMock.mockImplementation(async (_mux, options) => ({
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: ++generation,
ownerGeneration: generation,
ownerLease: `owner-lease-${generation}`,
outputFlowControl: { version: 1, windowSu: 256 * 1024 }
}))
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([
{
id: `ssh:${args.targetId}@@pty-1`,
providerGeneration: 23,
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
}
])
const deps = createMockDeps()
const session = new SshRelaySession(
args.targetId,
deps.getMainWindow,
deps.mockStore,
deps.mockPortForward
)
await session.establish(deps.mockConn)
vi.mocked(getPtyIdsForConnection).mockReturnValue([`ssh:${args.targetId}@@pty-1`])
vi.mocked(getSshPtyProvider).mockImplementation(
() => vi.mocked(registerSshPtyProvider).mock.calls.at(-1)?.[1]
)
attachForReconnectMock.mockImplementation(async () => {
queueMicrotask(() => {
if (args.recoveryFrame) {
const [sourceStartSu, sourceEndSu] = args.recoveryFrame
ptyDataHandlerRef.current?.({
id: `ssh:${args.targetId}@@pty-1`,
data: 'recovery',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: sourceEndSu - sourceStartSu,
source: {
relayPtyId: 'pty-1',
spanId: `new-token:${sourceStartSu}:${sourceEndSu}`,
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu,
sourceEndSu
}
})
}
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: args.recoveryEndSu
})
if (args.liveFrame) {
const [sourceStartSu, sourceEndSu] = args.liveFrame
ptyDataHandlerRef.current?.({
id: `ssh:${args.targetId}@@pty-1`,
data: 'live',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: sourceEndSu - sourceStartSu,
source: {
relayPtyId: 'pty-1',
spanId: `new-token:${sourceStartSu}:${sourceEndSu}`,
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu,
sourceEndSu
}
})
}
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: args.recoveryEndSu
}
}
})
await session.reconnect(deps.mockConn)
return { ...deps, session }
}
it('transfers negotiated owner recovery exactly once across an explicit detach', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: { write: vi.fn(), onData: vi.fn(), onClose: vi.fn() },
platform: 'linux-x64',
serverBuildId: 'test-relay-build'
})
const first = new SshRelaySession('recovery-target', getMainWindow, mockStore, mockPortForward)
await first.establish(mockConn)
first.detach()
const second = new SshRelaySession('recovery-target', getMainWindow, mockStore, mockPortForward)
await second.establish(mockConn)
const firstOpen = openConsumerSessionMock.mock.calls[0]?.[1]
const recoveredOpen = openConsumerSessionMock.mock.calls[1]?.[1]
expect(recoveredOpen).toMatchObject({
clientInstanceId: firstOpen.clientInstanceId,
resume: { ownerGeneration: 1, ownerLease: 'test-owner-lease' }
})
second.dispose()
const fresh = new SshRelaySession('recovery-target', getMainWindow, mockStore, mockPortForward)
await fresh.establish(mockConn)
const freshOpen = openConsumerSessionMock.mock.calls[2]?.[1]
expect(freshOpen.clientInstanceId).not.toBe(firstOpen.clientInstanceId)
expect(freshOpen).not.toHaveProperty('resume')
fresh.dispose()
})
it('clears stale owner recovery and retries a fresh same-build relay once without resume', async () => {
const targetId = 'fresh-relay-retry'
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
vi.mocked(deployAndLaunchRelay).mockResolvedValue({
transport: { write: vi.fn(), onData: vi.fn(), onClose: vi.fn() },
platform: 'linux-x64',
serverBuildId: 'test-relay-build'
})
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([
{
id: `ssh:${targetId}@@pty-1`,
providerGeneration: 23,
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
}
])
const first = new SshRelaySession(targetId, getMainWindow, mockStore, mockPortForward)
await first.establish(mockConn)
first.detach()
openConsumerSessionMock
.mockRejectedValueOnce(createMismatchedOwnerRecoveryError())
.mockImplementationOnce(async (_mux, options) => ({
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: 1,
ownerGeneration: 1,
ownerLease: 'fresh-owner-lease',
outputFlowControl: { version: 1, windowSu: 256 * 1024 }
}))
vi.mocked(getPtyIdsForConnection).mockReturnValue([`ssh:${targetId}@@pty-1`])
vi.mocked(getSshPtyProvider).mockImplementation(
() => vi.mocked(registerSshPtyProvider).mock.calls.at(-1)?.[1]
)
attachForReconnectMock.mockResolvedValue({
incarnationId: 'incarnation-1',
sourceRecovery: { status: 'restoreRequired', reason: 'checkpointUnavailable' }
})
const second = new SshRelaySession(targetId, getMainWindow, mockStore, mockPortForward)
const openCallCountBeforeRetry = openConsumerSessionMock.mock.calls.length
await second.establish(mockConn)
const retryCalls = openConsumerSessionMock.mock.calls
.slice(openCallCountBeforeRetry)
.map(([, options]) => options)
expect(retryCalls).toHaveLength(2)
expect(retryCalls[0]).toHaveProperty('resume')
expect(retryCalls[1]).not.toHaveProperty('resume')
expect(attachForReconnectMock).toHaveBeenCalledWith(
'pty-1',
undefined,
Object.freeze({ status: 'checkpointUnavailable' })
)
second.dispose()
})
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() }
@@ -95,18 +382,425 @@ describe('SshRelaySession data delivery', () => {
data: string
sequenceChars?: number
transformed?: boolean
providerGeneration: number
ptyIncarnation: string
source: {
relayPtyId: string
spanId: string
clientGeneration: number
ownerGeneration: number
deliveryToken: string
sourceStartSu: number
sourceEndSu: number
}
}) => void
const source = {
relayPtyId: 'pty-1',
spanId: 'token-1:0:9',
clientGeneration: 1,
ownerGeneration: 1,
deliveryToken: 'token-1',
sourceStartSu: 0,
sourceEndSu: 9
}
onData({ id: 'ssh-pty-1', data: '', sequenceChars: 9, transformed: true })
expect(runtime.onPtyData).toHaveBeenCalledWith('ssh-pty-1', '', expect.any(Number), 9, true)
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
onData({
id: 'ssh-pty-1',
data: '',
sequenceChars: 9,
transformed: true,
seq: 17,
rawLength: 9
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
source
})
expect(acceptOutputDataMock).toHaveBeenCalledWith({
id: 'ssh-pty-1',
data: '',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
rawLength: 9,
transformed: true,
source
})
expect(runtime.onPtyData).not.toHaveBeenCalled()
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', expect.anything())
})
it('forwards negotiated source identity to the bounded intake exactly once', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
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 {
onData: ReturnType<typeof vi.fn>
}
const onData = ptyProvider.onData.mock.calls[0]?.[0] as (payload: {
id: string
data: string
providerGeneration: number
ptyIncarnation: string
source: {
relayPtyId: string
spanId: string
clientGeneration: number
ownerGeneration: number
deliveryToken: string
sourceStartSu: number
sourceEndSu: number
}
}) => void
const source = {
relayPtyId: 'pty-1',
spanId: 'token-1:0:4',
clientGeneration: 1,
ownerGeneration: 1,
deliveryToken: 'token-1',
sourceStartSu: 0,
sourceEndSu: 4
}
onData({
id: 'ssh-pty-1',
data: 'data',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
source
})
expect(acceptOutputDataMock).toHaveBeenCalledOnce()
expect(acceptOutputDataMock).toHaveBeenCalledWith(
expect.objectContaining({ id: 'ssh-pty-1', rawLength: 4, source })
)
})
it('rejects missing negotiated source identity before main admission', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
const provider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as {
onData: ReturnType<typeof vi.fn>
}
const onData = provider.onData.mock.calls[0]?.[0] as (payload: Record<string, unknown>) => void
onData({
id: 'ssh-pty-1',
data: 'data',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1'
})
expect(acceptOutputDataMock).not.toHaveBeenCalled()
expect(closeSshPtyOutputGeneration).toHaveBeenCalledWith(
23,
'ssh_source_frame_malformed_or_missing'
)
})
it('keeps unoffered source metadata out of legacy intake', async () => {
openConsumerSessionMock.mockImplementationOnce(async (_mux, options) => ({
mode: 'legacy-fallback',
clientInstanceId: options.clientInstanceId,
serverBuildId: 'test-relay-build'
}))
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
const provider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as {
onData: ReturnType<typeof vi.fn>
}
const onData = provider.onData.mock.calls[0]?.[0] as (payload: Record<string, unknown>) => void
onData({
id: 'ssh-pty-1',
data: 'data',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
source: {
relayPtyId: 'pty-1',
spanId: 'token-1:0:4',
clientGeneration: 1,
ownerGeneration: 1,
deliveryToken: 'token-1',
sourceStartSu: 0,
sourceEndSu: 4
}
})
expect(acceptOutputDataMock).toHaveBeenCalledWith(
expect.not.objectContaining({ source: expect.anything() })
)
})
it('keeps same-build method-not-found fallback token-free', async () => {
openConsumerSessionMock.mockImplementationOnce(async (_mux, options) => ({
mode: 'legacy-fallback',
clientInstanceId: options.clientInstanceId,
serverBuildId: 'test-relay-build'
}))
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
expect(session.getState()).toBe('ready')
expect(pauseAdapterMock).not.toHaveBeenCalled()
expect(openConsumerSessionMock.mock.calls[0][1]).toHaveProperty('outputFlowControl')
expect(installSshPtySourceAckPublisher).not.toHaveBeenCalled()
})
it('publishes negotiated ACK batches through mux settlement', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
const publish = vi.mocked(installSshPtySourceAckPublisher).mock.calls[0]?.[1]
const settled = vi.fn()
const batch = {
acknowledgements: [
{
id: 'pty-1',
clientGeneration: 1,
ownerGeneration: 1,
deliveryToken: 'token-1',
creditedEndSu: 4
}
]
}
publish?.(batch, settled)
expect(openConsumerSessionMock.mock.calls[0][1]).toMatchObject({
outputFlowControl: { requestedWindowSu: 256 * 1024 }
})
expect(deployAndLaunchRelay).toHaveBeenCalledWith(mockConn, undefined, undefined, 'target-1')
expect(notifyWithSettlementMock).toHaveBeenCalledWith('pty.ackData', batch, settled)
})
it('offers V1 through reconnect negotiation', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
await session.reconnect(mockConn)
expect(openConsumerSessionMock.mock.calls[0][1]).toHaveProperty('outputFlowControl')
expect(openConsumerSessionMock.mock.calls[1][1]).toHaveProperty('outputFlowControl')
expect(deployAndLaunchRelay).toHaveBeenNthCalledWith(
1,
mockConn,
undefined,
undefined,
'target-1'
)
expect(deployAndLaunchRelay).toHaveBeenNthCalledWith(
2,
mockConn,
undefined,
undefined,
'target-1'
)
})
it('reattaches V1 from an exact checkpoint and quarantines live data until recoveryComplete', async () => {
let generation = 0
openConsumerSessionMock.mockImplementation(async (_mux, options) => {
generation++
return {
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: generation,
ownerGeneration: generation,
ownerLease: `owner-lease-${generation}`,
outputFlowControl: { version: 1, windowSu: 256 * 1024 }
}
})
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([
{
id: 'ssh:target-1@@pty-1',
providerGeneration: 23,
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
}
])
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.mocked(getPtyIdsForConnection).mockReturnValue(['ssh:target-1@@pty-1'])
vi.mocked(getSshPtyProvider).mockImplementation(
() => vi.mocked(registerSshPtyProvider).mock.calls.at(-1)?.[1]
)
let transferDisposedMux = false
const publishHeldRecovery = (sink: (payload: unknown) => void): void => {
for (const [data, sourceStartSu, sourceEndSu] of [
['re', 4, 6],
['co', 6, 8],
['live', 8, 12]
] as const) {
sink({
id: 'ssh:target-1@@pty-1',
data,
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: sourceEndSu - sourceStartSu,
source: {
relayPtyId: 'pty-1',
spanId: `new-token:${sourceStartSu}:${sourceEndSu}`,
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu,
sourceEndSu
}
})
}
}
const recoveryActivationLease = {
commit: vi.fn(),
retire: vi.fn()
}
const sourceActivationLease = {
commit: vi.fn(),
rollback: vi.fn(async () => true),
transferToRecovery: vi.fn((sink: (payload: unknown) => void) => {
publishHeldRecovery(sink)
return recoveryActivationLease
})
}
attachForReconnectMock.mockImplementation(async () => {
const canceled = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.deliveryCanceled'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
const disposeCount = muxDisposeMock.mock.calls.length
canceled?.({
id: 'pty-1',
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
replacementDeliveryToken: 'new-token'
})
transferDisposedMux = muxDisposeMock.mock.calls.length !== disposeCount
queueMicrotask(() => {
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
})
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceActivationLease
}
})
await session.reconnect(mockConn)
expect(attachForReconnectMock).toHaveBeenCalledWith(
'pty-1',
undefined,
expect.objectContaining({
status: 'checkpoint',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
})
)
expect(acceptOutputDataMock.mock.calls.map(([payload]) => payload.data)).toEqual([
're',
'co',
'live'
])
expect(transferDisposedMux).toBe(false)
expect(sourceActivationLease.transferToRecovery).toHaveBeenCalledOnce()
expect(sourceActivationLease.commit).not.toHaveBeenCalled()
expect(sourceActivationLease.rollback).not.toHaveBeenCalled()
expect(recoveryActivationLease.commit).toHaveBeenCalledOnce()
expect(recoveryActivationLease.retire).not.toHaveBeenCalled()
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:replay', expect.anything())
const closeCount = vi.mocked(closeSshPtyOutputGeneration).mock.calls.length
const canceled = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.deliveryCanceled'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
canceled?.({
id: 'pty-1',
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token'
})
expect(closeSshPtyOutputGeneration).toHaveBeenCalledTimes(closeCount)
})
it.each([
['gap', [5, 8] as const],
['overlap', [3, 8] as const],
['incomplete suffix', [4, 6] as const],
['missing body', undefined]
])('rejects %s recovery without destroying the physical PTY or lease', async (label, frame) => {
const targetId = `invalid-recovery-${label.replace(' ', '-')}`
const { mockStore, mockWindow } = await runRecoverySequence({
targetId,
recoveryEndSu: 8,
...(frame ? { recoveryFrame: frame } : {})
})
expect(acceptOutputDataMock).not.toHaveBeenCalled()
expect(muxRequestMock).toHaveBeenCalledWith('pty.cancelDelivery', {
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token'
})
expect(applySshPtySourceRecoveryCancellationProof).toHaveBeenCalledWith(
{
id: `ssh:${targetId}@@pty-1`,
code: -1,
providerGeneration: 23,
ptyIncarnation: 'incarnation-1'
},
{ sentEndSu: 8, creditedEndSu: 4 }
)
expect(mockStore.markSshRemotePtyLease).toHaveBeenCalledWith(targetId, 'pty-1', 'detached')
expect(mockStore.markSshRemotePtyLease).not.toHaveBeenCalledWith(targetId, 'pty-1', 'expired')
expect(mockStore.markSshRemotePtyLeases).not.toHaveBeenCalled()
expect(clearProviderPtyState).not.toHaveBeenCalled()
expect(clearPtyOwnershipForConnection).not.toHaveBeenCalled()
expect(deletePtyOwnership).not.toHaveBeenCalled()
expect(setPtyOwnership).not.toHaveBeenCalled()
expect(muxDisposeMock).not.toHaveBeenCalledWith('shutdown')
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:exit', expect.anything())
})
it('accepts empty recovery only when the checkpoint equals the recovery end', async () => {
const { mockStore } = await runRecoverySequence({
targetId: 'empty-recovery',
recoveryEndSu: 4,
liveFrame: [4, 8]
})
expect(acceptOutputDataMock.mock.calls.map(([payload]) => payload.data)).toEqual(['live'])
expect(mockStore.markSshRemotePtyLease).toHaveBeenCalledWith(
'empty-recovery',
'pty-1',
'attached'
)
})
})
@@ -2,15 +2,43 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SshRelaySession } from './ssh-relay-session'
import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures'
const { muxRequestMock } = vi.hoisted(() => ({ muxRequestMock: vi.fn() }))
const { acceptOutputExitMock, muxRequestMock } = vi.hoisted(() => ({
acceptOutputExitMock: vi.fn().mockResolvedValue(undefined),
muxRequestMock: vi.fn()
}))
vi.mock('./ssh-relay-deploy', () => ({ deployAndLaunchRelay: vi.fn() }))
vi.mock('./ssh-pty-consumer-session', () => ({
openSshPtyConsumerSession: vi.fn(async (_mux, options) => ({
clientInstanceId: options.clientInstanceId,
clientGeneration: 1,
ownerGeneration: 1,
ownerLease: 'test-owner-lease'
}))
}))
vi.mock('../ipc/ssh-pty-output-intake-registry', () => ({
acceptSshPtyOutputData: vi.fn().mockResolvedValue(undefined),
acceptSshPtyOutputExit: acceptOutputExitMock,
allocateSshPtyProviderGeneration: vi.fn(() => 31),
beginSshPtyOutputGenerationMigration: vi.fn(() => ({
byPty: new Map(),
completion: Promise.resolve()
})),
closeSshPtyOutputGeneration: vi.fn(),
getSshPtyAcceptedSourceCheckpoints: vi.fn(() => []),
applySshPtySourceCancellationProof: vi.fn(() => true),
applySshPtySourceRecoveryCancellationProof: vi.fn(() => true),
installSshPtySourceAckPublisher: vi.fn(() => () => {}),
installSshPtySourceCancellationPublisher: vi.fn(() => () => {})
}))
vi.mock('./ssh-relay-deploy-helpers', () => ({ execCommand: vi.fn().mockResolvedValue('') }))
vi.mock('./ssh-channel-multiplexer', () => ({
SshChannelMultiplexer: class MockSshChannelMultiplexer {
notify = vi.fn()
notifyWithSettlement = vi.fn()
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn().mockReturnValue(() => {})
onDispose = vi.fn().mockReturnValue(() => {})
dispose = vi.fn()
@@ -90,22 +118,41 @@ describe('SSH relay PTY incarnation exits', () => {
id: string
code: number
incarnationId: string
providerGeneration: number
ptyIncarnation: string
}) => void
vi.mocked(isCurrentPtyExit).mockReturnValueOnce(false)
onExit({ id: 'ssh:target-1@@pty-reused', code: 0, incarnationId: 'old-incarnation' })
onExit({
id: 'ssh:target-1@@pty-reused',
code: 0,
incarnationId: 'old-incarnation',
providerGeneration: 31,
ptyIncarnation: 'old-incarnation'
})
expect(clearProviderPtyState).not.toHaveBeenCalled()
expect(deletePtyOwnership).not.toHaveBeenCalled()
expect(mockStore.markSshRemotePtyLease).not.toHaveBeenCalled()
expect(acceptOutputExitMock).not.toHaveBeenCalled()
expect(runtime.onPtyExit).not.toHaveBeenCalled()
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:exit', expect.anything())
onExit({ id: 'ssh:target-1@@pty-reused', code: 7, incarnationId: 'current-incarnation' })
expect(runtime.onPtyExit).toHaveBeenCalledWith(
'ssh:target-1@@pty-reused',
7,
'current-incarnation'
onExit({
id: 'ssh:target-1@@pty-reused',
code: 7,
incarnationId: 'current-incarnation',
providerGeneration: 31,
ptyIncarnation: 'current-incarnation'
})
await vi.waitFor(() =>
expect(acceptOutputExitMock).toHaveBeenCalledWith({
id: 'ssh:target-1@@pty-reused',
code: 7,
providerGeneration: 31,
ptyIncarnation: 'current-incarnation'
})
)
expect(runtime.onPtyExit).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,263 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SshRelaySession } from './ssh-relay-session'
import {
createMismatchedOwnerRecoveryError,
createMockDeps,
mockDeploySuccess
} from './ssh-relay-session-test-fixtures'
type SettledMigration = {
status: 'settled'
checkpoint: {
id: string
providerGeneration: number
clientGeneration: number
ownerGeneration: number
ptyIncarnation: string
deliveryToken: string
acceptedSourceEndSu: number
}
}
const { attachForReconnectMock, beginMigrationMock, muxRequestMock, openConsumerSessionMock } =
vi.hoisted(() => ({
attachForReconnectMock: vi.fn().mockResolvedValue({}),
beginMigrationMock: vi.fn(() => ({
byPty: new Map(),
completion: Promise.resolve()
})),
muxRequestMock: vi.fn(),
openConsumerSessionMock: vi.fn()
}))
vi.mock('./ssh-relay-deploy', () => ({ deployAndLaunchRelay: vi.fn() }))
vi.mock('./ssh-pty-consumer-session', () => ({
openSshPtyConsumerSession: openConsumerSessionMock
}))
vi.mock('../ipc/ssh-pty-output-intake-registry', () => ({
acceptSshPtyOutputData: vi.fn().mockResolvedValue(undefined),
acceptSshPtyOutputExit: vi.fn().mockResolvedValue(undefined),
allocateSshPtyProviderGeneration: vi.fn(() => 23),
beginSshPtyOutputGenerationMigration: beginMigrationMock,
closeSshPtyOutputGeneration: vi.fn(),
getSshPtyAcceptedSourceCheckpoints: vi.fn(() => []),
installSshPtySourceAckPublisher: vi.fn(() => () => {}),
installSshPtySourceCancellationPublisher: vi.fn(() => () => {}),
applySshPtySourceCancellationProof: vi.fn(),
applySshPtySourceRecoveryCancellationProof: vi.fn()
}))
vi.mock('./ssh-channel-multiplexer', () => ({
SshChannelMultiplexer: class MockSshChannelMultiplexer {
notify = vi.fn()
notifyWithSettlement = vi.fn()
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn().mockReturnValue(() => {})
onDispose = vi.fn().mockReturnValue(() => {})
dispose = vi.fn()
isDisposed = vi.fn().mockReturnValue(false)
}
}))
vi.mock('../providers/ssh-pty-provider', () => ({
SshPtyProvider: class MockSshPtyProvider {
onData = vi.fn().mockReturnValue(() => {})
onReplay = vi.fn().mockReturnValue(() => {})
onExit = vi.fn().mockReturnValue(() => {})
attach = vi.fn().mockResolvedValue(undefined)
attachForReconnect = attachForReconnectMock
setPtyDeliveryPauseAdapter = vi.fn()
dispose = vi.fn()
}
}))
vi.mock('../providers/ssh-filesystem-provider', () => ({
SshFilesystemProvider: class MockSshFilesystemProvider {
dispose = vi.fn()
}
}))
vi.mock('../providers/ssh-git-provider', () => ({
SshGitProvider: class MockSshGitProvider {}
}))
vi.mock('../ipc/pty', () => ({
registerSshPtyProvider: vi.fn(),
unregisterSshPtyProvider: vi.fn(),
getSshPtyProvider: vi.fn().mockReturnValue({ dispose: vi.fn() }),
getPtyIdsForConnection: vi.fn().mockReturnValue([]),
clearPtyOwnershipForConnection: vi.fn(),
clearProviderPtyState: vi.fn(),
deletePtyOwnership: vi.fn(),
restorePtyIncarnation: vi.fn(),
setPtyOwnership: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
registerSshFilesystemProvider: vi.fn(),
unregisterSshFilesystemProvider: vi.fn(),
getSshFilesystemProvider: vi.fn().mockReturnValue({ dispose: vi.fn() })
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
registerSshGitProvider: vi.fn(),
unregisterSshGitProvider: vi.fn()
}))
const { getPtyIdsForConnection, getSshPtyProvider, registerSshPtyProvider } =
await import('../ipc/pty')
const { getSshPtyAcceptedSourceCheckpoints } = await import('../ipc/ssh-pty-output-intake-registry')
function pendingMigration() {
let resolve!: (result: SettledMigration) => void
const result = new Promise<SettledMigration>((promiseResolve) => {
resolve = promiseResolve
})
return { result, resolve }
}
function settledMigration(appPtyId: string, acceptedSourceEndSu: number): SettledMigration {
return {
status: 'settled',
checkpoint: {
id: appPtyId,
providerGeneration: 23,
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu
}
}
}
describe('SshRelaySession model migration', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([])
openConsumerSessionMock.mockImplementation(async (_mux, options) => ({
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: 1,
ownerGeneration: 1,
ownerLease: 'owner-lease-1',
...(options.outputFlowControl
? {
outputFlowControl: { version: 1, windowSu: options.outputFlowControl.requestedWindowSu }
}
: {})
}))
muxRequestMock.mockResolvedValue([])
mockDeploySuccess()
})
it('keeps overlapping reconnects behind the old-generation model migration', async () => {
const targetId = 'migration-fence'
const appPtyId = `ssh:${targetId}@@pty-1`
const migration = pendingMigration()
beginMigrationMock.mockReturnValueOnce({
byPty: new Map([[appPtyId, migration.result]]),
completion: migration.result.then(() => {})
})
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([
{
id: appPtyId,
providerGeneration: 23,
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
}
])
const deps = createMockDeps()
const session = new SshRelaySession(
targetId,
deps.getMainWindow,
deps.mockStore,
deps.mockPortForward
)
await session.establish(deps.mockConn)
vi.mocked(getPtyIdsForConnection).mockReturnValue([appPtyId])
vi.mocked(getSshPtyProvider).mockImplementation(
() => vi.mocked(registerSshPtyProvider).mock.calls.at(-1)?.[1]
)
attachForReconnectMock.mockResolvedValue({
incarnationId: 'incarnation-1',
sourceRecovery: { status: 'restoreRequired', reason: 'relayRestoreRequired' }
})
const firstReconnect = session.reconnect(deps.mockConn)
await vi.waitFor(() => expect(registerSshPtyProvider).toHaveBeenCalledTimes(2))
const secondReconnect = session.reconnect(deps.mockConn)
await vi.waitFor(() => expect(beginMigrationMock).toHaveBeenCalledTimes(2))
expect(attachForReconnectMock).not.toHaveBeenCalled()
migration.resolve(settledMigration(appPtyId, 8))
await Promise.all([firstReconnect, secondReconnect])
expect(attachForReconnectMock).toHaveBeenCalledWith(
'pty-1',
undefined,
Object.freeze({
status: 'checkpoint',
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu: 8
})
)
})
it('waits for a stale-owner migration before requesting restore', async () => {
const targetId = 'migration-stale-owner'
const appPtyId = `ssh:${targetId}@@pty-1`
const migration = pendingMigration()
beginMigrationMock.mockReturnValueOnce({
byPty: new Map([[appPtyId, migration.result]]),
completion: migration.result.then(() => {})
})
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([
settledMigration(appPtyId, 4).checkpoint
])
const deps = createMockDeps()
const session = new SshRelaySession(
targetId,
deps.getMainWindow,
deps.mockStore,
deps.mockPortForward
)
await session.establish(deps.mockConn)
vi.mocked(getPtyIdsForConnection).mockReturnValue([appPtyId])
vi.mocked(getSshPtyProvider).mockImplementation(
() => vi.mocked(registerSshPtyProvider).mock.calls.at(-1)?.[1]
)
openConsumerSessionMock
.mockRejectedValueOnce(createMismatchedOwnerRecoveryError())
.mockImplementationOnce(async (_mux, options) => ({
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: 2,
ownerGeneration: 2,
ownerLease: 'fresh-owner-lease',
outputFlowControl: { version: 1, windowSu: 256 * 1024 }
}))
attachForReconnectMock.mockResolvedValue({
incarnationId: 'incarnation-1',
sourceRecovery: { status: 'restoreRequired', reason: 'checkpointUnavailable' }
})
const reconnect = session.reconnect(deps.mockConn)
await vi.waitFor(() => expect(openConsumerSessionMock).toHaveBeenCalledTimes(3))
expect(attachForReconnectMock).not.toHaveBeenCalled()
migration.resolve(settledMigration(appPtyId, 8))
await reconnect
expect(attachForReconnectMock).toHaveBeenCalledWith(
'pty-1',
undefined,
Object.freeze({ status: 'checkpointUnavailable' })
)
})
})
@@ -8,13 +8,43 @@ type MockMuxInstance = {
requestHandlers: Map<string, (params: Record<string, unknown>) => Promise<unknown>>
}
const { muxRequestMock, muxInstancesRaw } = vi.hoisted(() => ({
muxRequestMock: vi.fn(),
muxInstancesRaw: [] as unknown[]
}))
const { acceptOutputExitMock, muxRequestMock, openConsumerSessionMock, muxInstancesRaw } =
vi.hoisted(() => ({
acceptOutputExitMock: vi.fn().mockResolvedValue(undefined),
muxRequestMock: vi.fn(),
openConsumerSessionMock: vi.fn(
async (
_mux: unknown,
options: { clientInstanceId: string; outputFlowControl?: unknown }
) => ({
clientInstanceId: options.clientInstanceId,
clientGeneration: 1,
ownerGeneration: 1,
ownerLease: 'test-owner-lease'
})
),
muxInstancesRaw: [] as unknown[]
}))
const muxInstances = muxInstancesRaw as MockMuxInstance[]
vi.mock('./ssh-relay-deploy', () => ({ deployAndLaunchRelay: vi.fn() }))
vi.mock('./ssh-pty-consumer-session', () => ({
openSshPtyConsumerSession: openConsumerSessionMock
}))
vi.mock('../ipc/ssh-pty-output-intake-registry', () => ({
acceptSshPtyOutputData: vi.fn().mockResolvedValue(undefined),
acceptSshPtyOutputExit: acceptOutputExitMock,
allocateSshPtyProviderGeneration: vi.fn(() => 17),
beginSshPtyOutputGenerationMigration: vi.fn(() => ({
byPty: new Map(),
completion: Promise.resolve()
})),
closeSshPtyOutputGeneration: vi.fn(),
getSshPtyAcceptedSourceCheckpoints: vi.fn(() => []),
applySshPtySourceRecoveryCancellationProof: vi.fn(() => true),
installSshPtySourceAckPublisher: vi.fn(() => () => {}),
installSshPtySourceCancellationPublisher: vi.fn(() => () => {})
}))
vi.mock('./ssh-relay-deploy-helpers', () => ({ execCommand: vi.fn().mockResolvedValue('') }))
vi.mock('node:crypto', async (importOriginal) => {
const actual = await importOriginal<typeof NodeCrypto>()
@@ -27,8 +57,10 @@ vi.mock('./ssh-channel-multiplexer', () => ({
SshChannelMultiplexer: class MockSshChannelMultiplexer {
requestHandlers = new Map<string, (params: Record<string, unknown>) => Promise<unknown>>()
notify = vi.fn()
notifyWithSettlement = vi.fn()
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn(
(method: string, handler: (params: Record<string, unknown>) => Promise<unknown>) => {
this.requestHandlers.set(method, handler)
@@ -97,6 +129,7 @@ const {
setPtyOwnership,
restorePtyIncarnation
} = await import('../ipc/pty')
const { deployAndLaunchRelay } = await import('./ssh-relay-deploy')
const APP_PTY_ID = 'ssh:target-1@@pty-live'
const INCARNATION_LEAF_ID = '11111111-1111-4111-8111-111111111111'
@@ -112,14 +145,26 @@ function detachedLease() {
}
}
function emitExitDuringAttach(payload: { id: string; code: number; incarnationId?: string }): void {
function emitExitDuringAttach(payload: {
id: string
code: number
incarnationId?: string
providerGeneration?: number
ptyIncarnation?: string
}): void {
const registeredProvider = vi.mocked(registerSshPtyProvider).mock.calls[0]?.[1] as unknown as {
onExit: ReturnType<typeof vi.fn>
}
const exitHandler = registeredProvider.onExit.mock.calls[0]?.[0] as
| ((exit: typeof payload) => void)
| undefined
queueMicrotask(() => exitHandler?.(payload))
queueMicrotask(() =>
exitHandler?.({
providerGeneration: 17,
ptyIncarnation: payload.incarnationId ?? `legacy:${payload.id}`,
...payload
})
)
}
describe('SshRelaySession reconnect incarnation ordering', () => {
@@ -135,7 +180,152 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
})
it('bounds fifty reattaches to eight workers without slow or failed sibling head-of-line delay', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.clearAllMocks()
mockDeploySuccess()
const ptyIds = Array.from({ length: 50 }, (_, index) => `pty-${index}`)
let active = 0
let peakActive = 0
const attempts = new Map<string, number>()
const mockAttach = vi.fn((id: string) => {
attempts.set(id, (attempts.get(id) ?? 0) + 1)
if (id === 'pty-0') {
return new Promise<void>(() => {})
}
if (id === 'pty-1') {
return Promise.reject(new Error('isolated attach failure'))
}
active++
peakActive = Math.max(peakActive, active)
return new Promise<void>((resolve) => {
setTimeout(() => {
active--
resolve()
}, 100)
})
})
vi.mocked(getSshPtyProvider).mockReturnValue({
attachForReconnect: mockAttach,
dispose: vi.fn()
} as unknown as ReturnType<typeof getSshPtyProvider>)
vi.mocked(getPtyIdsForConnection).mockReturnValue(ptyIds)
const random = vi.spyOn(Math, 'random').mockReturnValue(0)
vi.useFakeTimers()
try {
const reconnect = session.reconnect(mockConn)
await vi.advanceTimersByTimeAsync(750)
expect(
vi
.mocked(mockStore.markSshRemotePtyLease)
.mock.calls.filter(([, , state]) => state === 'attached')
.map(([, id]) => id)
).toHaveLength(48)
expect(peakActive).toBeLessThanOrEqual(8)
await vi.advanceTimersByTimeAsync(20_000)
await reconnect
expect(mockAttach).toHaveBeenCalledTimes(52)
expect(attempts.get('pty-0')).toBe(2)
expect(attempts.get('pty-1')).toBe(2)
expect(session.getState()).toBe('ready')
expect(mockStore.markSshRemotePtyLease).not.toHaveBeenCalledWith(
'target-1',
expect.any(String),
'expired'
)
} finally {
vi.useRealTimers()
random.mockRestore()
}
})
it('offers source credit through reconnect', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
await session.reconnect(mockConn)
expect(deployAndLaunchRelay).toHaveBeenNthCalledWith(
1,
mockConn,
undefined,
undefined,
'target-1'
)
expect(deployAndLaunchRelay).toHaveBeenNthCalledWith(
2,
mockConn,
undefined,
undefined,
'target-1'
)
expect(openConsumerSessionMock).toHaveBeenCalledTimes(2)
for (const [, options] of openConsumerSessionMock.mock.calls) {
expect(options.outputFlowControl).toBeDefined()
}
})
it('rolls back a timed-out activation that resolves after its replacement commits', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
vi.clearAllMocks()
mockDeploySuccess()
const timedOutLease = { commit: vi.fn(), rollback: vi.fn() }
const replacementLease = { commit: vi.fn(), rollback: vi.fn() }
let resolveTimedOut!: (result: {
incarnationId: string
sourceActivationLease: typeof timedOutLease
}) => void
const mockAttach = vi
.fn()
.mockReturnValueOnce(
new Promise((resolve) => {
resolveTimedOut = resolve
})
)
.mockResolvedValueOnce({
incarnationId: 'incarnation-replacement',
sourceActivationLease: replacementLease
})
vi.mocked(getSshPtyProvider).mockReturnValue({
attachForReconnect: mockAttach,
dispose: vi.fn()
} as unknown as ReturnType<typeof getSshPtyProvider>)
vi.mocked(getPtyIdsForConnection).mockReturnValue(['pty-1'])
const random = vi.spyOn(Math, 'random').mockReturnValue(0)
vi.useFakeTimers()
try {
const reconnect = session.reconnect(mockConn)
await vi.advanceTimersByTimeAsync(11_000)
await reconnect
resolveTimedOut({
incarnationId: 'incarnation-timed-out',
sourceActivationLease: timedOutLease
})
await Promise.resolve()
expect(replacementLease.commit).toHaveBeenCalledOnce()
expect(replacementLease.rollback).not.toHaveBeenCalled()
expect(timedOutLease.rollback).toHaveBeenCalledOnce()
expect(timedOutLease.commit).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
random.mockRestore()
}
})
it('keeps the winning reconnect incarnation when a stale health check resolves last', async () => {
const consumerInstanceId = '00000000-0000-4000-8000-000000000000'
const initialIncarnation = '00000000-0000-4000-8000-000000000001'
const winningIncarnation = '00000000-0000-4000-8000-000000000002'
const staleIncarnation = '00000000-0000-4000-8000-000000000003'
@@ -152,6 +342,7 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
return resolveHomeCalls === 2 ? staleHealthCheck : Promise.resolve('/')
})
vi.mocked(randomUUID)
.mockReturnValueOnce(consumerInstanceId)
.mockReturnValueOnce(initialIncarnation)
.mockReturnValueOnce(winningIncarnation)
.mockReturnValue(staleIncarnation)
@@ -190,7 +381,7 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
'target-1',
winningIncarnation
)
expect(randomUUID).toHaveBeenCalledTimes(2)
expect(randomUUID).toHaveBeenCalledTimes(3)
})
it('restores and persists exact incarnation proof from reconnect attach', async () => {
@@ -242,11 +433,12 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
onPtySpawned: vi.fn(),
registerPty: vi.fn()
}
const sourceActivationLease = { commit: vi.fn(), rollback: vi.fn() }
vi.mocked(getSshPtyProvider).mockReturnValue({
attachForReconnect: vi.fn().mockImplementation(async () => {
emitExitDuringAttach({ id: APP_PTY_ID, code: 0, incarnationId })
emitExitDuringAttach({ id: APP_PTY_ID, code: 0, incarnationId: 'incarnation-stale' })
return { incarnationId, replay: 'dead-output' }
return { incarnationId, replay: 'dead-output', sourceActivationLease }
}),
dispose: vi.fn()
} as unknown as ReturnType<typeof getSshPtyProvider>)
@@ -263,12 +455,20 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
await session.establish(mockConn)
expect(runtime.onPtyExit).toHaveBeenCalledWith(APP_PTY_ID, 0, incarnationId)
expect(acceptOutputExitMock).toHaveBeenCalledWith({
id: APP_PTY_ID,
code: 0,
providerGeneration: 17,
ptyIncarnation: incarnationId
})
expect(runtime.onPtyExit).not.toHaveBeenCalled()
expect(runtime.acceptPtyIncarnationForExit).toHaveBeenCalledWith(APP_PTY_ID, incarnationId)
expect(runtime.registerPty).not.toHaveBeenCalled()
expect(restorePtyIncarnation).toHaveBeenCalledWith(APP_PTY_ID, incarnationId)
expect(setPtyOwnership).not.toHaveBeenCalled()
expect(mockStore.persistPtyBinding).not.toHaveBeenCalled()
expect(sourceActivationLease.rollback).toHaveBeenCalledOnce()
expect(sourceActivationLease.commit).not.toHaveBeenCalled()
expect(mockStore.markSshRemotePtyLease).toHaveBeenCalledWith(
'target-1',
'pty-live',
@@ -290,6 +490,7 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
onPtySpawned: vi.fn(),
registerPty: vi.fn()
}
const sourceActivationLease = { commit: vi.fn(), rollback: vi.fn() }
vi.mocked(getSshPtyProvider).mockReturnValue({
attachForReconnect: vi.fn().mockImplementation(async () => {
emitExitDuringAttach({
@@ -297,7 +498,7 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
code: 0,
incarnationId: 'incarnation-old'
})
return { incarnationId: currentIncarnationId, replay: 'live-output' }
return { incarnationId: currentIncarnationId, replay: 'live-output', sourceActivationLease }
}),
dispose: vi.fn()
} as unknown as ReturnType<typeof getSshPtyProvider>)
@@ -316,6 +517,8 @@ describe('SshRelaySession reconnect incarnation ordering', () => {
expect(runtime.onPtyExit).not.toHaveBeenCalled()
expect(runtime.acceptPtyIncarnationForExit).not.toHaveBeenCalled()
expect(sourceActivationLease.commit).toHaveBeenCalledOnce()
expect(sourceActivationLease.rollback).not.toHaveBeenCalled()
expect(runtime.registerPty).toHaveBeenCalledWith(APP_PTY_ID, 'worktree-1', 'target-1', {
tabId: 'tab-1',
leafId: INCARNATION_LEAF_ID,
@@ -0,0 +1,791 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { SshRelaySession } from './ssh-relay-session'
import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures'
const {
acceptOutputDataMock,
acceptOutputExitMock,
muxRequestMock,
onNotificationByMethodMock,
openConsumerSessionMock,
muxDisposeMock,
ptyProviderDisposeMock,
sourceAckCleanupMock,
sourceCancellationCleanupMock,
attachForReconnectMock,
ptyDataHandlerRef,
ptyExitHandlerRef
} = vi.hoisted(() => ({
acceptOutputDataMock: vi.fn().mockResolvedValue(undefined),
acceptOutputExitMock: vi.fn().mockResolvedValue(undefined),
muxRequestMock: vi.fn(),
onNotificationByMethodMock: vi.fn(),
openConsumerSessionMock: vi.fn(),
muxDisposeMock: vi.fn(),
ptyProviderDisposeMock: vi.fn(),
sourceAckCleanupMock: vi.fn(),
sourceCancellationCleanupMock: vi.fn(),
attachForReconnectMock: vi.fn().mockResolvedValue({}),
ptyDataHandlerRef: { current: undefined as undefined | ((payload: unknown) => void) },
ptyExitHandlerRef: { current: undefined as undefined | ((payload: unknown) => void) }
}))
vi.mock('./ssh-relay-deploy', () => ({ deployAndLaunchRelay: vi.fn() }))
vi.mock('./ssh-pty-consumer-session', () => ({
openSshPtyConsumerSession: openConsumerSessionMock
}))
vi.mock('../ipc/ssh-pty-output-intake-registry', () => ({
acceptSshPtyOutputData: acceptOutputDataMock,
acceptSshPtyOutputExit: acceptOutputExitMock,
allocateSshPtyProviderGeneration: vi.fn(() => 23),
beginSshPtyOutputGenerationMigration: vi.fn(() => ({
byPty: new Map(),
completion: Promise.resolve()
})),
closeSshPtyOutputGeneration: vi.fn(),
getSshPtyAcceptedSourceCheckpoints: vi.fn(() => []),
installSshPtySourceAckPublisher: vi.fn(() => sourceAckCleanupMock),
installSshPtySourceCancellationPublisher: vi.fn(() => sourceCancellationCleanupMock),
applySshPtySourceCancellationProof: vi.fn(() => true),
applySshPtySourceRecoveryCancellationProof: vi.fn(() => true)
}))
vi.mock('./ssh-channel-multiplexer', () => ({
SshChannelMultiplexer: class MockSshChannelMultiplexer {
notify = vi.fn()
notifyWithSettlement = vi.fn()
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = onNotificationByMethodMock.mockImplementation(() => () => {})
onRequest = vi.fn().mockReturnValue(() => {})
onDispose = vi.fn().mockReturnValue(() => {})
dispose = muxDisposeMock
isDisposed = vi.fn().mockReturnValue(false)
}
}))
vi.mock('../providers/ssh-pty-provider', () => ({
isSshPtyNotFoundError: vi.fn().mockReturnValue(false),
isSshPtyIdentityMismatchError: vi.fn().mockReturnValue(false),
SshPtyProvider: class MockSshPtyProvider {
onData = vi.fn().mockImplementation((handler) => {
ptyDataHandlerRef.current = handler
return () => {}
})
onReplay = vi.fn().mockReturnValue(() => {})
onExit = vi.fn().mockImplementation((handler) => {
ptyExitHandlerRef.current = handler
return () => {}
})
attachForReconnect = attachForReconnectMock
setPtyDeliveryPauseAdapter = vi.fn()
dispose = ptyProviderDisposeMock
}
}))
vi.mock('../providers/ssh-filesystem-provider', () => ({
SshFilesystemProvider: class MockSshFilesystemProvider {
dispose = vi.fn()
}
}))
vi.mock('../providers/ssh-git-provider', () => ({
SshGitProvider: class MockSshGitProvider {}
}))
vi.mock('../ipc/pty', () => ({
registerSshPtyProvider: vi.fn(),
unregisterSshPtyProvider: vi.fn(),
getSshPtyProvider: vi.fn().mockReturnValue({ dispose: vi.fn() }),
getPtyIdsForConnection: vi.fn().mockReturnValue([]),
isCurrentPtyExit: vi.fn(() => true),
clearPtyOwnershipForConnection: vi.fn(),
clearProviderPtyState: vi.fn(),
deletePtyOwnership: vi.fn(),
restorePtyIncarnation: vi.fn(),
setPtyOwnership: vi.fn()
}))
vi.mock('../providers/ssh-filesystem-dispatch', () => ({
registerSshFilesystemProvider: vi.fn(),
unregisterSshFilesystemProvider: vi.fn(),
getSshFilesystemProvider: vi.fn().mockReturnValue({ dispose: vi.fn() })
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
registerSshGitProvider: vi.fn(),
unregisterSshGitProvider: vi.fn()
}))
const {
clearProviderPtyState,
clearPtyOwnershipForConnection,
deletePtyOwnership,
getSshPtyProvider,
getPtyIdsForConnection,
registerSshPtyProvider,
setPtyOwnership,
unregisterSshPtyProvider
} = await import('../ipc/pty')
const { closeSshPtyOutputGeneration, getSshPtyAcceptedSourceCheckpoints } =
await import('../ipc/ssh-pty-output-intake-registry')
const { applySshPtySourceCancellationProof } = await import('../ipc/ssh-pty-output-intake-registry')
const { applySshPtySourceRecoveryCancellationProof } =
await import('../ipc/ssh-pty-output-intake-registry')
describe('SshRelaySession recovery race fencing', () => {
beforeEach(() => {
vi.clearAllMocks()
ptyDataHandlerRef.current = undefined
ptyExitHandlerRef.current = undefined
attachForReconnectMock.mockResolvedValue({})
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([])
vi.mocked(applySshPtySourceCancellationProof).mockReturnValue(true)
vi.mocked(applySshPtySourceRecoveryCancellationProof).mockReturnValue(true)
muxRequestMock.mockResolvedValue([])
mockDeploySuccess()
})
function emitSourceFrame(args: {
targetId: string
token: string
clientGeneration: number
ownerGeneration: number
sourceStartSu: number
sourceEndSu: number
}): void {
ptyDataHandlerRef.current?.({
id: `ssh:${args.targetId}@@pty-1`,
data: 'late',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: args.sourceEndSu - args.sourceStartSu,
source: {
relayPtyId: 'pty-1',
spanId: `${args.token}:${args.sourceStartSu}:${args.sourceEndSu}`,
clientGeneration: args.clientGeneration,
ownerGeneration: args.ownerGeneration,
deliveryToken: args.token,
sourceStartSu: args.sourceStartSu,
sourceEndSu: args.sourceEndSu
}
})
}
async function prepareRecovery(targetId: string): Promise<{
session: SshRelaySession
deps: ReturnType<typeof createMockDeps>
}> {
let generation = 0
openConsumerSessionMock.mockImplementation(async (_mux, options) => ({
mode: 'negotiated',
clientInstanceId: options.clientInstanceId,
clientGeneration: ++generation,
ownerGeneration: generation,
ownerLease: `owner-lease-${generation}`,
outputFlowControl: { version: 1, windowSu: 256 * 1024 }
}))
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([
{
id: `ssh:${targetId}@@pty-1`,
providerGeneration: 23,
clientGeneration: 1,
ownerGeneration: 1,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
}
])
const deps = createMockDeps()
const session = new SshRelaySession(
targetId,
deps.getMainWindow,
deps.mockStore,
deps.mockPortForward
)
await session.establish(deps.mockConn)
vi.mocked(getPtyIdsForConnection).mockReturnValue([`ssh:${targetId}@@pty-1`])
vi.mocked(getSshPtyProvider).mockImplementation(
() => vi.mocked(registerSshPtyProvider).mock.calls.at(-1)?.[1]
)
return { session, deps }
}
it('publishes held recovery data before an exact exit without waiting for completion', async () => {
const targetId = 'exit-with-complete-private-body'
const { session, deps } = await prepareRecovery(targetId)
const recoveryActivationLease = { commit: vi.fn(), retire: vi.fn() }
const sourceActivationLease = {
commit: vi.fn(),
rollback: vi.fn(async () => true),
transferToRecovery: vi.fn((sink: (payload: unknown) => void) => {
sink({
id: `ssh:${targetId}@@pty-1`,
data: 'held',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: 4,
source: {
relayPtyId: 'pty-1',
spanId: 'new-token:4:8',
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu: 4,
sourceEndSu: 8
}
})
return recoveryActivationLease
})
}
attachForReconnectMock.mockImplementation(async () => {
ptyExitHandlerRef.current?.({
id: `ssh:${targetId}@@pty-1`,
code: 0,
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
incarnationId: 'incarnation-1'
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceActivationLease
}
})
await session.reconnect(deps.mockConn)
expect(acceptOutputDataMock).toHaveBeenCalledWith(expect.objectContaining({ data: 'held' }))
expect(acceptOutputExitMock).toHaveBeenCalledOnce()
expect(acceptOutputDataMock.mock.invocationCallOrder[0]).toBeLessThan(
acceptOutputExitMock.mock.invocationCallOrder[0]!
)
expect(sourceActivationLease.transferToRecovery).toHaveBeenCalledOnce()
expect(sourceActivationLease.rollback).not.toHaveBeenCalled()
expect(recoveryActivationLease.commit).toHaveBeenCalledOnce()
expect(recoveryActivationLease.retire).not.toHaveBeenCalled()
expect(muxRequestMock).not.toHaveBeenCalledWith('pty.cancelDelivery', expect.anything())
expect(setPtyOwnership).not.toHaveBeenCalled()
expect(deps.mockStore.markSshRemotePtyLease).not.toHaveBeenCalledWith(
targetId,
'pty-1',
'attached'
)
})
it('settles exact cancellation before publishing an exit with incomplete recovery data', async () => {
const targetId = 'exit-with-incomplete-private-body'
let settleCancellation: ((proof: unknown) => void) | undefined
muxRequestMock.mockImplementation((method) =>
method === 'pty.cancelDelivery'
? new Promise((resolve) => {
settleCancellation = resolve
})
: Promise.resolve([])
)
const { session, deps } = await prepareRecovery(targetId)
const recoveryActivationLease = { commit: vi.fn(), retire: vi.fn() }
const sourceActivationLease = {
commit: vi.fn(),
rollback: vi.fn(async () => true),
transferToRecovery: vi.fn((sink: (payload: unknown) => void) => {
sink({
id: `ssh:${targetId}@@pty-1`,
data: 'partial',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: 2,
source: {
relayPtyId: 'pty-1',
spanId: 'new-token:4:6',
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu: 4,
sourceEndSu: 6
}
})
return recoveryActivationLease
})
}
attachForReconnectMock.mockImplementation(async () => {
ptyExitHandlerRef.current?.({
id: `ssh:${targetId}@@pty-1`,
code: 0,
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
incarnationId: 'incarnation-1'
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceActivationLease
}
})
const reconnect = session.reconnect(deps.mockConn)
await vi.waitFor(() =>
expect(muxRequestMock).toHaveBeenCalledWith('pty.cancelDelivery', {
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token'
})
)
expect(acceptOutputExitMock).not.toHaveBeenCalled()
settleCancellation?.({ canceled: true, sentEndSu: 6, creditedEndSu: 4 })
await reconnect
expect(acceptOutputDataMock).not.toHaveBeenCalled()
expect(acceptOutputExitMock).toHaveBeenCalledOnce()
expect(recoveryActivationLease.commit).not.toHaveBeenCalled()
expect(recoveryActivationLease.retire).toHaveBeenCalledOnce()
expect(sourceActivationLease.rollback).not.toHaveBeenCalled()
expect(applySshPtySourceRecoveryCancellationProof).toHaveBeenCalledOnce()
})
it('awaits provisional cancellation proof before publishing an exact recovery exit', async () => {
const targetId = 'exit-before-recovery-identity'
let settleRollback: ((settled: boolean) => void) | undefined
const { session, deps } = await prepareRecovery(targetId)
const sourceActivationLease = {
commit: vi.fn(),
rollback: vi.fn(
() =>
new Promise<boolean>((resolve) => {
settleRollback = resolve
})
),
transferToRecovery: vi.fn()
}
attachForReconnectMock.mockImplementation(async () => {
ptyExitHandlerRef.current?.({
id: `ssh:${targetId}@@pty-1`,
code: 0,
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
incarnationId: 'incarnation-1'
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: { status: 'restoreRequired', reason: 'checkpointUnavailable' },
sourceActivationLease
}
})
const reconnect = session.reconnect(deps.mockConn)
await vi.waitFor(() => expect(sourceActivationLease.rollback).toHaveBeenCalledOnce())
expect(acceptOutputExitMock).not.toHaveBeenCalled()
settleRollback?.(true)
await reconnect
expect(acceptOutputExitMock).toHaveBeenCalledOnce()
expect(sourceActivationLease.transferToRecovery).not.toHaveBeenCalled()
expect(sourceActivationLease.commit).not.toHaveBeenCalled()
})
it('retains the empty recovery end as the first post-activation source anchor', async () => {
const targetId = 'empty-recovery-gap'
const { session, deps } = await prepareRecovery(targetId)
attachForReconnectMock.mockImplementation(async () => {
queueMicrotask(() => {
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 4
})
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 4
}
}
})
await session.reconnect(deps.mockConn)
const closeCount = vi.mocked(closeSshPtyOutputGeneration).mock.calls.length
emitSourceFrame({
targetId,
token: 'new-token',
clientGeneration: 2,
ownerGeneration: 2,
sourceStartSu: 5,
sourceEndSu: 8
})
expect(acceptOutputDataMock).not.toHaveBeenCalled()
expect(closeSshPtyOutputGeneration).toHaveBeenCalledTimes(closeCount + 1)
expect(closeSshPtyOutputGeneration).toHaveBeenLastCalledWith(
23,
'ssh_source_frame_stale_or_non_contiguous'
)
})
it('drops late frames from a token after its cancellation proof is validated', async () => {
const targetId = 'late-after-cancel'
muxRequestMock.mockImplementation(async (method) =>
method === 'pty.cancelDelivery' ? { canceled: true, sentEndSu: 8, creditedEndSu: 4 } : []
)
const { session, deps } = await prepareRecovery(targetId)
attachForReconnectMock.mockImplementation(async () => {
queueMicrotask(() => {
emitSourceFrame({
targetId,
token: 'new-token',
clientGeneration: 2,
ownerGeneration: 2,
sourceStartSu: 5,
sourceEndSu: 8
})
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
})
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
}
}
})
await session.reconnect(deps.mockConn)
const closeCount = vi.mocked(closeSshPtyOutputGeneration).mock.calls.length
emitSourceFrame({
targetId,
token: 'new-token',
clientGeneration: 2,
ownerGeneration: 2,
sourceStartSu: 8,
sourceEndSu: 12
})
expect(acceptOutputDataMock).not.toHaveBeenCalled()
expect(closeSshPtyOutputGeneration).toHaveBeenCalledTimes(closeCount)
expect(deps.mockStore.markSshRemotePtyLease).toHaveBeenCalledWith(targetId, 'pty-1', 'detached')
expect(clearProviderPtyState).not.toHaveBeenCalled()
expect(clearPtyOwnershipForConnection).not.toHaveBeenCalled()
expect(deletePtyOwnership).not.toHaveBeenCalled()
expect(deps.mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:exit', expect.anything())
expect(muxDisposeMock).not.toHaveBeenCalledWith('shutdown')
})
it('rejects cancellation proof below capacity-rejected and later private frames', async () => {
const targetId = 'capacity-watermark'
muxRequestMock.mockImplementation(async (method) =>
method === 'pty.cancelDelivery' ? { canceled: true, sentEndSu: 8, creditedEndSu: 4 } : []
)
const { session, deps } = await prepareRecovery(targetId)
const recoveryActivationLease = { commit: vi.fn(), retire: vi.fn() }
const sourceActivationLease = {
commit: vi.fn(),
rollback: vi.fn(),
transferToRecovery: vi.fn((sink: (payload: unknown) => void) => {
sink({
id: `ssh:${targetId}@@pty-1`,
data: 'x'.repeat(2 * 1024 * 1024 + 1),
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: 4,
source: {
relayPtyId: 'pty-1',
spanId: 'new-token:4:8',
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu: 4,
sourceEndSu: 8
}
})
sink({
id: `ssh:${targetId}@@pty-1`,
data: 'later',
providerGeneration: 23,
ptyIncarnation: 'incarnation-1',
sequenceChars: 4,
source: {
relayPtyId: 'pty-1',
spanId: 'new-token:8:12',
clientGeneration: 2,
ownerGeneration: 2,
deliveryToken: 'new-token',
sourceStartSu: 8,
sourceEndSu: 12
}
})
return recoveryActivationLease
})
}
attachForReconnectMock.mockResolvedValue({
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 12
},
sourceActivationLease
})
await session.reconnect(deps.mockConn)
expect(muxRequestMock).toHaveBeenCalledWith(
'pty.cancelDelivery',
expect.objectContaining({ deliveryToken: 'new-token' })
)
expect(vi.mocked(closeSshPtyOutputGeneration).mock.calls).toContainEqual([
23,
'ssh_source_recovery_cancellation_failed'
])
expect(applySshPtySourceRecoveryCancellationProof).not.toHaveBeenCalled()
expect(recoveryActivationLease.commit).not.toHaveBeenCalled()
expect(recoveryActivationLease.retire).toHaveBeenCalledOnce()
})
it.each([
['publication', undefined],
['proof', { canceled: true, sentEndSu: 8, creditedEndSu: 4 }],
['negative-end', { canceled: true, sentEndSu: -1, creditedEndSu: 4 }],
['credited-ahead', { canceled: true, sentEndSu: 8, creditedEndSu: 9 }],
['checkpoint-mismatch', { canceled: true, sentEndSu: 8, creditedEndSu: 3 }],
['sent-before-private-end', { canceled: true, sentEndSu: 7, creditedEndSu: 4 }]
] as const)(
'closes one provider generation when recovery cancellation %s rejects',
async (failure, cancellationResult) => {
const targetId = `cancel-${failure}-failure`
muxRequestMock.mockImplementation(async (method) => {
if (method !== 'pty.cancelDelivery') {
return []
}
if (failure === 'publication') {
throw new Error('cancel publication failed')
}
return cancellationResult
})
if (failure === 'proof') {
vi.mocked(applySshPtySourceRecoveryCancellationProof).mockImplementation(() => {
throw new Error('cancel proof rejected')
})
}
const { session, deps } = await prepareRecovery(targetId)
const onRelayLost = vi.fn()
const recoveryActivationLease = { commit: vi.fn(), retire: vi.fn() }
const activationLease = {
commit: vi.fn(),
rollback: vi.fn(),
transferToRecovery: vi.fn(() => recoveryActivationLease)
}
session.setOnRelayLost(onRelayLost)
let cleanupCountsBeforeFailure:
| {
generation: number
mux: number
provider: number
ack: number
cancellation: number
unregister: number
}
| undefined
attachForReconnectMock.mockImplementation(async () => {
cleanupCountsBeforeFailure = {
generation: vi.mocked(closeSshPtyOutputGeneration).mock.calls.length,
mux: muxDisposeMock.mock.calls.length,
provider: ptyProviderDisposeMock.mock.calls.length,
ack: sourceAckCleanupMock.mock.calls.length,
cancellation: sourceCancellationCleanupMock.mock.calls.length,
unregister: vi.mocked(unregisterSshPtyProvider).mock.calls.length
}
queueMicrotask(() => {
emitSourceFrame({
targetId,
token: 'new-token',
clientGeneration: 2,
ownerGeneration: 2,
sourceStartSu: 5,
sourceEndSu: 8
})
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceActivationLease: activationLease
}
})
await session.reconnect(deps.mockConn)
expect(cleanupCountsBeforeFailure).toBeDefined()
const before = cleanupCountsBeforeFailure!
expect(vi.mocked(closeSshPtyOutputGeneration).mock.calls).toHaveLength(before.generation + 1)
expect(closeSshPtyOutputGeneration).toHaveBeenLastCalledWith(
23,
'ssh_source_recovery_cancellation_failed'
)
expect(muxDisposeMock.mock.calls).toHaveLength(before.mux + 1)
expect(muxDisposeMock).toHaveBeenLastCalledWith('connection_lost')
expect(ptyProviderDisposeMock.mock.calls).toHaveLength(before.provider + 1)
expect(sourceAckCleanupMock.mock.calls).toHaveLength(before.ack + 1)
expect(sourceCancellationCleanupMock.mock.calls).toHaveLength(before.cancellation + 1)
expect(vi.mocked(unregisterSshPtyProvider).mock.calls).toHaveLength(before.unregister + 1)
expect(unregisterSshPtyProvider).toHaveBeenLastCalledWith(targetId)
expect(activationLease.transferToRecovery).toHaveBeenCalledOnce()
expect(activationLease.commit).not.toHaveBeenCalled()
expect(activationLease.rollback).not.toHaveBeenCalled()
expect(recoveryActivationLease.commit).not.toHaveBeenCalled()
expect(recoveryActivationLease.retire).toHaveBeenCalledOnce()
expect(onRelayLost).toHaveBeenCalledOnce()
expect(session.getState()).toBe('reconnecting')
expect(clearProviderPtyState).not.toHaveBeenCalled()
expect(clearPtyOwnershipForConnection).not.toHaveBeenCalled()
expect(deletePtyOwnership).not.toHaveBeenCalled()
expect(deps.mockStore.markSshRemotePtyLease).not.toHaveBeenCalled()
expect(deps.mockWindow.webContents.send).not.toHaveBeenCalledWith(
'pty:exit',
expect.anything()
)
expect(muxDisposeMock).not.toHaveBeenCalledWith('shutdown')
expect(vi.mocked(closeSshPtyOutputGeneration).mock.calls).not.toContainEqual([
99,
expect.anything()
])
expect(unregisterSshPtyProvider).not.toHaveBeenCalledWith('unrelated-target')
}
)
it('keeps a stale overlapping recovery from canceling or mutating its replacement', async () => {
const targetId = 'overlapping-recovery'
const { session, deps } = await prepareRecovery(targetId)
const staleRecoveryLease = { commit: vi.fn(), retire: vi.fn() }
const replacementRecoveryLease = { commit: vi.fn(), retire: vi.fn() }
const staleLease = {
commit: vi.fn(),
rollback: vi.fn(),
transferToRecovery: vi.fn(() => staleRecoveryLease)
}
const replacementLease = {
commit: vi.fn(),
rollback: vi.fn(),
transferToRecovery: vi.fn(() => replacementRecoveryLease)
}
attachForReconnectMock.mockImplementation(async () => {
const ownerGeneration = openConsumerSessionMock.mock.calls.length
if (ownerGeneration === 3) {
queueMicrotask(() => {
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
id: 'pty-1',
clientGeneration: 3,
ownerGeneration: 3,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'replacement-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 4
})
})
}
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: ownerGeneration,
ownerGeneration,
ptyIncarnation: 'incarnation-1',
deliveryToken: ownerGeneration === 2 ? 'stale-token' : 'replacement-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 4
},
sourceActivationLease: ownerGeneration === 2 ? staleLease : replacementLease
}
})
const staleReconnect = session.reconnect(deps.mockConn)
await vi.waitFor(() => expect(attachForReconnectMock).toHaveBeenCalledTimes(1))
await Promise.resolve()
const replacementReconnect = session.reconnect(deps.mockConn)
await Promise.all([staleReconnect, replacementReconnect])
const recoveryRequests = attachForReconnectMock.mock.calls.map((call) => call[2])
expect(recoveryRequests).toHaveLength(2)
expect(recoveryRequests[1]).toMatchObject({
status: 'checkpoint',
deliveryToken: 'old-token',
acceptedSourceEndSu: 4
})
expect(muxRequestMock.mock.calls.filter(([method]) => method === 'pty.cancelDelivery')).toEqual(
[]
)
expect(deps.mockStore.markSshRemotePtyLease).toHaveBeenCalledTimes(1)
expect(deps.mockStore.markSshRemotePtyLease).toHaveBeenCalledWith(targetId, 'pty-1', 'attached')
expect(setPtyOwnership).toHaveBeenCalledTimes(1)
expect(staleLease.transferToRecovery).toHaveBeenCalledOnce()
expect(staleLease.commit).not.toHaveBeenCalled()
expect(staleLease.rollback).not.toHaveBeenCalled()
expect(staleRecoveryLease.commit).not.toHaveBeenCalled()
expect(staleRecoveryLease.retire).toHaveBeenCalledOnce()
expect(replacementLease.transferToRecovery).toHaveBeenCalledOnce()
expect(replacementLease.commit).not.toHaveBeenCalled()
expect(replacementLease.rollback).not.toHaveBeenCalled()
expect(replacementRecoveryLease.commit).toHaveBeenCalledOnce()
expect(replacementRecoveryLease.retire).not.toHaveBeenCalled()
expect(clearProviderPtyState).not.toHaveBeenCalled()
expect(clearPtyOwnershipForConnection).not.toHaveBeenCalled()
expect(deletePtyOwnership).not.toHaveBeenCalled()
expect(deps.mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:exit', expect.anything())
expect(muxDisposeMock).not.toHaveBeenCalledWith('shutdown')
expect(session.getState()).toBe('ready')
})
})
@@ -15,12 +15,22 @@ vi.mock('./ssh-relay-deploy', () => ({
deployAndLaunchRelay: vi.fn()
}))
vi.mock('./ssh-pty-consumer-session', () => ({
openSshPtyConsumerSession: vi.fn(async (_mux, options) => ({
clientInstanceId: options.clientInstanceId,
clientGeneration: 1,
ownerGeneration: 1,
ownerLease: 'test-owner-lease'
}))
}))
vi.mock('./ssh-channel-multiplexer', () => {
return {
SshChannelMultiplexer: class MockSshChannelMultiplexer {
notify = vi.fn()
request = vi.fn().mockResolvedValue([])
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn().mockReturnValue(() => {})
onDispose = vi.fn().mockReturnValue(() => {})
dispose = vi.fn()
@@ -1,5 +1,6 @@
import { vi, type Mock } from 'vitest'
import type { BrowserWindow } from 'electron'
import { PtyConsumerSession } from '../../shared/pty-consumer-session'
import type { SshConnection } from './ssh-connection'
import type { Store } from '../persistence'
import type { SshPortForwardManager } from './ssh-port-forward'
@@ -47,3 +48,39 @@ export function mockDeploySuccess(): void {
platform: 'linux-x64'
})
}
export function createMismatchedOwnerRecoveryError(): unknown {
const stateMachine = new PtyConsumerSession({
serverBuildId: 'test-relay-build',
createLease: () => 'retained-owner-lease'
})
const owner = stateMachine.admit(
{ clientInstanceId: 'retained-client', requestedRole: 'session-owner' },
{
connectionId: 'retained-connection',
principal: 'retained-principal',
authenticated: true,
allowSessionOwner: true
}
)
owner.commitPublication()
stateMachine.close('retained-connection')
try {
stateMachine.admit(
{
clientInstanceId: 'retained-client',
requestedRole: 'session-owner',
resume: { ownerGeneration: 1, ownerLease: 'retained-owner-lease' }
},
{
connectionId: 'stale-connection',
principal: 'stale-principal',
authenticated: true,
allowSessionOwner: true
}
)
} catch (error) {
return error
}
throw new Error('Expected mismatched owner recovery to fail')
}
+65 -81
View File
@@ -8,12 +8,39 @@ import {
import { SSH_RELAY_CONFIGURE_GRACE_TIME_METHOD } from '../../shared/ssh-types'
import { createMockDeps, mockDeploySuccess } from './ssh-relay-session-test-fixtures'
const { muxRequestMock } = vi.hoisted(() => ({ muxRequestMock: vi.fn() }))
const { acceptOutputDataMock, muxRequestMock, openConsumerSessionMock, pauseAdapterMock } =
vi.hoisted(() => ({
acceptOutputDataMock: vi.fn().mockResolvedValue(undefined),
muxRequestMock: vi.fn(),
openConsumerSessionMock: vi.fn(),
pauseAdapterMock: vi.fn()
}))
vi.mock('./ssh-relay-deploy', () => ({
deployAndLaunchRelay: vi.fn()
}))
vi.mock('./ssh-pty-consumer-session', () => ({
SSH_PTY_SOURCE_WINDOW_SU: 256 * 1024,
openSshPtyConsumerSession: openConsumerSessionMock
}))
vi.mock('../ipc/ssh-pty-output-intake-registry', () => ({
acceptSshPtyOutputData: acceptOutputDataMock,
acceptSshPtyOutputExit: vi.fn().mockResolvedValue(undefined),
allocateSshPtyProviderGeneration: vi.fn(() => 41),
beginSshPtyOutputGenerationMigration: vi.fn(() => ({
byPty: new Map(),
completion: Promise.resolve()
})),
closeSshPtyOutputGeneration: vi.fn(),
getSshPtyAcceptedSourceCheckpoints: vi.fn(() => []),
applySshPtySourceCancellationProof: vi.fn(() => true),
applySshPtySourceRecoveryCancellationProof: vi.fn(() => true),
installSshPtySourceAckPublisher: vi.fn(() => () => {}),
installSshPtySourceCancellationPublisher: vi.fn(() => () => {})
}))
vi.mock('./ssh-relay-deploy-helpers', () => ({
execCommand: vi.fn().mockResolvedValue('')
}))
@@ -22,8 +49,10 @@ vi.mock('./ssh-channel-multiplexer', () => {
return {
SshChannelMultiplexer: class MockSshChannelMultiplexer {
notify = vi.fn()
notifyWithSettlement = vi.fn()
request = muxRequestMock
onNotification = vi.fn().mockReturnValue(() => {})
onNotificationByMethod = vi.fn().mockReturnValue(() => {})
onRequest = vi.fn().mockReturnValue(() => {})
onDispose = vi.fn().mockReturnValue(() => {})
dispose = vi.fn()
@@ -43,6 +72,7 @@ vi.mock('../providers/ssh-pty-provider', () => ({
onExit = vi.fn().mockReturnValue(() => {})
attach = vi.fn().mockResolvedValue(undefined)
attachForReconnect = vi.fn().mockResolvedValue({})
setPtyDeliveryPauseAdapter = pauseAdapterMock
dispose = vi.fn()
}
}))
@@ -86,12 +116,6 @@ 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 {
@@ -110,20 +134,21 @@ const { registerSshGitProvider, unregisterSshGitProvider } =
describe('SshRelaySession', () => {
beforeEach(() => {
vi.clearAllMocks()
openConsumerSessionMock.mockImplementation(async (_mux, options) => ({
mode: 'legacy-fallback',
clientInstanceId: options.clientInstanceId,
serverBuildId: 'test-relay-build'
}))
delete process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS
muxRequestMock.mockReset()
muxRequestMock.mockResolvedValue([])
mockDeploySuccess()
vi.mocked(getPtyIdsForConnection).mockReturnValue([])
_resetHiddenRendererPtyDeliveryGateForTest()
})
it('drops hidden-gated PTY data after runtime ingestion with one restore marker', async () => {
it('hands each PTY data event exactly once to the bounded main intake', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const runtime = {
onPtyData: vi.fn(() => 99),
onPtyExit: vi.fn()
}
const runtime = { onPtyData: vi.fn(), onPtyExit: vi.fn() }
const session = new SshRelaySession(
'target-1',
getMainWindow,
@@ -138,75 +163,28 @@ describe('SshRelaySession', () => {
const onData = ptyProvider.onData.mock.calls[0]?.[0] as (payload: {
id: string
data: string
providerGeneration: number
ptyIncarnation: 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', {
onData({
id: 'ssh-pty-1',
reason: 'hidden-drop',
markerSeq: 99
data: 'ssh output',
providerGeneration: 41,
ptyIncarnation: 'incarnation-1'
})
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', {
expect(acceptOutputDataMock).toHaveBeenCalledTimes(1)
expect(acceptOutputDataMock).toHaveBeenCalledWith({
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 {
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: 'still delivered' })
expect(mockWindow.webContents.send).toHaveBeenCalledWith('pty:data', {
id: 'ssh-pty-1',
data: 'still delivered',
rawLength: 'still delivered'.length
data: 'ssh output',
providerGeneration: 41,
ptyIncarnation: 'incarnation-1',
rawLength: 'ssh output'.length,
transformed: false
})
expect(runtime.onPtyData).not.toHaveBeenCalled()
expect(mockWindow.webContents.send).not.toHaveBeenCalledWith('pty:data', expect.anything())
})
it('starts in idle state', () => {
@@ -501,7 +479,7 @@ describe('SshRelaySession', () => {
})
})
it('drops identical reconnect replay payloads inside one reconnect burst', async () => {
it('does not wall-clock dedupe identical replay payloads from distinct reconnects', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow, mockWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
await session.establish(mockConn)
@@ -523,7 +501,7 @@ describe('SshRelaySession', () => {
.mocked(mockWindow.webContents.send)
.mock.calls.filter(([channel]) => channel === 'pty:replay')
expect(mockAttach).toHaveBeenCalledTimes(2)
expect(replaySends).toHaveLength(1)
expect(replaySends).toHaveLength(2)
})
it('establish re-attaches owned PTYs after explicit disconnect', async () => {
@@ -747,7 +725,7 @@ describe('SshRelaySession', () => {
})
})
it('routes transient reattach failures through relay-lost retry handling', async () => {
it('retries transient reattach failure without tearing down provider registration', async () => {
const { mockConn, mockStore, mockPortForward, getMainWindow } = createMockDeps()
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
const onRelayLost = vi.fn()
@@ -763,11 +741,17 @@ describe('SshRelaySession', () => {
dispose: vi.fn()
} as unknown as ReturnType<typeof getSshPtyProvider>)
vi.mocked(getPtyIdsForConnection).mockReturnValue(['pty-live'])
const random = vi.spyOn(Math, 'random').mockReturnValue(0)
await session.reconnect(mockConn)
try {
await session.reconnect(mockConn)
} finally {
random.mockRestore()
}
expect(mockAttach).toHaveBeenCalledWith('pty-live')
expect(onRelayLost).toHaveBeenCalledWith('target-1')
expect(mockAttach).toHaveBeenCalledTimes(2)
expect(onRelayLost).not.toHaveBeenCalled()
expect(session.getState()).toBe('ready')
expect(mockStore.markSshRemotePtyLease).not.toHaveBeenCalledWith(
'target-1',
'pty-live',
File diff suppressed because it is too large Load Diff
@@ -238,6 +238,7 @@ const POSIX_FIRST_INSTALL = [
'ORCA-NPTY-PROBE-OK\n',
'', // rm probe stderr
'DEAD',
'', // publish the per-launch credential
'READY'
]
@@ -253,6 +254,17 @@ const POSIX_REPAIR = [
'ORCA-NPTY-PROBE-OK\n',
'', // rm probe stderr
'DEAD',
'', // publish the per-launch credential
'READY'
]
const POSIX_HEALTHY_RECONNECT = [
'__ORCA_REMOTE_PLATFORM__ Linux x86_64',
SHELL_HOME,
'ORCA-NATIVE-DEPS-OK',
'', // per-launch namespace marker
'DEAD',
'', // publish the per-launch credential
'READY'
]
@@ -280,7 +292,7 @@ describe('relay install writes on a split SFTP namespace', () => {
vi.restoreAllMocks()
})
it('redirects every first-install write while shell commands keep the canonical path', async () => {
it('redirects every first-install artifact transfer while shell commands stay canonical', async () => {
const conn = makeConnection(capture)
feed(POSIX_FIRST_INSTALL)
@@ -310,7 +322,7 @@ describe('relay install writes on a split SFTP namespace', () => {
expect(markerCommands[0]).toContain(`${SHELL_RELAY_DIR}/.install-lock`)
})
it('probes one shared marker for every write of an install', async () => {
it('probes one shared marker for every first-install artifact transfer', async () => {
const conn = makeConnection(capture)
feed(POSIX_FIRST_INSTALL)
@@ -514,6 +526,88 @@ describe('relay repair writes on a split SFTP namespace', () => {
vi.restoreAllMocks()
})
it('publishes a healthy reconnect credential in the canonical shell namespace', async () => {
const conn = makeConnection(capture, { transferMethods: true })
feed(POSIX_HEALTHY_RECONNECT)
await deployAndLaunchRelay(conn)
expect(capture.writePaths).toEqual([])
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
})
it('does not redirect a healthy reconnect credential through fallback SFTP', async () => {
const conn = makeConnection(capture)
feed(POSIX_HEALTHY_RECONNECT)
await deployAndLaunchRelay(conn)
expect(capture.writePaths).toEqual([])
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
})
it.each(['busy', 'error'] as const)(
'generates a healthy %s-lock credential in the canonical shell namespace',
async (lockResult) => {
const conn = makeConnection(capture)
vi.mocked(tryAcquireRelayRepairLock).mockResolvedValue(lockResult)
feed([
'__ORCA_REMOTE_PLATFORM__ Linux x86_64',
SHELL_HOME,
'ORCA-NATIVE-DEPS-OK',
'DEAD',
'', // remote credential generation
'READY'
])
await deployAndLaunchRelay(conn)
expect(capture.writePaths).toEqual([])
expect(execCommands().some((command) => MARKER_PATTERN.test(command))).toBe(false)
const credentialCommand = execCommands().find((command) => command.includes('randomBytes'))
expect(credentialCommand).toContain(`${SHELL_RELAY_DIR}/relay.sock.credential`)
expect(credentialCommand).not.toContain(SFTP_RELAY_DIR)
}
)
it('keeps a healthy system-SSH reconnect on its secure shell-path writer', async () => {
const conn = makeConnection(capture, { systemSsh: true, transferMethods: true })
feed([
'__ORCA_REMOTE_PLATFORM__ Linux x86_64',
SHELL_HOME,
'ORCA-NATIVE-DEPS-OK',
'DEAD',
'', // remote credential generation
'READY'
])
await deployAndLaunchRelay(conn)
expect(conn.sftp).not.toHaveBeenCalled()
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
expect(capture.writePaths).toEqual([])
})
it('falls back to remote credential generation when a healthy marker is unavailable', async () => {
const conn = makeConnection(capture)
feed(['__ORCA_REMOTE_PLATFORM__ Linux x86_64', SHELL_HOME, 'ORCA-NATIVE-DEPS-OK'])
vi.mocked(execCommand).mockRejectedValueOnce(new Error('read-only marker'))
feed(['DEAD', '', 'READY'])
await deployAndLaunchRelay(conn)
expect(capture.writePaths).toEqual([])
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
})
it('stamps the marker only after the locked recheck, then redirects package.json', async () => {
const conn = makeConnection(capture)
let execCountAtLock = -1
@@ -545,6 +639,7 @@ describe('relay repair writes on a split SFTP namespace', () => {
'ORCA-NPTY-PROBE-OK\n',
'', // rm probe stderr
'DEAD',
'', // remote credential generation
'READY'
])
@@ -554,6 +649,9 @@ describe('relay repair writes on a split SFTP namespace', () => {
expect(conn.sftp).not.toHaveBeenCalled()
expect(capture.writePaths).toEqual([`${SHELL_RELAY_DIR}/package.json`])
expect(capture.writeOptions).toEqual([expect.objectContaining({ sftpNamespace: undefined })])
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
})
it('degrades to shell paths when marker creation fails outright', async () => {
@@ -566,12 +664,16 @@ describe('relay repair writes on a split SFTP namespace', () => {
'ORCA-NPTY-PROBE-OK\n',
'', // rm probe stderr
'DEAD',
'', // remote credential generation
'READY'
])
await deployAndLaunchRelay(conn)
expect(capture.writePaths).toEqual([`${SHELL_RELAY_DIR}/package.json`])
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
expect(capture.realpathCalls).toEqual([])
expect(warnSpy.mock.calls.map((args) => String(args[0]))).toContainEqual(
expect.stringContaining('SFTP namespace marker unavailable')
@@ -584,12 +686,14 @@ describe('relay repair writes on a split SFTP namespace', () => {
vi.mocked(execCommand).mockRejectedValueOnce(
Object.assign(new Error('marker teardown unconfirmed'), { sshChannelCloseConfirmed: false })
)
feed(['DEAD', 'READY'])
feed(['DEAD', '', 'READY'])
await deployAndLaunchRelay(conn)
// Repair is best-effort: the relay still launches, but nothing was written and no lock was released.
expect(capture.writePaths).toEqual([])
expect(execCommands().find((command) => command.includes('randomBytes'))).toContain(
`${SHELL_RELAY_DIR}/relay.sock.credential`
)
expect(vi.mocked(finalizeInstall)).not.toHaveBeenCalled()
expect(vi.mocked(abandonInstall)).not.toHaveBeenCalled()
expect(warnSpy.mock.calls.map((args) => String(args[0]))).toContainEqual(
+29 -1
View File
@@ -29,6 +29,7 @@ describe('SSH remote Orca CLI launcher', () => {
relayDir: 'C:/Users/me user/.orca-remote/relay-v1',
nodePath: 'C:/Program Files/nodejs/node.exe',
sockPath: '\\\\.\\pipe\\orca-relay-123',
credentialFile: 'C:/Users/me user/.orca-remote/relay-v1/relay.sock.credential',
hostPlatform: getRemoteHostPlatform('win32-x64')
})
}
@@ -41,6 +42,7 @@ describe('SSH remote Orca CLI launcher', () => {
expect(plan.files[0]?.path).toBe('C:/Users/me user/.orca-relay/bin/orca-launcher.cs')
expect(plan.files[0]?.contents).toContain('ProcessStartInfo')
expect(plan.files[0]?.contents).toContain('"--orca-cli"')
expect(plan.files[0]?.contents).toContain('socketPath + ".credential"')
expect(plan.files[0]?.contents).toContain("value[index] == '\"'")
expect(plan.files[0]?.contents).toContain("character == '\\\\'")
expect(plan.files[0]?.contents).not.toContain('cmd.exe')
@@ -83,11 +85,13 @@ describe('SSH remote Orca CLI launcher', () => {
const binDir = join(root, 'bin').replaceAll('\\', '/')
const relayDir = join(root, 'relay').replaceAll('\\', '/')
const sockPath = '\\\\.\\pipe\\orca-relay-test'
const credentialFile = `${relayDir}/relay.sock.credential`
const plan = createRemoteCliInstallPlan({
binDir,
relayDir,
nodePath: process.execPath,
sockPath,
credentialFile,
hostPlatform: getRemoteHostPlatform('win32-x64')
})
for (const file of plan.files) {
@@ -127,7 +131,8 @@ describe('SSH remote Orca CLI launcher', () => {
...process.env,
ORCA_RELAY_NODE_PATH: process.execPath,
ORCA_RELAY_DIR: relayDir,
ORCA_RELAY_SOCKET_PATH: sockPath
ORCA_RELAY_SOCKET_PATH: sockPath,
ORCA_RELAY_CREDENTIAL_FILE: credentialFile
}
}
)
@@ -136,6 +141,8 @@ describe('SSH remote Orca CLI launcher', () => {
expect(JSON.parse(launched.stdout)).toEqual([
'--sock-path',
sockPath,
'--credential-file',
credentialFile,
'--orca-cli',
'orchestration',
'send',
@@ -143,6 +150,26 @@ describe('SSH remote Orca CLI launcher', () => {
body,
'--json'
])
const defaulted = spawnSync(plan.launcherPath, ['status'], {
encoding: 'utf8',
env: {
...process.env,
ORCA_RELAY_NODE_PATH: process.execPath,
ORCA_RELAY_DIR: relayDir,
ORCA_RELAY_SOCKET_PATH: sockPath,
ORCA_RELAY_CREDENTIAL_FILE: ''
}
})
expect(defaulted.status, defaulted.stderr).toBe(0)
expect(JSON.parse(defaulted.stdout)).toEqual([
'--sock-path',
sockPath,
'--credential-file',
`${sockPath}.credential`,
'--orca-cli',
'status'
])
} finally {
rmSync(root, { recursive: true, force: true })
}
@@ -161,6 +188,7 @@ describe('SSH remote Orca CLI launcher', () => {
relayDir: join(root, 'relay').replaceAll('\\', '/'),
nodePath: process.execPath,
sockPath: '\\\\.\\pipe\\orca-relay-test',
credentialFile: join(root, 'relay', 'relay.sock.credential').replaceAll('\\', '/'),
hostPlatform: getRemoteHostPlatform('win32-x64')
})
for (const file of plan.files) {
+12 -3
View File
@@ -7,6 +7,7 @@ type RemoteCliInstallEnv = {
relayDir: string
nodePath: string
sockPath: string
credentialFile?: string
hostPlatform: RemoteHostPlatform
}
@@ -35,6 +36,11 @@ internal static class OrcaRemoteCliLauncher
string nodePath = RequireEnvironmentVariable("ORCA_RELAY_NODE_PATH");
string relayDirectory = RequireEnvironmentVariable("ORCA_RELAY_DIR");
string socketPath = RequireEnvironmentVariable("ORCA_RELAY_SOCKET_PATH");
string credentialFile = Environment.GetEnvironmentVariable("ORCA_RELAY_CREDENTIAL_FILE");
if (String.IsNullOrEmpty(credentialFile))
{
credentialFile = socketPath + ".credential";
}
string relayPath = Path.Combine(relayDirectory, "relay.js");
if (!File.Exists(nodePath))
@@ -51,7 +57,7 @@ internal static class OrcaRemoteCliLauncher
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = nodePath,
Arguments = BuildArguments(relayPath, socketPath, args),
Arguments = BuildArguments(relayPath, socketPath, credentialFile, args),
UseShellExecute = false
};
@@ -78,12 +84,14 @@ internal static class OrcaRemoteCliLauncher
return value;
}
private static string BuildArguments(string relayPath, string socketPath, string[] args)
private static string BuildArguments(string relayPath, string socketPath, string credentialFile, string[] args)
{
StringBuilder commandLine = new StringBuilder();
AppendArgument(commandLine, relayPath);
AppendArgument(commandLine, "--sock-path");
AppendArgument(commandLine, socketPath);
AppendArgument(commandLine, "--credential-file");
AppendArgument(commandLine, credentialFile);
AppendArgument(commandLine, "--orca-cli");
foreach (string arg in args)
{
@@ -223,11 +231,12 @@ export function createRemoteCliInstallPlan(env: RemoteCliInstallEnv): RemoteCliI
`ORCA_RELAY_NODE_PATH=\${ORCA_RELAY_NODE_PATH:-${quoteSh(env.nodePath)}}`,
`ORCA_RELAY_DIR=\${ORCA_RELAY_DIR:-${quoteSh(env.relayDir)}}`,
`ORCA_RELAY_SOCKET_PATH=\${ORCA_RELAY_SOCKET_PATH:-${quoteSh(env.sockPath)}}`,
`ORCA_RELAY_CREDENTIAL_FILE=\${ORCA_RELAY_CREDENTIAL_FILE:-${quoteSh(env.credentialFile ?? `${env.sockPath}.credential`)}}`,
'if [ ! -S "$ORCA_RELAY_SOCKET_PATH" ]; then',
' echo "Orca SSH CLI bridge cannot find the relay socket: $ORCA_RELAY_SOCKET_PATH" >&2',
' exit 1',
'fi',
'exec "$ORCA_RELAY_NODE_PATH" "$ORCA_RELAY_DIR/relay.js" --sock-path "$ORCA_RELAY_SOCKET_PATH" --orca-cli "$@"',
'exec "$ORCA_RELAY_NODE_PATH" "$ORCA_RELAY_DIR/relay.js" --sock-path "$ORCA_RELAY_SOCKET_PATH" --credential-file "$ORCA_RELAY_CREDENTIAL_FILE" --orca-cli "$@"',
''
].join('\n')
}