提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
@@ -0,0 +1,48 @@
plugins {
kotlin("jvm")
}
group = "sh.haven"
version = "0.1.0"
dependencies {
testImplementation("sh.haven:et-transport")
testImplementation("sh.haven:ssp-transport")
testImplementation("com.github.mwiede:jsch:2.28.7")
testImplementation("com.google.protobuf:protobuf-javalite:4.29.3")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.1")
testImplementation("junit:junit:4.13.2")
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
tasks.test {
// Only run when explicitly targeted and server is specified
val testHost = System.getProperty("test.host") ?: System.getenv("TEST_HOST")
if (testHost.isNullOrBlank()) {
enabled = false
}
testLogging {
showStandardStreams = true
events("passed", "failed", "skipped")
}
// Pass system properties to test JVM
systemProperty("test.host", System.getProperty("test.host") ?: "")
systemProperty("test.port", System.getProperty("test.port") ?: "22")
systemProperty("test.user", System.getProperty("test.user") ?: "")
systemProperty("test.key", System.getProperty("test.key") ?: "")
systemProperty("test.password", System.getProperty("test.password") ?: "")
systemProperty("test.et.port", System.getProperty("test.et.port") ?: "2022")
}
@@ -0,0 +1,329 @@
package sh.haven.integration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import sh.haven.et.EtLogger
import sh.haven.et.transport.EtTransport
import java.net.ServerSocket
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Integration tests for the ET transport against a real etserver.
*
* Requires:
* - etserver running on test.host:test.et.port (default 2022)
* - etterminal available in PATH on the remote host
* - SSH key or password auth configured
*
* Run with:
* ./gradlew :integration-tests:test -Dtest.host=192.168.0.180 -Dtest.user=ian -Dtest.key=~/.ssh/id_ed25519
*/
class EtTransportTest {
private var sshSession: com.jcraft.jsch.Session? = null
private var transport: EtTransport? = null
private val receivedOutput = CopyOnWriteArrayList<String>()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val testLogger = object : EtLogger {
override fun d(tag: String, msg: String) = println("[$tag] $msg")
override fun e(tag: String, msg: String, throwable: Throwable?) {
System.err.println("[$tag] ERROR: $msg")
throwable?.printStackTrace(System.err)
}
}
@Before
fun setUp() {
TestServer.requireConfigured()
}
@After
fun tearDown() {
transport?.close()
sshSession?.disconnect()
}
/** Bootstrap etterminal via SSH, returning (clientId, passkey). */
private fun bootstrap(): Pair<String, String> {
val session = TestServer.sshConnect()
sshSession = session
val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
fun randomAlphaNum(len: Int) = String(CharArray(len) { chars.random() })
val proposedId = "XXX" + randomAlphaNum(13)
val proposedKey = randomAlphaNum(32)
val term = "xterm-256color"
val cmd = "echo '${proposedId}/${proposedKey}_${term}' | etterminal"
val result = TestServer.exec(session, cmd)
val output = result.stdout + "\n" + result.stderr
val marker = "IDPASSKEY:"
val markerPos = output.indexOf(marker)
assertTrue("etterminal bootstrap failed. Output: ${output.take(200)}", markerPos >= 0)
val idPasskey = output.substring(markerPos + marker.length).trim().take(49)
val parts = idPasskey.split("/", limit = 2)
assertEquals("Expected clientId/passkey format", 2, parts.size)
assertEquals("clientId should be 16 chars", 16, parts[0].length)
assertEquals("passkey should be 32 chars", 32, parts[1].length)
return Pair(parts[0], parts[1])
}
@Test
fun `ET bootstrap returns valid credentials`() {
bootstrap()
}
@Test
fun `ET transport connects and receives shell output`() = runBlocking {
val (clientId, passkey) = bootstrap()
val outputLatch = CountDownLatch(1)
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { data, offset, len ->
val text = String(data, offset, len)
receivedOutput.add(text)
outputLatch.countDown()
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should receive shell output within 5s", outputLatch.await(5, TimeUnit.SECONDS))
assertTrue("Should have received some output", receivedOutput.isNotEmpty())
}
@Test
fun `ET transport sends input and receives echo`() = runBlocking {
val (clientId, passkey) = bootstrap()
val echoLatch = CountDownLatch(1)
val marker = "HAVEN_TEST_${System.currentTimeMillis()}"
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { data, offset, len ->
val text = String(data, offset, len)
receivedOutput.add(text)
if (receivedOutput.joinToString("").contains(marker)) {
echoLatch.countDown()
}
},
logger = testLogger,
)
transport!!.start(scope)
// Wait for shell prompt
delay(1000)
// Send echo command
transport!!.sendInput("echo $marker\n".toByteArray())
assertTrue(
"Should receive echo of marker within 5s",
echoLatch.await(5, TimeUnit.SECONDS),
)
}
@Test
fun `ET transport handles resize during active session`() = runBlocking {
val (clientId, passkey) = bootstrap()
val outputLatch = CountDownLatch(1)
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { _, _, _ -> outputLatch.countDown() },
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 5s", outputLatch.await(5, TimeUnit.SECONDS))
// Resize should not throw or disconnect
transport!!.resize(120, 40)
delay(500)
transport!!.resize(80, 24)
delay(500)
// Verify session still works after resize
val postResizeLatch = CountDownLatch(1)
val postResizeOutput = CopyOnWriteArrayList<String>()
// Replace transport with one that captures post-resize output
val marker = "RESIZE_OK_${System.currentTimeMillis()}"
transport!!.sendInput("echo $marker\n".toByteArray())
delay(2000)
val allOutput = receivedOutput.joinToString("")
// Session should still be alive (no disconnect)
assertNotNull("Transport should still be active", transport)
}
@Test
fun `ET transport responds to keepalives`() = runBlocking {
val (clientId, passkey) = bootstrap()
val outputLatch = CountDownLatch(1)
var disconnected = false
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { _, _, _ -> outputLatch.countDown() },
onDisconnect = { disconnected = true },
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 5s", outputLatch.await(5, TimeUnit.SECONDS))
// Wait long enough for server to send keepalives (typically 5-10s)
delay(15_000)
assertFalse("Should not have disconnected during keepalive period", disconnected)
}
@Test
fun `ET transport handles rapid input`() = runBlocking {
val (clientId, passkey) = bootstrap()
val outputLatch = CountDownLatch(1)
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { _, _, _ -> outputLatch.countDown() },
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 5s", outputLatch.await(5, TimeUnit.SECONDS))
// Rapid-fire input — tests nonce sequencing under load
repeat(50) { i ->
transport!!.sendInput("echo line$i\n".toByteArray())
}
delay(3000)
// If nonces went out of sync, the server would have dropped the connection
// and subsequent sends would fail silently
}
@Test
fun `ET transport handles concurrent resize and input`() = runBlocking {
val (clientId, passkey) = bootstrap()
val outputLatch = CountDownLatch(1)
var disconnected = false
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { _, _, _ -> outputLatch.countDown() },
onDisconnect = { clean ->
println("ET disconnected during concurrent test (clean=$clean)")
disconnected = true
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 5s", outputLatch.await(5, TimeUnit.SECONDS))
// Interleave resize and input rapidly — tests nonce sequencing across packet types
repeat(30) { i ->
transport!!.sendInput("echo concurrent$i\n".toByteArray())
if (i % 3 == 0) {
transport!!.resize(80 + (i % 40), 24 + (i % 10))
}
}
delay(3000)
assertFalse("Should not disconnect during concurrent resize+input", disconnected)
}
@Test
fun `ET transport fires onDisconnect on socket close`() = runBlocking {
val (clientId, passkey) = bootstrap()
val outputLatch = CountDownLatch(1)
val disconnectLatch = CountDownLatch(1)
transport = EtTransport(
serverHost = TestServer.host,
port = TestServer.etPort,
clientId = clientId,
passkey = passkey,
onOutput = { _, _, _ -> outputLatch.countDown() },
onDisconnect = { clean ->
println("ET disconnected (clean=$clean)")
disconnectLatch.countDown()
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 5s", outputLatch.await(5, TimeUnit.SECONDS))
// Force close — should trigger onDisconnect
transport!!.close()
// onDisconnect may or may not fire depending on timing (close sets closed=true
// before the read loop sees the exception), so just verify no crash
delay(500)
}
@Test
fun `ET transport handshake timeout on unresponsive port`() = runBlocking {
// Open a local TCP port that accepts connections but never responds
val serverSocket = ServerSocket(0) // OS-assigned port
val localPort = serverSocket.localPort
val disconnectLatch = CountDownLatch(1)
try {
transport = EtTransport(
serverHost = "127.0.0.1",
port = localPort,
clientId = "XXX" + "A".repeat(13),
passkey = "B".repeat(32),
onOutput = { _, _, _ -> },
onDisconnect = { clean ->
println("ET handshake timeout disconnect (clean=$clean)")
disconnectLatch.countDown()
},
logger = testLogger,
)
transport!!.start(scope)
// Should disconnect within ~10s (handshake read timeout)
assertTrue(
"Should fire onDisconnect within 15s on unresponsive port",
disconnectLatch.await(15, TimeUnit.SECONDS),
)
} finally {
serverSocket.close()
}
}
}
@@ -0,0 +1,161 @@
package sh.haven.integration
import com.google.protobuf.ExtensionRegistryLite
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import sh.haven.mosh.crypto.MoshCrypto
import sh.haven.mosh.network.MoshConnection
import sh.haven.mosh.proto.Hostinput
import sh.haven.mosh.proto.Userinput
import sh.haven.mosh.proto.Transportinstruction.Instruction as TransportInstruction
/**
* Low-level mosh connectivity test — bypasses the transport to test
* the connection + crypto layer directly.
*/
class MoshConnectivityTest {
@Before
fun setUp() {
TestServer.requireConfigured()
}
@Test
fun `mosh key parses to valid AES-128 key`() {
val session = TestServer.sshConnect()
try {
val result = TestServer.exec(session, "mosh-server new -s -c 256 -l LANG=en_US.UTF-8")
val output = result.stdout + "\n" + result.stderr
val connectLine = output.lines().first { it.startsWith("MOSH CONNECT") }
val key = connectLine.split(" ")[3]
println("Key: $key (${key.length} chars)")
val crypto = MoshCrypto(key)
assertNotNull("Crypto should initialise", crypto)
} finally {
session.disconnect()
}
}
@Test
fun `mosh connection sends and receives first packet`() {
val session = TestServer.sshConnect()
try {
val result = TestServer.exec(session, "mosh-server new -s -c 256 -l LANG=en_US.UTF-8")
val output = result.stdout + "\n" + result.stderr
val connectLine = output.lines().first { it.startsWith("MOSH CONNECT") }
val parts = connectLine.split(" ")
val moshPort = parts[2].toInt()
val moshKey = parts[3]
println("Connecting to ${TestServer.host}:$moshPort")
val crypto = MoshCrypto(moshKey)
val conn = MoshConnection(TestServer.host, moshPort, crypto)
// Send an empty keepalive instruction (what the transport sends initially)
val keepalive = TransportInstruction.newBuilder().apply {
oldNum = 0
newNum = 0
ackNum = 0
}.build()
conn.sendInstruction(keepalive)
println("Sent initial keepalive")
// Try to receive server's response
val response = conn.receiveInstruction(5000)
assertNotNull("Should receive response from mosh-server within 5s", response)
println("Received instruction: oldNum=${response!!.oldNum} newNum=${response.newNum} ackNum=${response.ackNum}")
assertTrue("Server should have newNum > 0", response.newNum > 0)
conn.close()
} finally {
session.disconnect()
}
}
/**
* Low-level protocol test: sends an initial resize (which triggers mosh-server's
* child release) and verifies terminal output arrives in subsequent diffs.
* Without the resize, mosh-server never releases the shell and all diffs are empty.
*/
@Test
fun `mosh initial resize triggers terminal output`() {
val session = TestServer.sshConnect()
try {
val result = TestServer.exec(session, "mosh-server new -s -c 256 -l LANG=en_US.UTF-8")
val output = result.stdout + "\n" + result.stderr
val connectLine = output.lines().first { it.startsWith("MOSH CONNECT") }
val parts = connectLine.split(" ")
val moshPort = parts[2].toInt()
val moshKey = parts[3]
val crypto = MoshCrypto(moshKey)
val conn = MoshConnection(TestServer.host, moshPort, crypto)
val registry = ExtensionRegistryLite.newInstance().also {
Hostinput.registerAllExtensions(it)
}
// Build a resize diff (UserMessage with one Resize instruction)
val resizeMsg = Userinput.UserMessage.newBuilder()
.addInstruction(
Userinput.Instruction.newBuilder()
.setExtension(Userinput.resize,
Userinput.ResizeMessage.newBuilder()
.setWidth(80).setHeight(24).build())
)
.build()
val resizeDiff = resizeMsg.toByteArray()
// Send instruction with newNum=1 (resize makes state advance from 0 to 1)
val inst = TransportInstruction.newBuilder()
.setProtocolVersion(2)
.setOldNum(0).setNewNum(1).setAckNum(0).setThrowawayNum(0)
.setDiff(com.google.protobuf.ByteString.copyFrom(resizeDiff))
.build()
conn.sendInstruction(inst)
println("Sent initial resize instruction")
var remoteStateNum = 0L
var foundTerminalOutput = false
for (round in 1..20) {
// Send ack with current remoteStateNum
val ack = TransportInstruction.newBuilder()
.setProtocolVersion(2)
.setOldNum(0).setNewNum(1).setAckNum(remoteStateNum).setThrowawayNum(0)
.setDiff(com.google.protobuf.ByteString.copyFrom(resizeDiff))
.build()
if (round > 1) conn.sendInstruction(ack)
val response = conn.receiveInstruction(2000) ?: continue
if (response.newNum > remoteStateNum) {
remoteStateNum = response.newNum
}
if (response.hasDiff() && !response.diff.isEmpty) {
val hostMsg = Hostinput.HostMessage.parseFrom(response.diff, registry)
for (hi in hostMsg.instructionList) {
if (hi.hasExtension(Hostinput.hostbytes)) {
val text = hi.getExtension(Hostinput.hostbytes).hoststring.toStringUtf8()
println("Round $round: terminal output (${text.length} chars): ${text.take(80).replace("\n", "\\n")}")
if (text.isNotEmpty()) foundTerminalOutput = true
}
}
} else {
println("Round $round: newNum=${response.newNum} (no diff)")
}
if (foundTerminalOutput) break
}
assertTrue("Should receive terminal output after sending initial resize", foundTerminalOutput)
conn.close()
} finally {
session.disconnect()
}
}
}
@@ -0,0 +1,254 @@
package sh.haven.integration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import sh.haven.mosh.MoshLogger
import sh.haven.mosh.transport.MoshTransport
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Integration tests for the Mosh transport against a real mosh-server.
*
* Requires:
* - mosh-server installed on test.host
* - UDP port 60001+ open on the server firewall
* - SSH key or password auth configured
*
* Run with:
* ./gradlew :integration-tests:test -Dtest.host=192.168.0.180 -Dtest.user=ian -Dtest.key=~/.ssh/id_ed25519
*/
class MoshTransportTest {
private var sshSession: com.jcraft.jsch.Session? = null
private var transport: MoshTransport? = null
private val receivedOutput = CopyOnWriteArrayList<String>()
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val testLogger = object : MoshLogger {
override fun d(tag: String, msg: String) = println("[$tag] $msg")
override fun e(tag: String, msg: String, throwable: Throwable?) {
System.err.println("[$tag] ERROR: $msg")
throwable?.printStackTrace(System.err)
}
}
@Before
fun setUp() {
TestServer.requireConfigured()
}
@After
fun tearDown() {
transport?.close()
sshSession?.disconnect()
}
/** Bootstrap mosh-server via SSH, returning (serverIp, port, key). */
private fun bootstrap(): Triple<String, Int, String> {
val session = TestServer.sshConnect()
sshSession = session
val cmd = "mosh-server new -s -c 256 -l LANG=en_US.UTF-8"
val result = TestServer.exec(session, cmd)
val output = result.stdout + "\n" + result.stderr
val connectLine = output.lines().firstOrNull { it.startsWith("MOSH CONNECT") }
assertNotNull(
"mosh-server bootstrap failed. stderr: ${result.stderr.take(200)}",
connectLine,
)
val parts = connectLine!!.split(" ")
assertTrue("Expected MOSH CONNECT <port> <key>", parts.size >= 4)
val moshPort = parts[2].toInt()
val moshKey = parts[3]
return Triple(TestServer.host, moshPort, moshKey)
}
@Test
fun `mosh bootstrap returns valid MOSH CONNECT`() {
val (host, port, key) = bootstrap()
assertTrue("Port should be >= 60001", port >= 60001)
assertTrue("Key should be non-empty", key.isNotBlank())
println("MOSH CONNECT $host:$port key=${key.take(6)}...")
}
@Test
fun `mosh transport connects and receives shell output`() {
val (host, port, key) = bootstrap()
val outputLatch = CountDownLatch(1)
var disconnectReason: Boolean? = null
println("Connecting mosh transport to $host:$port")
transport = MoshTransport(
serverIp = host,
port = port,
key = key,
onOutput = { data, offset, len ->
val text = String(data, offset, len)
println("Mosh output (${len} bytes): ${text.take(80).replace("\n", "\\n")}")
receivedOutput.add(text)
outputLatch.countDown()
},
onDisconnect = { clean ->
println("Mosh disconnected (clean=$clean)")
disconnectReason = clean
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue(
"Should receive shell output within 15s (disconnected=$disconnectReason)",
outputLatch.await(15, TimeUnit.SECONDS),
)
assertTrue("Should have received some output", receivedOutput.isNotEmpty())
}
@Test
fun `mosh transport sends input and receives echo`() = runBlocking {
val (host, port, key) = bootstrap()
val echoLatch = CountDownLatch(1)
val outputLatch = CountDownLatch(1)
val marker = "HAVEN_MOSH_${System.currentTimeMillis()}"
var disconnected = false
transport = MoshTransport(
serverIp = host,
port = port,
key = key,
onOutput = { data, offset, len ->
val text = String(data, offset, len)
receivedOutput.add(text)
outputLatch.countDown()
if (receivedOutput.joinToString("").contains(marker)) {
echoLatch.countDown()
}
},
onDisconnect = { clean ->
println("Mosh disconnected during echo test (clean=$clean)")
disconnected = true
},
logger = testLogger,
)
transport!!.start(scope)
// Wait for shell prompt
assertTrue("Should receive initial output within 15s", outputLatch.await(15, TimeUnit.SECONDS))
transport!!.sendInput("echo $marker\n".toByteArray())
assertTrue(
"Should receive echo of marker within 5s (disconnected=$disconnected)",
echoLatch.await(5, TimeUnit.SECONDS),
)
}
@Test
fun `mosh transport handles resize`() = runBlocking {
val (host, port, key) = bootstrap()
val outputLatch = CountDownLatch(1)
var disconnected = false
transport = MoshTransport(
serverIp = host,
port = port,
key = key,
onOutput = { _, _, _ -> outputLatch.countDown() },
onDisconnect = { clean ->
println("Mosh disconnected during resize test (clean=$clean)")
disconnected = true
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 15s", outputLatch.await(15, TimeUnit.SECONDS))
transport!!.resize(120, 40)
delay(500)
transport!!.resize(80, 24)
delay(500)
assertFalse("Should not disconnect after resize", disconnected)
}
@Test
fun `mosh transport survives idle period`() = runBlocking {
val (host, port, key) = bootstrap()
val outputLatch = CountDownLatch(1)
var disconnected = false
transport = MoshTransport(
serverIp = host,
port = port,
key = key,
onOutput = { _, _, _ -> outputLatch.countDown() },
onDisconnect = { clean ->
println("Mosh disconnected during idle test (clean=$clean)")
disconnected = true
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 15s", outputLatch.await(15, TimeUnit.SECONDS))
// Mosh keepalive interval is 3s — wait long enough for several
delay(10_000)
assertFalse("Should not disconnect during idle", disconnected)
// Verify session still works
val marker = "ALIVE_${System.currentTimeMillis()}"
val aliveLatch = CountDownLatch(1)
// Re-wire output capture
transport!!.sendInput("echo $marker\n".toByteArray())
delay(2000)
val allOutput = receivedOutput.joinToString("")
// Transport should still be functional
assertNotNull("Transport should still be active", transport)
}
@Test
fun `mosh transport handles rapid input without nonce desync`() = runBlocking {
val (host, port, key) = bootstrap()
val outputLatch = CountDownLatch(1)
var disconnected = false
transport = MoshTransport(
serverIp = host,
port = port,
key = key,
onOutput = { _, _, _ -> outputLatch.countDown() },
onDisconnect = { clean ->
println("Mosh disconnected during rapid input test (clean=$clean)")
disconnected = true
},
logger = testLogger,
)
transport!!.start(scope)
assertTrue("Should connect within 15s", outputLatch.await(15, TimeUnit.SECONDS))
// Rapid-fire input
repeat(50) { i ->
transport!!.sendInput("echo rapid$i\n".toByteArray())
}
delay(3000)
assertFalse("Should not disconnect during rapid input", disconnected)
}
}
@@ -0,0 +1,179 @@
package sh.haven.integration
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import sh.haven.et.EtLogger
import sh.haven.et.transport.EtTransport
import sh.haven.mosh.MoshLogger
import sh.haven.mosh.transport.MoshTransport
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* Tests that session manager commands (tmux/screen) work correctly
* over Mosh and ET transports — verifying prompt detection logic.
*
* Requires tmux installed on the test server.
*/
class SessionManagerTest {
private var sshSession: com.jcraft.jsch.Session? = null
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val receivedOutput = CopyOnWriteArrayList<String>()
private val etLogger = object : EtLogger {
override fun d(tag: String, msg: String) = println("[$tag] $msg")
override fun e(tag: String, msg: String, throwable: Throwable?) {
System.err.println("[$tag] ERROR: $msg")
throwable?.printStackTrace(System.err)
}
}
private val moshLogger = object : MoshLogger {
override fun d(tag: String, msg: String) = println("[$tag] $msg")
override fun e(tag: String, msg: String, throwable: Throwable?) {
System.err.println("[$tag] ERROR: $msg")
throwable?.printStackTrace(System.err)
}
}
@Before
fun setUp() {
TestServer.requireConfigured()
}
@After
fun tearDown() {
sshSession?.disconnect()
}
/** Strip ANSI/OSC escape sequences. */
private fun stripEscapes(text: String): String {
return text.replace(Regex("\u001b(?:\\[[^a-zA-Z]*[a-zA-Z]|][^\u0007]*\u0007)"), "")
}
@Test
fun `prompt detection finds shell prompt in mosh output`() = runBlocking {
val session = TestServer.sshConnect()
sshSession = session
val result = TestServer.exec(session, "mosh-server new -s -c 256 -l LANG=en_US.UTF-8")
val output = result.stdout + "\n" + result.stderr
val connectLine = output.lines().firstOrNull { it.startsWith("MOSH CONNECT") }
?: return@runBlocking // mosh-server not available, skip
val parts = connectLine.split(" ")
val moshPort = parts[2].toInt()
val moshKey = parts[3]
val promptDetected = AtomicBoolean(false)
val promptLatch = CountDownLatch(1)
val transport = MoshTransport(
serverIp = TestServer.host,
port = moshPort,
key = moshKey,
onOutput = { data, offset, len ->
val raw = String(data, offset, len)
receivedOutput.add(raw)
if (!promptDetected.get()) {
val stripped = stripEscapes(raw).trimEnd()
if (stripped.isNotEmpty()) {
val last = stripped.last()
if (last == '$' || last == '#' || last == '%' || last == '>') {
promptDetected.set(true)
promptLatch.countDown()
}
}
}
},
logger = moshLogger,
)
transport.start(scope)
assertTrue(
"Should detect shell prompt within 5s",
promptLatch.await(5, TimeUnit.SECONDS),
)
transport.close()
}
@Test
fun `tmux attach command executes after prompt over mosh`() = runBlocking {
val session = TestServer.sshConnect()
sshSession = session
// Check tmux is available
val tmuxCheck = TestServer.exec(session, "command -v tmux")
if (tmuxCheck.exitStatus != 0) {
println("tmux not installed, skipping")
return@runBlocking
}
// Kill any existing test session
TestServer.exec(session, "tmux kill-session -t haven-integ-test 2>/dev/null")
val result = TestServer.exec(session, "mosh-server new -s -c 256 -l LANG=en_US.UTF-8")
val output = result.stdout + "\n" + result.stderr
val connectLine = output.lines().firstOrNull { it.startsWith("MOSH CONNECT") }
?: return@runBlocking
val parts = connectLine.split(" ")
val moshPort = parts[2].toInt()
val moshKey = parts[3]
val promptDetected = AtomicBoolean(false)
val tmuxCommand = "tmux new-session -A -s haven-integ-test"
val transportRef = arrayOfNulls<MoshTransport>(1)
val transport = MoshTransport(
serverIp = TestServer.host,
port = moshPort,
key = moshKey,
onOutput = { data, offset, len ->
val raw = String(data, offset, len)
receivedOutput.add(raw)
// Same prompt detection logic as TerminalViewModel
if (!promptDetected.get()) {
val stripped = stripEscapes(raw).trimEnd()
if (stripped.isNotEmpty()) {
val last = stripped.last()
if (last == '$' || last == '#' || last == '%' || last == '>') {
if (promptDetected.compareAndSet(false, true)) {
println("Prompt detected ('$last'), sending tmux command")
transportRef[0]?.sendInput("$tmuxCommand\n".toByteArray())
}
}
}
}
},
logger = moshLogger,
)
transportRef[0] = transport
transport.start(scope)
// Wait for tmux to start
delay(3000)
// Verify tmux session was created
val tmuxList = TestServer.exec(session, "tmux list-sessions 2>/dev/null")
assertTrue(
"tmux session 'haven-integ-test' should exist. Output: ${tmuxList.stdout}",
tmuxList.stdout.contains("haven-integ-test"),
)
transport.close()
// Cleanup
TestServer.exec(session, "tmux kill-session -t haven-integ-test 2>/dev/null")
}
}
@@ -0,0 +1,89 @@
package sh.haven.integration
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import org.junit.Assume.assumeTrue
import java.io.File
/**
* SSH connection to the test server for bootstrapping mosh/ET sessions.
*
* Configure via system properties:
* -Dtest.host=192.168.0.180
* -Dtest.port=22
* -Dtest.user=ian
* -Dtest.key=~/.ssh/id_ed25519
* -Dtest.password=
* -Dtest.et.port=2022
*
* Or environment variables: TEST_HOST, TEST_PORT, TEST_USER, TEST_KEY, TEST_PASSWORD, TEST_ET_PORT
*/
object TestServer {
val host: String = prop("test.host", "TEST_HOST") ?: ""
val port: Int = prop("test.port", "TEST_PORT")?.toIntOrNull() ?: 22
val user: String = prop("test.user", "TEST_USER") ?: ""
val keyPath: String = prop("test.key", "TEST_KEY") ?: ""
val password: String = prop("test.password", "TEST_PASSWORD") ?: ""
val etPort: Int = prop("test.et.port", "TEST_ET_PORT")?.toIntOrNull() ?: 2022
val isConfigured: Boolean
get() = host.isNotBlank() && user.isNotBlank()
fun requireConfigured() {
assumeTrue(
"Test server not configured. Set -Dtest.host=... -Dtest.user=...",
isConfigured,
)
}
/** Open an SSH session to the test server. Caller must disconnect. */
fun sshConnect(): Session {
val jsch = JSch()
val expandedKey = keyPath.replaceFirst("~", System.getProperty("user.home"))
if (expandedKey.isNotBlank() && File(expandedKey).exists()) {
jsch.addIdentity(expandedKey)
}
val session = jsch.getSession(user, host, port)
if (password.isNotBlank()) {
session.setPassword(password)
}
session.setConfig("StrictHostKeyChecking", "no")
session.connect(10_000)
return session
}
/** Execute a command over SSH and return stdout + stderr + exit status. */
fun exec(session: Session, command: String): ExecResult {
val channel = session.openChannel("exec") as ChannelExec
channel.setCommand(command)
channel.inputStream = null
val stdout = channel.inputStream
val stderr = channel.errStream
channel.connect(10_000)
val outText = stdout.bufferedReader().readText()
val errText = stderr.bufferedReader().readText()
channel.disconnect()
return ExecResult(
exitStatus = channel.exitStatus,
stdout = outText,
stderr = errText,
)
}
data class ExecResult(
val exitStatus: Int,
val stdout: String,
val stderr: String,
)
private fun prop(sysProp: String, envVar: String): String? {
return System.getProperty(sysProp)?.takeIf { it.isNotBlank() }
?: System.getenv(envVar)?.takeIf { it.isNotBlank() }
}
}