From 2b75a9d66e6baca4c88f46b230b46fba4fd95a26 Mon Sep 17 00:00:00 2001 From: James Babcock Date: Mon, 16 Nov 2026 01:41:12 -0800 Subject: [PATCH] Add an ssh client to Terminal, as an alternative to (or tunnel for) g2mirror --- .gitignore | 2 + .../main/java/com/faceclaw/app/FaceclawSsh.kt | 212 ++++ App_Resources/iOS/src/FaceclawSsh.h | 31 + App_Resources/iOS/src/FaceclawSsh.m | 234 ++++ App_Resources/iOS/src/module.modulemap | 1 + README.md | 6 +- app/apps/terminal/connections.ts | 96 +- app/apps/terminal/terminal-app.worker.ts | 497 +++++++- app/apps/terminal/terminal-client.ts | 44 + app/apps/terminal/tmux-client.ts | 1094 +++++++++++++++++ app/native/g2mirror-client.ts | 63 +- app/native/ssh-common.ts | 153 +++ app/native/ssh.ios.ts | 69 ++ app/native/ssh.ts | 66 + app/native/terminal-session-types.ts | 59 + app/ui/dashboard-settings.ts | 19 +- hooks/before-prepare/faceclaw-kotlin.js | 5 +- .../app/callbacks/FaceclawSshListener.kt | 9 + native/ssh/README.md | 43 + native/ssh/channels.go | 254 ++++ native/ssh/faceclawssh.go | 304 +++++ native/ssh/faceclawssh_test.go | 526 ++++++++ native/ssh/go.mod | 21 + native/ssh/go.sum | 16 + native/ssh/interop_test.go | 58 + native/ssh/keys.go | 91 ++ native/ssh/pool.go | 416 +++++++ scripts/go-ssh-build.cjs | 129 ++ .../hooks/faceclaw-kotlin.before-prepare.js | 5 +- tests/terminal-connections.test.cjs | 56 + tests/terminal-in-place-view.test.cjs | 9 + tests/tmux-client.test.cjs | 202 +++ tests/tsconfig.json | 3 + 33 files changed, 4694 insertions(+), 99 deletions(-) create mode 100644 App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSsh.kt create mode 100644 App_Resources/iOS/src/FaceclawSsh.h create mode 100644 App_Resources/iOS/src/FaceclawSsh.m create mode 100644 app/apps/terminal/terminal-client.ts create mode 100644 app/apps/terminal/tmux-client.ts create mode 100644 app/native/ssh-common.ts create mode 100644 app/native/ssh.ios.ts create mode 100644 app/native/ssh.ts create mode 100644 app/native/terminal-session-types.ts create mode 100644 native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawSshListener.kt create mode 100644 native/ssh/README.md create mode 100644 native/ssh/channels.go create mode 100644 native/ssh/faceclawssh.go create mode 100644 native/ssh/faceclawssh_test.go create mode 100644 native/ssh/go.mod create mode 100644 native/ssh/go.sum create mode 100644 native/ssh/interop_test.go create mode 100644 native/ssh/keys.go create mode 100644 native/ssh/pool.go create mode 100644 scripts/go-ssh-build.cjs create mode 100644 tests/terminal-connections.test.cjs create mode 100644 tests/tmux-client.test.cjs diff --git a/.gitignore b/.gitignore index 326fbf1f..6ecde3ea 100644 --- a/.gitignore +++ b/.gitignore @@ -58,6 +58,8 @@ native/kotlin/.kotlin/ native/kotlin/build/ native/kotlin/shared/build/ native/kotlin/local.properties +# Go SSH transport build outputs (scripts/go-ssh-build.cjs) +native/ssh/build/ native/kotlin/plugin/platforms/android/*.aar native/kotlin/plugin/platforms/ios/ !native/kotlin/plugin/platforms/ diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSsh.kt b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSsh.kt new file mode 100644 index 00000000..4efc7c9d --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSsh.kt @@ -0,0 +1,212 @@ +package com.faceclaw.app + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.security.keystore.StrongBoxUnavailableException +import android.util.Base64 +import android.util.Log +import com.faceclaw.ssh.faceclawssh.Channel +import com.faceclaw.ssh.faceclawssh.Faceclawssh +import com.faceclaw.ssh.faceclawssh.Listener +import com.faceclaw.ssh.faceclawssh.Signer +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.PrivateKey +import java.security.Signature +import java.security.spec.ECGenParameterSpec +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * One SSH channel for the TypeScript side (app/native/ssh.ts), backed by the + * gomobile-bound Go transport in native/ssh. `spec` is the Go openSpec JSON. + * Events arrive from Go goroutines and are posted to the Looper of the + * thread that constructed this object (a JS isolate's own thread), like + * FaceclawWebSocket. + */ +class FaceclawSshChannel(spec: String, useKey: Boolean, listener: FaceclawSshListener) { + private val handler = Handler(Looper.myLooper() ?: Looper.getMainLooper()) + private val channel: Channel + + init { + val signer = if (useKey) FaceclawSshKeys.signer() else null + channel = Faceclawssh.open(spec, signer, object : Listener { + override fun onEvent(kind: String?, payload: String?) { + handler.post { + try { + listener.onEvent(kind, payload) + } catch (t: Throwable) { + Log.w(TAG, "listener onEvent($kind) failed", t) + } + } + } + }) + } + + fun send(text: String): Boolean = channel.send(text) + + fun close() = channel.close() + + private companion object { + const val TAG = "FaceclawSsh" + } +} + +/** + * The device's SSH client key and the Terminal app's saved SSH passwords. + * + * The client key is an ECDSA P-256 key generated inside Android Keystore + * (StrongBox when the device has one) and never exportable: only its public + * half leaves the keystore, as an authorized_keys line. Passwords are + * encrypted with an AES-GCM key that also lives in Keystore, and stored in a + * private SharedPreferences file kept apart from the settings store (which is + * exported by the settings port). + */ +object FaceclawSshKeys { + private const val TAG = "FaceclawSsh" + private const val CLIENT_KEY_ALIAS = "faceclaw-ssh-client" + private const val SECRET_KEY_ALIAS = "faceclaw-ssh-secrets" + private const val SECRETS_PREFS = "faceclaw_ssh_secrets" + private const val GCM_TAG_BITS = 128 + + private fun keyStore(): KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + + @JvmStatic + @Synchronized + fun hasClientKey(): Boolean = keyStore().containsAlias(CLIENT_KEY_ALIAS) + + /** Generate the client key if it doesn't exist yet. */ + @JvmStatic + @Synchronized + fun ensureClientKey() { + if (keyStore().containsAlias(CLIENT_KEY_ALIAS)) return + fun spec(strongBox: Boolean): KeyGenParameterSpec { + val builder = KeyGenParameterSpec.Builder(CLIENT_KEY_ALIAS, KeyProperties.PURPOSE_SIGN) + .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1")) + .setDigests(KeyProperties.DIGEST_SHA256) + if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) builder.setIsStrongBoxBacked(true) + return builder.build() + } + val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore") + try { + generator.initialize(spec(strongBox = true)) + generator.generateKeyPair() + } catch (e: Exception) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && e is StrongBoxUnavailableException) { + Log.i(TAG, "StrongBox unavailable; generating the SSH key in the TEE") + } else { + Log.w(TAG, "StrongBox key generation failed; retrying in the TEE", e) + } + generator.initialize(spec(strongBox = false)) + generator.generateKeyPair() + } + Log.i(TAG, "generated SSH client key") + } + + /** X.509 SubjectPublicKeyInfo DER of the client key, or null if none. */ + @JvmStatic + fun publicKey(): ByteArray? = keyStore().getCertificate(CLIENT_KEY_ALIAS)?.publicKey?.encoded + + /** The client key's authorized_keys line (generating the key if needed). */ + @JvmStatic + fun authorizedKey(comment: String): String { + ensureClientKey() + return Faceclawssh.authorizedKey(publicKey(), comment) + } + + /** The client key's SHA256 fingerprint (generating the key if needed). */ + @JvmStatic + fun fingerprint(): String { + ensureClientKey() + return Faceclawssh.fingerprint(publicKey()) + } + + /** A Go Signer over the client key, generating the key if needed. */ + @JvmStatic + fun signer(): Signer? = try { + ensureClientKey() + val publicKey = publicKey() ?: throw IllegalStateException("client key has no certificate") + object : Signer { + override fun publicKey(): ByteArray = publicKey + override fun sign(data: ByteArray?): ByteArray { + val privateKey = keyStore().getKey(CLIENT_KEY_ALIAS, null) as PrivateKey + return Signature.getInstance("SHA256withECDSA").run { + initSign(privateKey) + update(data ?: ByteArray(0)) + sign() + } + } + } + } catch (t: Throwable) { + Log.w(TAG, "SSH client key unavailable", t) + null + } + + private fun secretKey(): SecretKey { + val store = keyStore() + (store.getKey(SECRET_KEY_ALIAS, null) as? SecretKey)?.let { return it } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init( + KeyGenParameterSpec.Builder(SECRET_KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build() + ) + return generator.generateKey() + } + + private fun prefs(context: Context) = + context.applicationContext.getSharedPreferences(SECRETS_PREFS, Context.MODE_PRIVATE) + + @JvmStatic + @Synchronized + fun setSecret(context: Context, id: String, value: String) { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, secretKey()) + val sealed = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8)) + prefs(context).edit().putString(id, Base64.encodeToString(sealed, Base64.NO_WRAP)).apply() + } + + /** The saved secret, or "" if none (or it can no longer be decrypted). */ + @JvmStatic + @Synchronized + fun getSecret(context: Context, id: String): String { + val encoded = prefs(context).getString(id, null) ?: return "" + return try { + val sealed = Base64.decode(encoded, Base64.NO_WRAP) + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val ivLength = 12 + cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, sealed, 0, ivLength)) + String(cipher.doFinal(sealed, ivLength, sealed.size - ivLength), Charsets.UTF_8) + } catch (t: Throwable) { + Log.w(TAG, "saved SSH secret unreadable; dropping it", t) + prefs(context).edit().remove(id).apply() + "" + } + } + + @JvmStatic + @Synchronized + fun removeSecret(context: Context, id: String) { + prefs(context).edit().remove(id).apply() + } + + /** Put text on the phone's clipboard (from any thread). */ + @JvmStatic + fun copyToClipboard(context: Context, label: String, text: String) { + val appContext = context.applicationContext + Handler(Looper.getMainLooper()).post { + val clipboard = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(ClipData.newPlainText(label, text)) + } + } +} diff --git a/App_Resources/iOS/src/FaceclawSsh.h b/App_Resources/iOS/src/FaceclawSsh.h new file mode 100644 index 00000000..cf8a479a --- /dev/null +++ b/App_Resources/iOS/src/FaceclawSsh.h @@ -0,0 +1,31 @@ +#import + +/** + * One SSH channel for the TypeScript side (app/native/ssh.ios.ts), backed by + * the gomobile-bound Go transport in native/ssh. `spec` is the Go openSpec + * JSON. Events arrive on Go threads and queue here; the owning JS isolate + * drains them with takeEvents (a JSON array of {kind, payload}). + */ +@interface FaceclawSshChannel : NSObject +- (instancetype)initWithSpec:(NSString *)spec useKey:(BOOL)useKey; +- (NSString *)takeEvents; +- (BOOL)send:(NSString *)text; +- (void)close; +@end + +/** + * The device's SSH client key (a non-exportable Secure Enclave P-256 key; a + * plain keychain key on the simulator, which has no Secure Enclave) and the + * Terminal app's saved SSH passwords (keychain generic passwords). + */ +@interface FaceclawSshKeys : NSObject +/** "ecdsa-sha2-nistp256 AAAA... comment"; generates the key if needed. nil on failure. */ ++ (NSString *)authorizedKeyWithComment:(NSString *)comment; +/** "SHA256:..." fingerprint; generates the key if needed. nil on failure. */ ++ (NSString *)fingerprint; ++ (void)setSecret:(NSString *)value forId:(NSString *)secretId; +/** The saved secret, or "" if none. */ ++ (NSString *)secretForId:(NSString *)secretId; ++ (void)removeSecretForId:(NSString *)secretId; ++ (void)copyToClipboard:(NSString *)text; +@end diff --git a/App_Resources/iOS/src/FaceclawSsh.m b/App_Resources/iOS/src/FaceclawSsh.m new file mode 100644 index 00000000..492707f5 --- /dev/null +++ b/App_Resources/iOS/src/FaceclawSsh.m @@ -0,0 +1,234 @@ +#import "FaceclawSsh.h" +#import +#import +#import + +static NSString *const kClientKeyTag = @"com.faceclaw.ssh.client"; +static NSString *const kSecretService = @"com.faceclaw.ssh.secret"; + +#pragma mark - Client key + +static NSData *ClientKeyTagData(void) { + return [kClientKeyTag dataUsingEncoding:NSUTF8StringEncoding]; +} + +static SecKeyRef CopyClientKey(void) { + NSDictionary *query = @{ + (id)kSecClass: (id)kSecClassKey, + (id)kSecAttrApplicationTag: ClientKeyTagData(), + (id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom, + (id)kSecReturnRef: @YES, + }; + CFTypeRef key = NULL; + if (SecItemCopyMatching((__bridge CFDictionaryRef)query, &key) != errSecSuccess) return NULL; + return (SecKeyRef)key; +} + +static SecKeyRef CreateClientKey(BOOL secureEnclave) { + SecAccessControlRef access = SecAccessControlCreateWithFlags( + kCFAllocatorDefault, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + secureEnclave ? kSecAccessControlPrivateKeyUsage : 0, NULL); + if (!access) return NULL; + NSMutableDictionary *attributes = [@{ + (id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom, + (id)kSecAttrKeySizeInBits: @256, + (id)kSecPrivateKeyAttrs: @{ + (id)kSecAttrIsPermanent: @YES, + (id)kSecAttrApplicationTag: ClientKeyTagData(), + (id)kSecAttrAccessControl: (__bridge id)access, + }, + } mutableCopy]; + if (secureEnclave) attributes[(id)kSecAttrTokenID] = (id)kSecAttrTokenIDSecureEnclave; + CFErrorRef error = NULL; + SecKeyRef key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes, &error); + CFRelease(access); + if (!key && error) { + NSLog(@"FaceclawSsh: key generation failed (secure enclave %d): %@", secureEnclave, (__bridge NSError *)error); + CFRelease(error); + } + return key; +} + +/** The client key, generating it on first use. Caller releases. */ +static SecKeyRef CopyOrCreateClientKey(void) { + @synchronized([FaceclawSshKeys class]) { + SecKeyRef key = CopyClientKey(); + if (key) return key; + key = CreateClientKey(YES); +#if TARGET_OS_SIMULATOR + if (!key) key = CreateClientKey(NO); +#endif + return key; + } +} + +/** Uncompressed X9.62 public point (0x04 || X || Y). */ +static NSData *PublicKeyData(SecKeyRef key) { + SecKeyRef publicKey = SecKeyCopyPublicKey(key); + if (!publicKey) return nil; + NSData *data = (__bridge_transfer NSData *)SecKeyCopyExternalRepresentation(publicKey, NULL); + CFRelease(publicKey); + return data; +} + +@interface FaceclawSshSigner : NSObject +@end + +@implementation FaceclawSshSigner { + SecKeyRef _key; + NSData *_publicKey; +} +- (instancetype)initWithKey:(SecKeyRef)key { + if ((self = [super init])) { + _key = (SecKeyRef)CFRetain(key); + _publicKey = PublicKeyData(key); + } + return self; +} +- (void)dealloc { + if (_key) CFRelease(_key); +} +- (NSData *)publicKey { + return _publicKey; +} +- (NSData *)sign:(NSData *)data error:(NSError **)error { + CFErrorRef cfError = NULL; + NSData *signature = (__bridge_transfer NSData *)SecKeyCreateSignature( + _key, kSecKeyAlgorithmECDSASignatureMessageX962SHA256, (__bridge CFDataRef)(data ?: [NSData data]), &cfError); + if (!signature) { + if (error) *error = (__bridge_transfer NSError *)cfError; + else if (cfError) CFRelease(cfError); + } + return signature; +} +@end + +#pragma mark - Channel + +@interface FaceclawSshEventQueue : NSObject +@property(nonatomic, strong) NSMutableArray *events; +@property(nonatomic) BOOL ended; +@end + +@implementation FaceclawSshEventQueue +- (instancetype)init { + if ((self = [super init])) _events = [NSMutableArray array]; + return self; +} +- (void)onEvent:(NSString *)kind payload:(NSString *)payload { + @synchronized(self) { + if (_ended) return; + [_events addObject:@{@"kind": kind ?: @"", @"payload": payload ?: @""}]; + } +} +@end + +@implementation FaceclawSshChannel { + FaceclawsshChannel *_channel; + FaceclawSshEventQueue *_queue; +} + +- (instancetype)initWithSpec:(NSString *)spec useKey:(BOOL)useKey { + if ((self = [super init])) { + _queue = [FaceclawSshEventQueue new]; + FaceclawSshSigner *signer = nil; + if (useKey) { + SecKeyRef key = CopyOrCreateClientKey(); + if (key) { + signer = [[FaceclawSshSigner alloc] initWithKey:key]; + CFRelease(key); + } + } + _channel = FaceclawsshOpen(spec, signer, _queue); + } + return self; +} + +- (NSString *)takeEvents { + NSArray *events; + @synchronized(_queue) { + if (_queue.events.count == 0) return @"[]"; + events = [_queue.events copy]; + [_queue.events removeAllObjects]; + } + NSData *data = [NSJSONSerialization dataWithJSONObject:events options:0 error:nil]; + return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"[]"; +} + +- (BOOL)send:(NSString *)text { + return [_channel send:text]; +} + +- (void)close { + @synchronized(_queue) { + _queue.ended = YES; + [_queue.events removeAllObjects]; + } + [_channel close]; +} +@end + +#pragma mark - Keys and secrets + +@implementation FaceclawSshKeys + ++ (NSString *)authorizedKeyWithComment:(NSString *)comment { + SecKeyRef key = CopyOrCreateClientKey(); + if (!key) return nil; + NSData *publicKey = PublicKeyData(key); + CFRelease(key); + NSError *error = nil; + NSString *line = FaceclawsshAuthorizedKey(publicKey, comment ?: @"", &error); + if (error) NSLog(@"FaceclawSsh: authorizedKey failed: %@", error); + return line; +} + ++ (NSString *)fingerprint { + SecKeyRef key = CopyOrCreateClientKey(); + if (!key) return nil; + NSData *publicKey = PublicKeyData(key); + CFRelease(key); + NSError *error = nil; + NSString *fingerprint = FaceclawsshFingerprint(publicKey, &error); + if (error) NSLog(@"FaceclawSsh: fingerprint failed: %@", error); + return fingerprint; +} + ++ (NSDictionary *)secretQuery:(NSString *)secretId { + return @{ + (id)kSecClass: (id)kSecClassGenericPassword, + (id)kSecAttrService: kSecretService, + (id)kSecAttrAccount: secretId ?: @"", + }; +} + ++ (void)setSecret:(NSString *)value forId:(NSString *)secretId { + NSDictionary *query = [self secretQuery:secretId]; + SecItemDelete((__bridge CFDictionaryRef)query); + NSMutableDictionary *item = [query mutableCopy]; + item[(id)kSecValueData] = [(value ?: @"") dataUsingEncoding:NSUTF8StringEncoding]; + item[(id)kSecAttrAccessible] = (id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly; + OSStatus status = SecItemAdd((__bridge CFDictionaryRef)item, NULL); + if (status != errSecSuccess) NSLog(@"FaceclawSsh: saving secret failed: %d", (int)status); +} + ++ (NSString *)secretForId:(NSString *)secretId { + NSMutableDictionary *query = [[self secretQuery:secretId] mutableCopy]; + query[(id)kSecReturnData] = @YES; + query[(id)kSecMatchLimit] = (id)kSecMatchLimitOne; + CFTypeRef result = NULL; + if (SecItemCopyMatching((__bridge CFDictionaryRef)query, &result) != errSecSuccess) return @""; + NSData *data = (__bridge_transfer NSData *)result; + return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @""; +} + ++ (void)removeSecretForId:(NSString *)secretId { + SecItemDelete((__bridge CFDictionaryRef)[self secretQuery:secretId]); +} + ++ (void)copyToClipboard:(NSString *)text { + dispatch_async(dispatch_get_main_queue(), ^{ + UIPasteboard.generalPasteboard.string = text ?: @""; + }); +} +@end diff --git a/App_Resources/iOS/src/module.modulemap b/App_Resources/iOS/src/module.modulemap index 9bc01ad2..41e90570 100644 --- a/App_Resources/iOS/src/module.modulemap +++ b/App_Resources/iOS/src/module.modulemap @@ -2,6 +2,7 @@ module FaceclawGraphics { header "FaceclawGraphics.h" header "FaceclawFontRenderer.h" header "FaceclawSocket.h" + header "FaceclawSsh.h" header "FaceclawLc3Decoder.h" header "FaceclawSpeech.h" header "FaceclawLocation.h" diff --git a/README.md b/README.md index fc17edc5..fd27e4de 100644 --- a/README.md +++ b/README.md @@ -80,8 +80,10 @@ import it into the new version (see [config transfer](scripts/config-transfer.md * **Integration with Android notifications**: shows the same notification icons your phone does, and popups when notifications arrive. * **Terminal mirroring.** Mirror terminal apps such as Claude Code or Codex - CLI with [g2mirror](https://github.com/jimrandomh/g2mirror), view them on - the glasses, and send them inputs with the voice assistant. + CLI with [g2mirror](https://github.com/jimrandomh/g2mirror), or attach to + tmux sessions over SSH (no server-side setup beyond tmux 3.2+), view them + on the glasses, and send them inputs with the voice assistant. g2mirror + can also be tunnelled over SSH instead of a VPN. * **Media player controls** including playlist and media library navigation, compatible with most Android media players. * **Turn-by-turn directions** (requires a Mapbox API token). diff --git a/app/apps/terminal/connections.ts b/app/apps/terminal/connections.ts index aeb1fec8..f53cb650 100644 --- a/app/apps/terminal/connections.ts +++ b/app/apps/terminal/connections.ts @@ -1,13 +1,21 @@ import { getStringSetting, setStringSetting } from "../../native/settings-store"; /** - * Terminal-app connection registry: the g2mirror hosts the app knows about, - * stored as JSON under one settings key so every isolate sees the same list - * and change notifications ride the ordinary settings-store channel. + * Terminal-app connection registry: the hosts the app knows about, stored as + * JSON under one settings key so every isolate sees the same list and change + * notifications ride the ordinary settings-store channel. * - * A connection is entered as a g2mirror:// connection string (the same form - * g2mirror-view accepts): g2mirror://@[:port] for plain - * websockets (default port 8737), g2mirrors://... for TLS (default 443). + * A connection is entered as a connection string: + * - g2mirror://@[:port]: a g2mirror server reached directly + * (the same form g2mirror-view accepts) over a plain websocket (default + * port 8737); g2mirrors://... for TLS (default 443). + * - ssh://@[:port]: tmux on an SSH host (default port 22). + * - ssh://@[:port]?g2mirror=[@[:port]]: a g2mirror + * server tunnelled over SSH; the address after the token is where the + * server listens as seen from the SSH host (default 127.0.0.1:8737). + * SSH connections pin the host's key (hostKeys, trusted on first connection + * after the user checks its fingerprint); their passwords live in the + * platform keystore (app/native/ssh), not here. */ export const TERMINAL_CONNECTIONS_KEY = "terminal.connections"; @@ -25,6 +33,8 @@ export type TerminalConnection = { serverName: string | null; /** Auto-connect while the Terminal app is open. Toggled by Connect/Disconnect. */ enabled: boolean; + /** SSH connections: trusted host keys (SSH wire format, base64). */ + hostKeys: string[]; }; export type ParsedConnectionString = { @@ -54,8 +64,79 @@ export function parseConnectionString(url: string): ParsedConnectionString | nul return { secure, host, port, authToken }; } -/** The host[:port] part of a connection string; "" if it doesn't parse. */ +export type ParsedSshConnection = { + user: string; + host: string; + port: number; +} & ( + | { mode: "tmux" } + | { + mode: "g2mirror"; + authToken: string; + /** Where g2mirror-server listens, from the SSH host's point of view. */ + targetHost: string; + targetPort: number; + } +); + +function decodeComponent(text: string): string { + try { + return decodeURIComponent(text); + } catch { + return text; + } +} + +/** Parse an ssh://user@host[:port][?g2mirror=token[@host[:port]]] string; null if malformed. */ +export function parseSshConnectionString(url: string): ParsedSshConnection | null { + const match = /^ssh:\/\/([^@\s/?]+)@(\[[^\]\s]+\]|[^:/@\s?]+)(?::(\d+))?\/?(?:\?(.*))?$/.exec(url.trim()); + if (!match) return null; + const user = decodeComponent(match[1]!); + const host = match[2]!.replace(/^\[(.*)\]$/, "$1"); + const port = match[3] ? parseInt(match[3], 10) : 22; + if (!user || !(port >= 1 && port <= 65535)) return null; + const params = new Map(); + for (const part of (match[4] ?? "").split("&").filter(Boolean)) { + const equals = part.indexOf("="); + if (equals < 0) return null; + params.set(part.slice(0, equals), decodeComponent(part.slice(equals + 1))); + } + for (const key of params.keys()) { + if (key !== "g2mirror") return null; + } + const g2mirror = params.get("g2mirror"); + if (g2mirror === undefined) return { user, host, port, mode: "tmux" }; + // token[@host[:port]], split at the last "@" so the token may contain one. + const at = g2mirror.lastIndexOf("@"); + const authToken = at < 0 ? g2mirror : g2mirror.slice(0, at); + const target = at < 0 ? "" : g2mirror.slice(at + 1); + const targetMatch = /^(\[[^\]\s]+\]|[^:\s]*)(?::(\d+))?$/.exec(target); + if (!authToken || !targetMatch) return null; + const targetHost = targetMatch[1] || "127.0.0.1"; + const targetPort = targetMatch[2] ? parseInt(targetMatch[2], 10) : 8737; + if (!(targetPort >= 1 && targetPort <= 65535)) return null; + return { user, host, port, mode: "g2mirror", authToken, targetHost, targetPort }; +} + +export type ParsedAnyConnection = + | ({ kind: "g2mirror" } & ParsedConnectionString) + | ({ kind: "ssh" } & ParsedSshConnection); + +/** Parse any supported connection string; null if it's none of them. */ +export function parseAnyConnectionString(url: string): ParsedAnyConnection | null { + const direct = parseConnectionString(url); + if (direct) return { kind: "g2mirror", ...direct }; + const ssh = parseSshConnectionString(url); + return ssh ? { kind: "ssh", ...ssh } : null; +} + +/** The [user@]host[:port] part of a connection string (never a token); "" if it doesn't parse. */ export function connectionStringHostLabel(url: string): string { + const ssh = parseSshConnectionString(url); + if (ssh) { + const host = ssh.host.includes(":") ? `[${ssh.host}]` : ssh.host; + return `${ssh.user}@${host}${ssh.port === 22 ? "" : `:${ssh.port}`}`; + } const parsed = parseConnectionString(url); if (!parsed) return ""; const defaultPort = parsed.secure ? 443 : 8737; @@ -79,6 +160,7 @@ export function loadConnections(): TerminalConnection[] { url: String(item?.url ?? ""), serverName: typeof item?.serverName === "string" && item.serverName ? item.serverName : null, enabled: item?.enabled !== false, + hostKeys: Array.isArray(item?.hostKeys) ? item.hostKeys.filter((key: unknown) => typeof key === "string") : [], })) .filter((connection) => connection.id.length > 0 && connection.url.length > 0); } catch { diff --git a/app/apps/terminal/terminal-app.worker.ts b/app/apps/terminal/terminal-app.worker.ts index 2445895f..051b1a0f 100644 --- a/app/apps/terminal/terminal-app.worker.ts +++ b/app/apps/terminal/terminal-app.worker.ts @@ -16,11 +16,17 @@ * Each view has its own websocket connection (the protocol allows one attached * session per connection) and its own xterm emulator. * - * Connections are g2mirror://@[:port] strings (g2mirrors:// for - * TLS), stored as JSON in the settings store (see connections.ts). Each - * enabled connection gets a control websocket that backs the session list and - * carries unsolicited bell/title notifications; control connections live as - * long as the worker so bells keep flowing even if the hub window is closed. + * Connections are connection strings stored as JSON in the settings store + * (see connections.ts): g2mirror://@[:port] for a g2mirror + * server (g2mirrors:// for TLS), ssh://@ for tmux over SSH + * (TmuxClient), or ssh://@?g2mirror= for a g2mirror server + * tunnelled over SSH. Each enabled connection gets a control client that + * backs the session list and carries bell/title/activity notifications; + * control connections live as long as the worker so bells keep flowing even + * if the hub window is closed. SSH connections that need the user (an + * unverified or changed host key, a password, an unauthorized key) record + * the failure on the control (sshIssue) and offer a page that resolves it + * instead of retrying. * The host's server_name (from the init reply) is cached per connection and * used as its display name, falling back to the connection string's * host[:port] before the first successful handshake. @@ -57,7 +63,22 @@ import { getActiveDisplay } from "../../native/active-display"; import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures"; import type { KeyEvent } from "../../g2/keyboard/keys"; import { encodeTerminalKey, terminalScrollbackKey } from "./terminal-keys"; -import { G2MirrorClient, type G2MirrorClientOptions, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client"; +import { G2MirrorClient, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client"; +import type { TerminalClient } from "./terminal-client"; +import { TmuxClient, type OpenLineChannel } from "./tmux-client"; +import { + copyToPhoneClipboard, + describeSshFailure, + getSshSecret, + openSshChannel, + removeSshSecret, + setSshSecret, + sshClientKey, + type SshEndpoint, + type SshFailure, + type SshHostKey, +} from "../../native/ssh"; +import { wrapText } from "../../graphics/textwrap"; import { onSettingsStoreChanged } from "../../native/settings-store"; import { clamp } from "../../util/numeric-util"; import { @@ -66,12 +87,22 @@ import { terminalDisplayLayoutSetting, terminalLaunchPresetsSetting, terminalNewConnectionSetting, + terminalSshPasswordSetting, terminalWakeOnBellSetting, textSettingMenuItem, toggleSettingMenuItem, } from "../../ui/dashboard-settings"; import { terminalFontPickerMenuItem } from "../../ui/font-picker"; -import { connectionDisplayName, loadConnections, parseConnectionString, saveConnections, TERMINAL_CONNECTIONS_KEY, updateConnection, type TerminalConnection } from "./connections"; +import { + connectionDisplayName, + connectionStringHostLabel, + loadConnections, + parseAnyConnectionString, + saveConnections, + TERMINAL_CONNECTIONS_KEY, + updateConnection, + type TerminalConnection, +} from "./connections"; import { TerminalEmulator } from "./terminal-emulator"; import { drawSubmenuIndicator, submenuItem, type MenuItem } from "../../ui/menu"; import { Menu, type MenuDrawArgs } from "../../ui/menu-core"; @@ -114,6 +145,10 @@ const RECONNECT_MAX_DELAY_MS = 60_000; const NEW_CONNECTION_DRAFT_KEY = "terminal.newConnectionDraft"; // Storage key of terminalLaunchPresetsSetting, edited from the window menu. const LAUNCH_PRESETS_KEY = "terminal.launchPresets"; +// Storage key of terminalSshPasswordSetting (the password page's draft). +const SSH_PASSWORD_DRAFT_KEY = "terminal.sshPasswordDraft"; +// Comment on this device's SSH public key in authorized_keys. +const SSH_KEY_COMMENT = "faceclaw"; type BaseWindow = { windowId: string; @@ -150,10 +185,24 @@ type BaseWindow = { /** * What the hub window is showing: the session list, the Manage Connections - * section, or the Add-connection screen (type the g2mirror:// string on the - * phone, click to save). + * section, the Add-connection screen (type the connection string on the + * phone, click to save), or a page of text with a click action (verify a + * host key, enter a password, show this device's SSH key). */ -type HubMode = "sessions" | "connections" | "add"; +type HubMode = "sessions" | "connections" | "add" | "page"; + +type HubPage = { + title: string; + /** Body text, wrapped to the window; re-read on every paint. */ + body: () => string; + /** Bottom hint line. */ + hint: string; + onClick?: () => void; + /** Double-click. */ + onBack: () => void; + /** Runs whenever the page goes away (back, click, window closed). */ + onLeave?: () => void; +}; type HubWindow = BaseWindow & { kind: "hub"; @@ -170,6 +219,8 @@ type HubWindow = BaseWindow & { sessionOrder: string[]; /** Parse-failure message shown on the Add-connection screen. */ addError: string; + /** The page shown in mode "page". */ + page: HubPage | null; }; type ViewWindow = BaseWindow & { @@ -188,7 +239,7 @@ type ViewWindow = BaseWindow & { label: string; /** Sidebar-icon character (">3"); "" if every glyph was taken at open time. */ glyph: string; - client: G2MirrorClient; + client: TerminalClient; emulator: TerminalEmulator; receivedData: boolean; attachRequested: boolean; @@ -222,8 +273,8 @@ type PendingView = { socket: string; label: string; glyph: string; - /** Client options captured when the view was requested from a live control. */ - options: G2MirrorClientOptions; + /** How to make the view's client, captured when it was requested from a live control. */ + options: ClientRecipe; }; const windows = new Map(); @@ -304,7 +355,13 @@ let screenOn = true; */ type ControlConnection = { config: TerminalConnection; - client: G2MirrorClient | null; + client: TerminalClient | null; + /** + * An SSH failure only the user can fix (host key to verify, password or + * key needed). Shown on the host's heading with a row that opens the fix; + * reconnects wait for it. Cleared on a successful connection. + */ + sshIssue: SshFailure | null; state: G2MirrorState | null; unsubscribers: Array<() => void>; reconnectTimer: ReturnType | null; @@ -513,7 +570,8 @@ onSettingsStoreChanged((key) => { reportIdle(); return; case NEW_CONNECTION_DRAFT_KEY: - // Live keystrokes from the phone editor; repaint the add screen. + case SSH_PASSWORD_DRAFT_KEY: + // Live keystrokes from the phone editor; repaint the add/password screen. renderHubWindows(); return; case "terminal.autoReconnect": @@ -587,6 +645,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport list: null, sessionOrder: [], addError: "", + page: null, }); // The hub carries the app's assistant tools; declare them once it exists. post({ type: "set-tools", windowId, tools: TERMINAL_TOOLS }); @@ -619,6 +678,10 @@ function closeWindow(windowId: string): void { // Window closed mid-add: shut the phone editor down. endAddConnection(window); } + if (window.kind === "hub" && window.mode === "page") { + // Likewise for a page's phone editor (the password draft). + closeHubPage(window, "sessions"); + } // Likewise for a setting being edited from the window menu. window.menu?.close(); windows.delete(windowId); @@ -636,17 +699,120 @@ function closeWindow(windowId: string): void { } } -/** Client options for a connection string; null if the string doesn't parse. */ -function clientOptionsFor(connection: TerminalConnection): G2MirrorClientOptions | null { - const parsed = parseConnectionString(connection.url); +/** + * How to make clients for a connection: "g2mirror" dials a g2mirror server + * directly, "ssh-g2mirror" reaches one through an SSH tunnel, "tmux" runs + * tmux control mode over SSH. + */ +type ClientRecipe = { + kind: "g2mirror" | "ssh-g2mirror" | "tmux"; + /** + * `role` "control" watches bells (tmux keeps the bell bookkeeping for that + * client only). `onSshFailure` hears why an SSH channel failed. + */ + create(cols: number, rows: number, role: "control" | "view", onSshFailure?: (failure: SshFailure) => void): TerminalClient; +}; + +/** Client recipe for a connection string; null if the string doesn't parse. */ +function clientOptionsFor(connection: TerminalConnection): ClientRecipe | null { + const parsed = parseAnyConnectionString(connection.url); if (!parsed) return null; + if (parsed.kind === "g2mirror") { + const { secure, host, port, authToken } = parsed; + return { + kind: "g2mirror", + create: (cols, rows) => new G2MirrorClient({ secure, host, port, authToken, deviceName: DEVICE_NAME, cols, rows }), + }; + } + const connectionId = connection.id; + const label = connectionStringHostLabel(connection.url); + // Read at every channel open, so a newly trusted key or saved password + // applies to the next (re)connect, views included. + const endpoint = (): SshEndpoint => ({ + host: parsed.host, + port: parsed.port, + user: parsed.user, + hostKeys: loadConnections().find((candidate) => candidate.id === connectionId)?.hostKeys ?? [], + password: getSshSecret(sshPasswordSecretId(connectionId)), + useKey: true, + }); + if (parsed.mode === "g2mirror") { + const { authToken, targetHost, targetPort } = parsed; + const urlHost = targetHost.includes(":") && !targetHost.startsWith("[") ? `[${targetHost}]` : targetHost; + const url = `ws://${urlHost}:${targetPort}/`; + return { + kind: "ssh-g2mirror", + create: (cols, rows, _role, onSshFailure) => + new G2MirrorClient({ + secure: false, + host: targetHost, + port: targetPort, + authToken, + deviceName: DEVICE_NAME, + cols, + rows, + transport: { + label: `${label} over SSH`, + open: (listener) => { + const channel = openSshChannel(endpoint(), { type: "websocket", url }, { + onOpen: () => listener.onOpen(), + onText: (text) => listener.onTextMessage(text), + onClosed: (info) => listener.onClosed(info.code ?? 1000, info.reason ?? ""), + onFailure: (failure) => { + onSshFailure?.(failure); + listener.onFailure(describeSshFailure(failure)); + }, + }); + return { sendText: (text) => channel.send(text), sendBinary: () => false, close: () => channel.close() }; + }, + }, + }), + }; + } return { - ...parsed, - deviceName: DEVICE_NAME, - ...viewGrid(), + kind: "tmux", + create: (cols, rows, role, onSshFailure) => { + const openChannel: OpenLineChannel = (command, listener) => + openSshChannel(endpoint(), { type: "exec", command }, { + onOpen: () => listener.onOpen(), + onText: (line) => listener.onLine(line), + onStderr: (line) => listener.onStderr(line), + onClosed: (info) => listener.onClosed(info.exitStatus ?? null), + onFailure: (failure) => { + onSshFailure?.(failure); + listener.onFailure(describeSshFailure(failure)); + }, + }); + return new TmuxClient({ openChannel, label, cols, rows, stateKey: role === "control" ? connectionId : "" }); + }, }; } +function sshPasswordSecretId(connectionId: string): string { + return `terminal.password.${connectionId}`; +} + +/** Failures that retrying can't fix: the user has to verify a key or supply credentials. */ +function sshFailureNeedsUser(failure: SshFailure): boolean { + return failure.kind === "hostkey-unknown" || failure.kind === "hostkey-mismatch" || failure.kind === "auth"; +} + +/** + * A control's SSH channel failed. If the user has to act, remember why, and + * if they're looking at the hub's lists, open the page that fixes it. + */ +function noteSshFailure(control: ControlConnection, failure: SshFailure): void { + if (!sshFailureNeedsUser(failure) || controls.get(control.config.id) !== control || !control.client) return; + control.sshIssue = failure; + renderHubWindows(); + for (const window of windows.values()) { + if (window.kind === "hub" && window.foreground && (window.mode === "sessions" || window.mode === "connections")) { + openSshIssuePage(window, control); + break; + } + } +} + /** * Reconcile the live control clients with the stored connection list: start * enabled connections, stop disabled or removed ones, restart ones whose @@ -672,6 +838,7 @@ function syncControlsFromSettings(): void { control = { config: connection, client: null, + sshIssue: null, state: null, unsubscribers: [], reconnectTimer: null, @@ -693,12 +860,13 @@ function syncControlsFromSettings(): void { function startControl(control: ControlConnection): void { stopControl(control); - const options = clientOptionsFor(control.config); - if (!options) { + const recipe = clientOptionsFor(control.config); + if (!recipe) { control.state = null; return; } - const client = new G2MirrorClient(options); + const grid = viewGrid(); + const client = recipe.create(grid.cols, grid.rows, "control", (failure) => noteSshFailure(control, failure)); const connectionId = control.config.id; control.client = client; control.state = client.state(); @@ -712,6 +880,7 @@ function startControl(control: ControlConnection): void { control.state = state; if (state.phase === "connected") { control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS; + control.sshIssue = null; maybeCacheServerName(control, state.serverName); } if (state.phase === "failed") scheduleControlReconnect(control); @@ -786,6 +955,8 @@ function scheduleControlReconnect(control: ControlConnection): void { if (!terminalAutoReconnectSetting.get()) return; if (windows.size === 0 && !hasTerminalBackgroundWork()) return; if (!control.config.enabled) return; + // Waiting on the user (host key, password) or on the host (no usable tmux). + if (control.sshIssue || control.state?.retryable === false) return; const delayMs = control.reconnectDelayMs; control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS); control.reconnectTimer = setTimeout(() => { @@ -952,7 +1123,7 @@ function createViewWindow( const cell = getTerminalFontConfig(); const gridCols = Math.floor(viewport.width / cell.cellWidth); const gridRows = Math.floor(viewport.height / cell.cellHeight); - const client = new G2MirrorClient({ ...view.options, cols: gridCols, rows: gridRows }); + const client = view.options.create(gridCols, gridRows, "view"); const window: ViewWindow = { kind: "view", hub: null, @@ -1247,6 +1418,11 @@ function handleInput(window: TerminalWindow, event: InputEvent, frameId: number) renderAndSubmit(window, frameId); return; } + if (window.kind === "hub" && window.mode === "page") { + window.page?.onBack(); + renderAndSubmit(window, frameId); + return; + } if (window.kind === "hub" && window.mode === "connections") { setHubMode(window, "sessions"); renderAndSubmit(window, frameId); @@ -1424,6 +1600,154 @@ function setHubMode(window: HubWindow, mode: HubMode): void { window.addError = ""; } +function openHubPage(window: HubWindow, page: HubPage): void { + if (window.mode === "add") endAddConnection(window); + if (window.mode === "page") window.page?.onLeave?.(); + window.page = page; + window.mode = "page"; + scheduleRender(window); +} + +/** Leave the current page (if any) for `mode`. */ +function closeHubPage(window: HubWindow, mode: HubMode): void { + const page = window.page; + window.page = null; + page?.onLeave?.(); + setHubMode(window, mode); + scheduleRender(window); +} + +/** The list a page returns to: the one it was opened from. */ +function hubListMode(window: HubWindow): HubMode { + return window.mode === "connections" ? "connections" : "sessions"; +} + +function openSshIssuePage(window: HubWindow, control: ControlConnection): void { + const issue = control.sshIssue; + if (!issue) return; + if (issue.kind === "hostkey-unknown" && issue.hostKey) { + openHostKeyPage(window, control, issue.hostKey); + } else if (issue.kind === "hostkey-mismatch" && issue.hostKey) { + openHostKeyChangedPage(window, control, issue.hostKey); + } else if (issue.kind === "auth" && issue.passwordAllowed) { + openPasswordPage(window, control, Boolean(issue.passwordTried)); + } else if (issue.kind === "auth") { + openClientKeyPage(window, `${connectionDisplayName(control.config)} didn't accept this device's key (and doesn't take passwords).\n`); + } +} + +function hostKeyTypeName(type: string): string { + if (type === "ssh-ed25519") return "ED25519"; + if (type.startsWith("ecdsa-")) return "ECDSA"; + if (type === "ssh-rsa") return "RSA"; + return type; +} + +function hostKeyFile(type: string): string { + if (type === "ssh-ed25519") return "/etc/ssh/ssh_host_ed25519_key.pub"; + if (type.startsWith("ecdsa-")) return "/etc/ssh/ssh_host_ecdsa_key.pub"; + return "/etc/ssh/ssh_host_rsa_key.pub"; +} + +/** First connection to an SSH host: show the key's fingerprint; click trusts it. */ +function openHostKeyPage(window: HubWindow, control: ControlConnection, hostKey: SshHostKey): void { + const returnMode = hubListMode(window); + openHubPage(window, { + title: "Verify host key", + body: () => + `First connection to ${connectionStringHostLabel(control.config.url)}. Its ${hostKeyTypeName(hostKey.type)} host key fingerprint is:\n` + + `${hostKey.fingerprint}\n\n` + + `To check it, run this on the host and compare:\nssh-keygen -lf ${hostKeyFile(hostKey.type)}`, + hint: `click trust and connect ${GESTURE_DOUBLE_CLICK} cancel`, + onClick: () => { + const hostKeys = [...control.config.hostKeys.filter((key) => key !== hostKey.key), hostKey.key]; + control.config.hostKeys = hostKeys; + updateConnection(control.config.id, { hostKeys }); + control.sshIssue = null; + closeHubPage(window, returnMode); + connectControl(control); + }, + onBack: () => closeHubPage(window, returnMode), + }); +} + +function openHostKeyChangedPage(window: HubWindow, control: ControlConnection, hostKey: SshHostKey): void { + const returnMode = hubListMode(window); + openHubPage(window, { + title: "HOST KEY CHANGED", + body: () => + `${connectionStringHostLabel(control.config.url)} presented a different host key than the one trusted before: ` + + `${hostKeyTypeName(hostKey.type)} ${hostKey.fingerprint}\n\n` + + "Someone may be intercepting the connection, so Faceclaw won't connect. If the host was reinstalled or its keys " + + 'were regenerated, use "Forget host key" on this connection in Manage Connections, then verify the new fingerprint.', + hint: `${GESTURE_DOUBLE_CLICK} back`, + onBack: () => closeHubPage(window, returnMode), + }); +} + +/** Ask for the host's password on the phone (masked editor); click saves it and connects. */ +function openPasswordPage(window: HubWindow, control: ControlConnection, rejected: boolean): void { + const returnMode = hubListMode(window); + terminalSshPasswordSetting.set(""); + post({ type: "start-text-setting-edit", settingId: terminalSshPasswordSetting.id }); + openHubPage(window, { + title: "SSH password", + body: () => { + const typed = terminalSshPasswordSetting.get(); + return ( + (rejected ? "The host refused the saved password.\n" : "") + + `Type the password for ${connectionStringHostLabel(control.config.url)} in the phone app, then click to connect. ` + + "It is saved encrypted on this phone.\n\n" + + (typed ? "*".repeat(Math.min(typed.length, 32)) : "(nothing typed yet)") + ); + }, + hint: `click connect ${GESTURE_DOUBLE_CLICK} cancel`, + onClick: () => { + const password = terminalSshPasswordSetting.get(); + if (!password) return; + setSshSecret(sshPasswordSecretId(control.config.id), password); + control.sshIssue = null; + closeHubPage(window, returnMode); + connectControl(control); + }, + onBack: () => closeHubPage(window, returnMode), + onLeave: () => { + terminalSshPasswordSetting.set(""); + post({ type: "end-text-setting-edit" }); + }, + }); +} + +/** This device's SSH public key (the private half never leaves the keystore); click copies it. */ +function openClientKeyPage(window: HubWindow, intro = ""): void { + const returnMode = hubListMode(window); + let key: { authorizedKey: string; fingerprint: string } | null = null; + let error = ""; + try { + key = sshClientKey(SSH_KEY_COMMENT); + } catch (caught) { + error = String((caught as Error)?.message ?? caught); + } + let copied = false; + openHubPage(window, { + title: "This device's SSH key", + body: () => + key + ? `${intro}Add this line to ~/.ssh/authorized_keys on each host to log in with this phone's key:\n` + + `${key.authorizedKey}\n${key.fingerprint}` + + (copied ? "\n\nCopied to the phone's clipboard." : "") + : `Couldn't create this device's key: ${error}`, + hint: key ? `click copy to phone clipboard ${GESTURE_DOUBLE_CLICK} back` : `${GESTURE_DOUBLE_CLICK} back`, + onClick: key + ? () => { + copyToPhoneClipboard("SSH public key", key!.authorizedKey); + copied = true; + } + : undefined, + onBack: () => closeHubPage(window, returnMode), + }); +} + /** * One control connection's sessions in this hub window's display order: * most-recently-updated first as of when the window became visible, with @@ -1479,6 +1803,7 @@ function hubSessionItems(window: HubWindow): HubItem[] { ]; const multiHost = controls.size > 1; const canLaunch = launchPresetNames().length > 0; + const isTmux = (control: ControlConnection) => clientOptionsFor(control.config)?.kind === "tmux"; // Every configured host is listed under its own heading, in stored order, // whatever its connection state: a connected host lists its sessions, any // other shows its state on the heading plus a Connect row (unless it is @@ -1488,10 +1813,17 @@ function hubSessionItems(window: HubWindow): HubItem[] { const name = connectionDisplayName(control.config); if (!isControlConnected(control)) { items.push({ label: `${name} (${controlStatusWord(control)})`, heading: true }); + if (control.sshIssue && control.config.enabled) { + items.push({ label: sshIssueAction(control.sshIssue), onSelect: () => openSshIssuePage(window, control) }); + continue; + } const connecting = control.config.enabled && control.state?.phase === "connecting"; if (!connecting && clientOptionsFor(control.config)) { + // A failure retrying can't fix (tmux missing or too old) says why; + // selecting it retries once the host is fixed. + const unfixable = control.config.enabled && control.state?.retryable === false; items.push({ - label: control.reconnectTimer ? "Connect now" : "Connect", + label: unfixable ? control.state!.status : control.reconnectTimer ? "Connect now" : "Connect", onSelect: () => connectControl(control), }); } @@ -1500,7 +1832,8 @@ function hubSessionItems(window: HubWindow): HubItem[] { items.push({ label: name, heading: true, - onSelect: canLaunch ? () => launchOnHost(window, control) : undefined, + // tmux hosts can always start a shell, presets or not. + onSelect: canLaunch || isTmux(control) ? () => launchOnHost(window, control) : undefined, }); const sessions = orderedSessions(window, control); for (const session of sessions) { @@ -1516,7 +1849,11 @@ function hubSessionItems(window: HubWindow): HubItem[] { } if (!sessions.length) { items.push({ - label: multiHost ? "(no live sessions)" : "(no live sessions; run g2mirror )", + label: isTmux(control) + ? "(no tmux sessions; select the host to start one)" + : multiHost + ? "(no live sessions)" + : "(no live sessions; run g2mirror )", onSelect: () => control.client?.listSessions(), }); } @@ -1537,6 +1874,10 @@ function hubConnectionItems(window: HubWindow): HubItem[] { label: "Add connection", onSelect: () => beginAddConnection(window), }, + { + label: "This device's SSH key", + onSelect: () => openClientKeyPage(window), + }, { label: "Done", onSelect: () => setHubMode(window, "sessions"), @@ -1547,6 +1888,13 @@ function hubConnectionItems(window: HubWindow): HubItem[] { function controlStatusWord(control: ControlConnection): string { if (!control.config.enabled) return "off"; + const issue = control.sshIssue; + if (issue) { + if (issue.kind === "hostkey-unknown") return "verify host key"; + if (issue.kind === "hostkey-mismatch") return "HOST KEY CHANGED"; + if (issue.passwordTried) return "password rejected"; + return issue.passwordAllowed ? "password needed" : "key not authorized"; + } switch (control.state?.phase) { case "connected": case "attached": @@ -1579,6 +1927,32 @@ function openConnectionActions(window: HubWindow, control: ControlConnection): v connectControl(control); }, }, + ...(control.config.hostKeys.length + ? [ + { + label: "Forget host key", + onSelect: (ctx: { stack: { pop(): unknown } }) => { + ctx.stack.pop(); + control.config.hostKeys = []; + updateConnection(control.config.id, { hostKeys: [] }); + control.sshIssue = null; + if (control.config.enabled) startControl(control); + renderHubWindows(); + }, + }, + ] + : []), + ...(isSshConnection(control) && getSshSecret(sshPasswordSecretId(control.config.id)) + ? [ + { + label: "Forget saved password", + onSelect: (ctx: { stack: { pop(): unknown } }) => { + ctx.stack.pop(); + removeSshSecret(sshPasswordSecretId(control.config.id)); + }, + }, + ] + : []), { label: `Remove ${name}`, onSelect: (ctx) => { @@ -1596,6 +1970,11 @@ function openConnectionActions(window: HubWindow, control: ControlConnection): v windowMenu(window).open(items); } +function isSshConnection(control: ControlConnection): boolean { + const kind = clientOptionsFor(control.config)?.kind; + return kind === "tmux" || kind === "ssh-g2mirror"; +} + /** Enable and (re)connect now; also the manual retry path, so reset backoff. */ function connectControl(control: ControlConnection): void { control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS; @@ -1616,6 +1995,7 @@ function disconnectControl(control: ControlConnection): void { function removeControl(control: ControlConnection): void { stopControl(control); + removeSshSecret(sshPasswordSecretId(control.config.id)); controls.delete(control.config.id); saveConnections(loadConnections().filter((connection) => connection.id !== control.config.id)); renderHubWindows(); @@ -1624,7 +2004,7 @@ function removeControl(control: ControlConnection): void { /** * Enter the Add-connection screen: clear the draft and ask the shell to open * the phone text editor on it. The user types (or voice-inputs) the - * g2mirror:// string, then clicks to save or double-clicks to cancel. + * connection string, then clicks to save or double-clicks to cancel. */ function beginAddConnection(window: HubWindow): void { terminalNewConnectionSetting.set(""); @@ -1634,15 +2014,15 @@ function beginAddConnection(window: HubWindow): void { function saveAddConnection(window: HubWindow): void { const url = terminalNewConnectionSetting.get(); - if (!parseConnectionString(url)) { + if (!parseAnyConnectionString(url)) { window.addError = url - ? "Not a g2mirror://token@host connection string." - : "Enter a g2mirror:// connection string first."; + ? "Not an ssh://user@host or g2mirror://token@host string." + : "Enter a connection string first."; scheduleRender(window); return; } const connections = loadConnections(); - connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true }); + connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true, hostKeys: [] }); saveConnections(connections); endAddConnection(window); setHubMode(window, "connections"); @@ -1672,6 +2052,15 @@ function handleHubInput(window: HubWindow, event: InputEvent, frameId: number): frameTimings.finishFrame(frameId, "discarded: terminal add-connection ignored input"); return; } + if (window.mode === "page") { + if (event.type === "click" && window.page?.onClick) { + window.page.onClick(); + renderAndSubmit(window, frameId); + return; + } + frameTimings.finishFrame(frameId, "discarded: terminal page ignored input"); + return; + } const list = hubMenu(window); list.setItems(hubItems(window)); switch (event.type) { @@ -1859,6 +2248,11 @@ function launchPresetNames(): string[] { */ function launchOnHost(window: HubWindow, control: ControlConnection): void { const presets = launchPresetNames(); + if (presets.length === 0) { + // A tmux host with no presets configured: a new session running the login shell. + launchFromUi(control, "shell"); + return; + } if (presets.length === 1) { launchFromUi(control, presets[0]!); return; @@ -1903,6 +2297,9 @@ function paintHub(window: HubWindow): GrayImage { if (window.mode === "add") { return paintAddConnection(window); } + if (window.mode === "page" && window.page) { + return paintHubPage(window, window.page); + } const { viewportWidth: width, viewportHeight: height, padding } = window; const image = new GrayImage(width, height, 0); const font = chromeFont(); @@ -1917,7 +2314,7 @@ function paintHub(window: HubWindow): GrayImage { let listTop = header.listTop; if (window.mode === "sessions" && controls.size === 0) { - image.drawText(font, header.titleX, listTop, "Add a g2mirror:// connection to get started, see:", 150); + image.drawText(font, header.titleX, listTop, "Add an ssh:// (tmux) or g2mirror:// connection to get started, see:", 150); image.drawText(font, header.titleX, listTop + step, "https://github.com/jimrandomh/g2mirror", 190); listTop += 2 * step + 6; } @@ -1959,8 +2356,8 @@ function paintAddConnection(window: HubWindow): GrayImage { image.drawText(font, padding.left, padding.top, "Add connection", 220); const bodyX = padding.left + PAGE_BODY_INDENT; const instructionsY = padding.top + 10 + step; - image.drawText(font, bodyX, instructionsY, "Type the g2mirror://token@host string in the", 170); - image.drawText(font, bodyX, instructionsY + step, "phone app (or use voice input from the menu).", 170); + image.drawText(font, bodyX, instructionsY, "Type ssh://user@host (tmux) or g2mirror://token@host in", 170); + image.drawText(font, bodyX, instructionsY + step, "the phone app (or use voice input from the menu).", 170); const draftY = instructionsY + 3 * step; const draft = terminalNewConnectionSetting.get(); image.drawText(font, bodyX, draftY, truncateLabel(draft || "(empty)", 52), 220); @@ -1971,6 +2368,34 @@ function paintAddConnection(window: HubWindow): GrayImage { return image; } +/** A page of text: title at the top padding, wrapped body, hint on the bottom padding. */ +function paintHubPage(window: HubWindow, page: HubPage): GrayImage { + const { viewportWidth: width, viewportHeight: height, padding } = window; + const image = new GrayImage(width, height, 0); + const font = chromeFont(); + const step = lineStep(font); + image.drawText(font, padding.left, padding.top, page.title, 220); + const bodyX = padding.left + PAGE_BODY_INDENT; + const hintY = height - padding.bottom - font.lineHeight; + const lines = wrapText(font, page.body(), Math.max(1, width - padding.right - bodyX), { breakLongWords: true }); + let y = padding.top + 10 + step; + for (const line of lines) { + if (y + step > hintY) break; + image.drawText(font, bodyX, y, line, 190); + y += step; + } + image.drawText(font, bodyX, hintY, page.hint, 110); + return image; +} + +/** The action row under a host whose SSH connection needs the user. */ +function sshIssueAction(issue: SshFailure): string { + if (issue.kind === "hostkey-unknown") return "Verify host key..."; + if (issue.kind === "hostkey-mismatch") return "Host key changed!"; + if (issue.passwordAllowed) return issue.passwordTried ? "Re-enter password..." : "Enter password..."; + return "Show this device's SSH key..."; +} + function truncateLabel(text: string, maxLength: number): string { return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`; } diff --git a/app/apps/terminal/terminal-client.ts b/app/apps/terminal/terminal-client.ts new file mode 100644 index 00000000..529850f7 --- /dev/null +++ b/app/apps/terminal/terminal-client.ts @@ -0,0 +1,44 @@ +import type { + G2MirrorHistoryReply, + G2MirrorPhase, + G2MirrorSession, + G2MirrorState, +} from "../../native/terminal-session-types"; + +/** + * What the Terminal worker needs from a session backend. G2MirrorClient (a + * g2mirror server, directly or tunnelled over SSH) and TmuxClient (tmux + * control mode over SSH) both provide it. The model is g2mirror's: a client + * starts "connecting", reaches "connected" (it can list and launch sessions, + * and reports bells/activity/titles for them), and can then attach to one + * session, view it (snapshot + live output), page its scrollback, and type + * into it. + */ +export interface TerminalClient { + state(): G2MirrorState; + onStateChange(listener: (state: G2MirrorState) => void): () => void; + /** Raw VT100/xterm bytes to feed the emulator. Snapshot implies reset-first. */ + onTerminalData(listener: (data: Uint8Array, kind: "snapshot" | "output") => void): () => void; + onSessionAttached(listener: (command: string) => void): () => void; + onSessionDetached(listener: (reason: string) => void): () => void; + onBell(listener: (socket: string, lastBellAtMs: number) => void): () => void; + onActivity(listener: (socket: string, lastOutputAtMs: number) => void): () => void; + onTitle(listener: (socket: string, title: string) => void): () => void; + /** Fired after a snapshot's terminal data, with its scrollback splice point. */ + onSnapshot(listener: (historyNext: number, historyOldest: number) => void): () => void; + onHistoryLines(listener: (reply: G2MirrorHistoryReply) => void): () => void; + setViewport(cols: number, rows: number): void; + start(): void; + stop(): void; + listSessions(): void; + launchSession(preset: string): Promise; + connectSession(socket: string): void; + disconnectSession(): void; + view(): void; + unview(): void; + requestHistory(before: number, limit?: number): void; + sendInput(text: string): void; + submitInput(text: string): void; +} + +export type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState }; diff --git a/app/apps/terminal/tmux-client.ts b/app/apps/terminal/tmux-client.ts new file mode 100644 index 00000000..b2a0abd0 --- /dev/null +++ b/app/apps/terminal/tmux-client.ts @@ -0,0 +1,1094 @@ +/** + * tmux backend for the Terminal app: lists, watches, views and types into + * tmux panes on an SSH host, presenting them through the same TerminalClient + * model as g2mirror sessions (each pane is one "session"; its pane id, e.g. + * "%12", plays the part of g2mirror's session socket). + * + * Two kinds of channel run on the host, both opened through `openChannel` + * (an SSH exec channel in the app, a local process in tests): + * + * - The poller: a /bin/sh loop that prints the tmux version and host name, + * then every 2 s lists every pane of every session (only when the listing + * changed). It also (re)installs an alert-bell hook that counts bells per + * window in the @faceclaw_bells window option: tmux's own bell flag misses + * bells in a session's current window, and this way bells that ring while + * we're disconnected still show up as a higher count. Bell, activity and + * title notifications come from diffing successive listings. + * + * - The viewer (after connectSession): a tmux control-mode client + * (`tmux -C attach-session`) on the pane's session. It never changes the + * session's current window or active pane, so a desktop client attached to + * the same session is undisturbed. Viewing sets a per-window size for this + * client (`refresh-client -C @W:WxH`, which resizes the window to the + * glasses while we look, and restores it when cleared), snapshots the pane + * with capture-pane, and then applies its %output stream. Unviewing pauses + * the pane's output to this client (`refresh-client -A %N:pause`; "off" + * would make tmux stop reading the pane altogether when no other client + * wants it, stalling the program). Output from the session's other panes is + * paused as soon as it shows up. + * + * Requires tmux 3.2+ (control-mode pause/continue and per-window sizes); + * older versions get a message asking for an upgrade. 3.8's history_added / + * history_collected make scrollback paging exact; before that it assumes + * the history hasn't hit its limit since the snapshot. + */ +import type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState } from "./terminal-client"; + +export const TMUX_MIN_VERSION: [number, number] = [3, 2]; + +export type LineChannelListener = { + onOpen(): void; + /** One stdout line (see native/ssh escapeLine for non-UTF-8 lines). */ + onLine(line: string): void; + onStderr(line: string): void; + onClosed(exitStatus: number | null): void; + onFailure(message: string): void; +}; + +export type LineChannel = { + send(line: string): boolean; + close(): void; +}; + +/** Run `command` on the host (through the user's login shell, like ssh does). */ +export type OpenLineChannel = (command: string, listener: LineChannelListener) => LineChannel; + +export type TmuxClientOptions = { + openChannel: OpenLineChannel; + /** How status lines name the host, e.g. "jim@laptop". */ + label: string; + /** Grid the glasses view sessions at. */ + cols: number; + rows: number; + /** + * Remembers per-window bell counts across client instances (the worker + * makes a new client per reconnect), so a bell that rang while we were + * disconnected is still reported. The connection id for the client that + * watches bells; "" (counts kept per instance) for view clients, which + * mustn't consume bells the watching client hasn't seen yet. + */ + stateKey: string; +}; + +const POLL_INTERVAL_S = 2; +const BELL_HOOK_INDEX = 7091; +const LAUNCH_TIMEOUT_MS = 15_000; +const SUBMIT_DELAY_MS = 150; +// send-keys -H takes one argument per byte; keep command lines modest. +const SEND_KEYS_CHUNK_BYTES = 256; +// How many listings connectSession waits for a just-launched pane to appear. +const CONNECT_WAIT_POLLS = 4; + +// ---- host-side scripts ---- + +const TMUX_CANDIDATES = [ + "/opt/homebrew/bin/tmux", + "/usr/local/bin/tmux", + '"$HOME/.local/bin/tmux"', + '"$HOME/bin/tmux"', + "/home/linuxbrew/.linuxbrew/bin/tmux", + '"$HOME/.nix-profile/bin/tmux"', + "/run/current-system/sw/bin/tmux", + "/snap/bin/tmux", +]; + +/** + * Wrap a /bin/sh script as an exec command. The command runs under the + * user's login shell, which may be bash, zsh, fish or csh, so it stays a + * single line whose only quoting is one pair of single quotes, and the + * script may contain neither single quotes nor "\\" (fish treats \\ and \' + * specially inside single quotes; any other backslash is literal in all of + * them). + */ +export function hostCommand(script: string): string { + if (script.includes("'") || script.includes("\\\\") || /[\r\n]/.test(script)) { + throw new Error("host script contains characters that can't be quoted portably"); + } + return `exec /bin/sh -c '${script}'`; +} + +/** + * Sets T to the tmux binary: PATH as the exec shell sees it, then PATH as a + * login shell sees it (Homebrew/Nix/~/.local installs are often only on the + * login PATH), then common install locations. + */ +function locateTmux(): string { + return [ + "T=$(command -v tmux 2>/dev/null)", + '[ -x "$T" ] || T=$("${SHELL:-/bin/sh}" -lc "command -v tmux" 2>/dev/null &1)"', + 'echo "FACECLAW-HOST $(hostname 2>/dev/null)"', + 'echo "FACECLAW-HOME $HOME"', + `F="${format}"`, + `H="${hook}"`, + "P=-", + // Print the listing only when it changed. No server running: the + // listing is empty. + `while :; do O=$("$T" set-hook -g "alert-bell[${BELL_HOOK_INDEX}]" "$H" \\; list-panes -a -F "$F" 2>/dev/null); ` + + `if [ "$O" != "$P" ]; then echo FACECLAW-BEGIN; printf "%s\\n" "$O"; echo FACECLAW-END; P=$O; fi; sleep ${POLL_INTERVAL_S}; done`, + ].join("; "), + ); +} + +export function viewerCommand(sessionId: string): string { + if (!/^\$\d+$/.test(sessionId)) throw new Error(`bad tmux session id ${sessionId}`); + // "\$" keeps /bin/sh from expanding the session id ($3) as a variable. + return hostCommand(`${locateTmux()}; exec "$T" -C attach-session -t "\\${sessionId}"`); +} + +const SAFE_LAUNCH_COMMAND = /^[A-Za-z0-9 ._/+:=@%,-]+$/; + +/** New detached session running `preset` ("shell" or "": the default shell). */ +export function launchCommand(preset: string): string { + const command = preset === "shell" ? "" : preset.trim(); + if (command && !SAFE_LAUNCH_COMMAND.test(command)) { + throw new Error(`Launch preset "${preset}" has characters that can't be passed to tmux.`); + } + return hostCommand( + `${locateTmux()}; exec "$T" new-session -d -P -F "FACECLAW-LAUNCHED #{pane_id} #{session_id}"${command ? ` "${command}"` : ""}`, + ); +} + +// ---- parsing helpers ---- + +/** Parse `tmux -V` output; null for builds without a numeric version (master), treated as new. */ +export function parseTmuxVersion(text: string): [number, number] | null { + const match = /(\d+)\.(\d+)/.exec(text); + return match ? [parseInt(match[1]!, 10), parseInt(match[2]!, 10)] : null; +} + +export function tmuxVersionSupported(text: string): boolean { + const version = parseTmuxVersion(text); + if (!version) return true; + const [major, minor] = version; + return major > TMUX_MIN_VERSION[0] || (major === TMUX_MIN_VERSION[0] && minor >= TMUX_MIN_VERSION[1]); +} + +export type PaneRow = { + paneId: string; + sessionId: string; + sessionName: string; + windowId: string; + windowIndex: string; + windowName: string; + windowPanes: number; + paneIndex: string; + pid: number; + dead: boolean; + /** Last output (or window activity), seconds, host clock. */ + activity: number; + bells: number; + command: string; + path: string; + title: string; +}; + +export function parsePaneRow(line: string): PaneRow | null { + const fields = line.split("\t"); + if (fields.length < PANE_FIELDS.length || !fields[0]!.startsWith("%")) return null; + const title = fields.slice(PANE_FIELDS.length - 1).join("\t"); + return { + paneId: fields[0]!, + sessionId: fields[1]!, + sessionName: fields[2]!, + windowId: fields[3]!, + windowIndex: fields[4]!, + windowName: fields[5]!, + windowPanes: parseInt(fields[6]!, 10) || 1, + paneIndex: fields[7]!, + pid: parseInt(fields[8]!, 10) || 0, + dead: fields[9] === "1", + activity: parseInt(fields[10]!, 10) || 0, + bells: parseInt(fields[11]!, 10) || 0, + command: fields[12]!, + path: fields[13]!, + title, + }; +} + +/** + * A row's label in the session list: "session:window[.pane] ", where + * the title is what the program set (OSC 0/2) or, when it hasn't set one + * (tmux's default title is the host name), the running command and its + * directory. + */ +export function paneLabel(row: PaneRow, hostName: string, home: string): string { + const where = `${row.sessionName}:${row.windowIndex}${row.windowPanes > 1 ? `.${row.paneIndex}` : ""}`; + const shortHost = hostName.split(".")[0] ?? ""; + const meaningfulTitle = row.title && row.title !== hostName && row.title !== shortHost ? row.title : ""; + if (meaningfulTitle) return `${where} ${meaningfulTitle}`; + const path = home && (row.path === home || row.path.startsWith(`${home}/`)) ? `~${row.path.slice(home.length)}` : row.path; + return `${where} ${row.command}${path ? ` ${path}` : ""}`; +} + +/** + * Decode a tmux control-mode %output value to bytes: "\ooo" is an octal + * byte (tmux escapes control characters and backslashes this way, and the + * SSH transport escapes bytes of lines that aren't valid UTF-8 the same + * way); any other character is UTF-8 encoded. + */ +export function decodeTmuxOutput(value: string): Uint8Array { + const bytes: number[] = []; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code === 0x5c && i + 3 < value.length && /^[0-7]{3}$/.test(value.slice(i + 1, i + 4))) { + bytes.push(parseInt(value.slice(i + 1, i + 4), 8) & 0xff); + i += 3; + continue; + } + pushUtf8(bytes, value, i); + if (code >= 0xd800 && code <= 0xdbff && i + 1 < value.length) i++; + } + return Uint8Array.from(bytes); +} + +function pushUtf8(bytes: number[], text: string, index: number): void { + const point = text.codePointAt(index)!; + if (point < 0x80) bytes.push(point); + else if (point < 0x800) bytes.push(0xc0 | (point >> 6), 0x80 | (point & 0x3f)); + else if (point < 0x10000) bytes.push(0xe0 | (point >> 12), 0x80 | ((point >> 6) & 0x3f), 0x80 | (point & 0x3f)); + else + bytes.push( + 0xf0 | (point >> 18), + 0x80 | ((point >> 12) & 0x3f), + 0x80 | ((point >> 6) & 0x3f), + 0x80 | (point & 0x3f), + ); +} + +export function encodeUtf8(text: string): Uint8Array { + const bytes: number[] = []; + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + pushUtf8(bytes, text, i); + if (code >= 0xd800 && code <= 0xdbff && i + 1 < text.length) i++; + } + return Uint8Array.from(bytes); +} + +// Pane state read for a snapshot, '|'-separated (all numeric but the id). +const SNAPSHOT_FIELDS = [ + "#{pane_id}", + "#{cursor_x}", + "#{cursor_y}", + "#{cursor_flag}", + "#{keypad_cursor_flag}", + "#{keypad_flag}", + "#{wrap_flag}", + "#{insert_flag}", + "#{alternate_on}", + "#{scroll_region_upper}", + "#{scroll_region_lower}", + "#{pane_width}", + "#{pane_height}", + "#{history_size}", + "#{history_added}", + "#{history_collected}", + "#{history_generation}", +]; + +export type PaneState = { + paneId: string; + cursorX: number; + cursorY: number; + cursorVisible: boolean; + appCursorKeys: boolean; + appKeypad: boolean; + wrap: boolean; + insert: boolean; + alternate: boolean; + scrollUpper: number; + scrollLower: number; + width: number; + height: number; + /** Absolute index of the next line to enter the history (history_added, else history_size). */ + historyNext: number; + /** Oldest retained absolute index (history_collected, else 0). */ + historyOldest: number; + generation: string; +}; + +export function parsePaneState(line: string): PaneState | null { + const f = line.split("|"); + if (f.length < SNAPSHOT_FIELDS.length || !f[0]!.startsWith("%")) return null; + const n = (index: number) => parseInt(f[index]!, 10) || 0; + const exact = f[14] !== ""; + return { + paneId: f[0]!, + cursorX: n(1), + cursorY: n(2), + cursorVisible: f[3] !== "0", + appCursorKeys: f[4] === "1", + appKeypad: f[5] === "1", + wrap: f[6] !== "0", + insert: f[7] === "1", + alternate: f[8] === "1", + scrollUpper: n(9), + scrollLower: n(10), + width: n(11), + height: n(12), + historyNext: exact ? n(14) : n(13), + historyOldest: exact ? n(15) : 0, + generation: f[16] ?? "", + }; +} + +/** + * Terminal bytes that recreate a captured pane in a freshly reset emulator: + * the normal screen (when the pane is in the alternate screen), the visible + * lines, then cursor position and the modes that change how keys encode. + */ +export function snapshotBytes(state: PaneState, visible: string[], normalScreen: string[]): Uint8Array { + let out = ""; + const rows = (lines: string[]) => lines.slice(0, Math.max(1, state.height)).join("\x1b[0m\r\n"); + if (state.alternate) { + out += rows(normalScreen) + "\x1b[0m\x1b[?1049h\x1b[H"; + } + out += rows(visible) + "\x1b[0m"; + if (state.scrollUpper !== 0 || state.scrollLower !== state.height - 1) { + out += `\x1b[${state.scrollUpper + 1};${state.scrollLower + 1}r`; + } + out += `\x1b[${state.cursorY + 1};${state.cursorX + 1}H`; + if (!state.cursorVisible) out += "\x1b[?25l"; + if (state.appCursorKeys) out += "\x1b[?1h"; + if (state.appKeypad) out += "\x1b="; + if (!state.wrap) out += "\x1b[?7l"; + if (state.insert) out += "\x1b[4h"; + return encodeUtf8(out); +} + +/** send-keys -H commands typing `bytes` into pane `paneId`. */ +export function sendKeysCommands(paneId: string, bytes: Uint8Array): string[] { + const commands: string[] = []; + for (let start = 0; start < bytes.length; start += SEND_KEYS_CHUNK_BYTES) { + const hex = Array.from(bytes.subarray(start, start + SEND_KEYS_CHUNK_BYTES), (byte) => byte.toString(16).padStart(2, "0")); + commands.push(`send-keys -t ${paneId} -H ${hex.join(" ")}`); + } + return commands; +} + +// ---- client ---- + +type Block = { ok: boolean; lines: string[] }; +type PendingCommands = { count: number; blocks: Block[]; done: (blocks: Block[]) => void }; +type BellMemory = Map<string, { count: number; lastBellAt: number | null }>; + +const bellMemoryByKey = new Map<string, BellMemory>(); + +export class TmuxClient { + private phase: G2MirrorPhase = "idle"; + private status = "Not connected."; + private retryable = true; + private stopped = false; + private generation = 0; + + private poller: LineChannel | null = null; + private pollerLines: string[] | null = null; + private versionText = ""; + private hostName = ""; + private home = ""; + private rows = new Map<string, PaneRow>(); + private sessions: G2MirrorSession[] = []; + private listings = 0; + private pendingConnect: { paneId: string; deadline: number } | null = null; + + private viewer: LineChannel | null = null; + private attachedPane: PaneRow | null = null; + private viewing = false; + private sizeDirty = false; + private snapshotInFlight = false; + private snapshotGeneration = ""; + private pausedPanes = new Set<string>(); + private pending: PendingCommands[] = []; + private block: { time: string; number: string; ours: boolean; lines: string[] } | null = null; + private liveCheckInFlight = false; + private readonly localBellMemory: BellMemory = new Map(); + + private readonly stateListeners = new Set<(state: G2MirrorState) => void>(); + private readonly terminalDataListeners = new Set<(data: Uint8Array, kind: "snapshot" | "output") => void>(); + private readonly snapshotListeners = new Set<(historyNext: number, historyOldest: number) => void>(); + private readonly historyListeners = new Set<(reply: G2MirrorHistoryReply) => void>(); + private readonly attachedListeners = new Set<(command: string) => void>(); + private readonly detachedListeners = new Set<(reason: string) => void>(); + private readonly bellListeners = new Set<(socket: string, lastBellAtMs: number) => void>(); + private readonly activityListeners = new Set<(socket: string, lastOutputAtMs: number) => void>(); + private readonly titleListeners = new Set<(socket: string, title: string) => void>(); + + constructor(private readonly options: TmuxClientOptions) {} + + state(): G2MirrorState & { retryable: boolean } { + return { + phase: this.phase, + status: this.status, + sessions: this.sessions.slice(), + attachedCommand: this.attachedPane ? this.labelFor(this.attachedPane) : "", + serverName: this.hostName, + retryable: this.retryable, + }; + } + + onStateChange(listener: (state: G2MirrorState) => void): () => void { + return subscribe(this.stateListeners, listener); + } + onTerminalData(listener: (data: Uint8Array, kind: "snapshot" | "output") => void): () => void { + return subscribe(this.terminalDataListeners, listener); + } + onSnapshot(listener: (historyNext: number, historyOldest: number) => void): () => void { + return subscribe(this.snapshotListeners, listener); + } + onHistoryLines(listener: (reply: G2MirrorHistoryReply) => void): () => void { + return subscribe(this.historyListeners, listener); + } + onSessionAttached(listener: (command: string) => void): () => void { + return subscribe(this.attachedListeners, listener); + } + onSessionDetached(listener: (reason: string) => void): () => void { + return subscribe(this.detachedListeners, listener); + } + onBell(listener: (socket: string, lastBellAtMs: number) => void): () => void { + return subscribe(this.bellListeners, listener); + } + onActivity(listener: (socket: string, lastOutputAtMs: number) => void): () => void { + return subscribe(this.activityListeners, listener); + } + onTitle(listener: (socket: string, title: string) => void): () => void { + return subscribe(this.titleListeners, listener); + } + + setViewport(cols: number, rows: number): void { + if (cols === this.options.cols && rows === this.options.rows) return; + this.options.cols = cols; + this.options.rows = rows; + if (this.viewing) this.snapshot(); + } + + start(): void { + if (this.poller || this.viewer) return; + this.stopped = false; + this.retryable = true; + this.resetSessionState(); + this.setState("connecting", `Connecting to ${this.options.label}...`); + this.openPoller(); + } + + stop(): void { + this.stopped = true; + this.generation++; + if (this.viewer && this.attachedPane && this.viewing) { + // Best effort: give the window back its own size before detaching. + this.viewer.send(`refresh-client -C ${this.attachedPane.windowId}:`); + } + this.closeChannels(); + this.resetSessionState(); + this.setState("idle", "Not connected."); + } + + listSessions(): void { + // The poller pushes every change; nothing to ask for. + } + + launchSession(preset: string): Promise<string> { + return new Promise((resolve, reject) => { + if (this.phase !== "connected" && this.phase !== "attached") { + reject(new Error("Not connected to tmux.")); + return; + } + let command: string; + try { + command = launchCommand(preset); + } catch (error) { + reject(error); + return; + } + let settled = false; + let channel: LineChannel | null = null; + const errors: string[] = []; + const finish = (error: Error | null, paneId?: string) => { + if (settled) return; + settled = true; + clearTimeout(timer); + channel?.close(); + if (error) reject(error); + else resolve(paneId!); + }; + const timer = setTimeout(() => finish(new Error(`Launch of "${preset}" timed out.`)), LAUNCH_TIMEOUT_MS); + channel = this.options.openChannel(command, { + onOpen: () => {}, + onLine: (line) => { + const match = /^FACECLAW-LAUNCHED (%\d+) (\$\d+)$/.exec(line); + if (match) finish(null, match[1]); + else if (line === "FACECLAW-NO-TMUX") finish(new Error("tmux is not installed on the host.")); + }, + onStderr: (line) => errors.push(line), + onClosed: () => finish(new Error(errors.join(" ") || `Launch of "${preset}" failed.`)), + onFailure: (message) => finish(new Error(message)), + }); + if (settled) channel.close(); + }); + } + + connectSession(paneId: string): void { + if (this.phase !== "connected") return; + const row = this.rows.get(paneId); + if (!row) { + // Just launched, perhaps: wait a few listings for it to show up. + this.pendingConnect = { paneId, deadline: this.listings + CONNECT_WAIT_POLLS }; + this.setState(this.phase, "Waiting for the session..."); + return; + } + this.pendingConnect = null; + this.openViewer(row); + } + + disconnectSession(): void { + if (this.phase !== "attached") return; + this.unview(); + this.viewer?.close(); + this.viewer = null; + this.attachedPane = null; + this.setState("idle", "Detached."); + } + + view(): void { + if (this.phase !== "attached" || !this.attachedPane) return; + this.viewing = true; + this.snapshot(); + } + + unview(): void { + if (this.phase !== "attached" || !this.attachedPane || !this.viewing) return; + this.viewing = false; + const pane = this.attachedPane; + this.command([`refresh-client -A '${pane.paneId}:pause'`, `refresh-client -C ${pane.windowId}:`]); + } + + requestHistory(before: number, limit = 200): void { + if (this.phase !== "attached" || !this.attachedPane) return; + void this.fetchHistory(this.attachedPane, before, limit); + } + + sendInput(text: string): void { + if (this.phase !== "attached" || !this.attachedPane || !text) return; + if (this.sizeDirty && this.viewing) { + // Someone else resized the window since we sized it (window-size + // "latest" follows the most recently active client). Typing here makes + // us the active one again: take the size back and resync. + this.snapshot(); + } + this.command(sendKeysCommands(this.attachedPane.paneId, encodeUtf8(text))); + } + + submitInput(text: string): void { + if (this.phase !== "attached") return; + // Like g2mirror's `delays`: a pause before Enter so paste-detecting apps + // (Claude Code) read it as a keypress, not the tail of a paste. + if (text) this.sendInput(text); + const generation = this.generation; + setTimeout(() => { + if (generation === this.generation) this.sendInput("\r"); + }, text ? SUBMIT_DELAY_MS : 0); + } + + // ---- poller ---- + + private openPoller(): void { + const generation = this.generation; + const stderr: string[] = []; + this.poller = this.options.openChannel(pollerCommand(), { + onOpen: () => {}, + onLine: (line) => { + if (generation === this.generation) this.handlePollerLine(line); + }, + onStderr: (line) => { + stderr.push(line); + if (stderr.length > 5) stderr.shift(); + }, + onClosed: (exitStatus) => { + if (generation !== this.generation || this.phase === "failed") return; + this.poller = null; + if (this.phase === "attached") return; // the viewer carries on alone + const detail = stderr.length ? `: ${stderr[stderr.length - 1]}` : exitStatus !== null ? ` (exit ${exitStatus})` : ""; + this.fail(`Session listing on ${this.options.label} ended${detail}`); + }, + onFailure: (message) => { + if (generation !== this.generation) return; + this.poller = null; + this.fail(message); + }, + }); + } + + private handlePollerLine(line: string): void { + if (this.pollerLines) { + if (line === "FACECLAW-END") { + this.applyListing(this.pollerLines); + this.pollerLines = null; + } else { + this.pollerLines.push(line); + } + return; + } + if (line === "FACECLAW-BEGIN") { + this.pollerLines = []; + } else if (line === "FACECLAW-NO-TMUX") { + this.retryable = false; + this.fail(`tmux is not installed on ${this.options.label} (or not on the login shell's PATH).`); + } else if (line.startsWith("FACECLAW-TMUX ")) { + this.versionText = line.slice("FACECLAW-TMUX ".length).trim(); + if (!tmuxVersionSupported(this.versionText)) { + this.retryable = false; + this.fail( + `${this.versionText || "tmux"} on ${this.options.label} is too old; Faceclaw needs tmux ${TMUX_MIN_VERSION.join(".")} or newer. Please upgrade it.`, + ); + } + } else if (line.startsWith("FACECLAW-HOST ")) { + this.hostName = line.slice("FACECLAW-HOST ".length).trim(); + } else if (line.startsWith("FACECLAW-HOME ")) { + this.home = line.slice("FACECLAW-HOME ".length).trim(); + } + } + + private applyListing(lines: string[]): void { + const now = Date.now(); + const previous = this.rows; + const firstListing = this.listings === 0; + this.listings++; + const memory = this.options.stateKey ? bellMemoryFor(this.options.stateKey) : this.localBellMemory; + const rows = new Map<string, PaneRow>(); + const bellsByWindow = new Map<string, number>(); + for (const line of lines) { + const row = parsePaneRow(line); + if (!row || rows.has(row.paneId)) continue; + rows.set(row.paneId, row); + bellsByWindow.set(row.windowId, row.bells); + } + // Bells are counted per window. A count above the remembered one is a + // bell (possibly one that rang while we were away); a lower one means the + // tmux server restarted and reused the id. + const belledWindows = new Set<string>(); + for (const [windowId, count] of bellsByWindow) { + const known = memory.get(windowId); + if (!known) { + memory.set(windowId, { count, lastBellAt: null }); + } else if (count > known.count) { + memory.set(windowId, { count, lastBellAt: now }); + belledWindows.add(windowId); + } else if (count < known.count) { + memory.set(windowId, { count, lastBellAt: known.lastBellAt }); + } + } + this.rows = rows; + this.sessions = [...rows.values()] + .filter((row) => !row.dead) + .map((row) => ({ + socket: row.paneId, + pid: row.pid, + cwdHint: row.path.replace(/\//g, "_"), + lastBellAt: memory.get(row.windowId)?.lastBellAt ?? null, + lastOutputAt: row.activity ? row.activity * 1000 : null, + title: this.labelFor(row), + })); + if (this.phase === "connecting") { + this.setState("connected", `Connected to ${this.options.label} (${this.versionText || "tmux"}).`); + } else { + this.emitState(); + } + if (!firstListing) { + for (const row of rows.values()) { + const before = previous.get(row.paneId); + if (belledWindows.has(row.windowId)) { + const at = memory.get(row.windowId)?.lastBellAt ?? now; + for (const listener of this.bellListeners) listener(row.paneId, at); + } + if (before && row.activity > before.activity) { + for (const listener of this.activityListeners) listener(row.paneId, row.activity * 1000); + } + if (before && row.title !== before.title) { + for (const listener of this.titleListeners) listener(row.paneId, this.labelFor(row)); + } + } + } + if (this.pendingConnect) { + const { paneId, deadline } = this.pendingConnect; + const row = rows.get(paneId); + if (row) { + this.pendingConnect = null; + this.openViewer(row); + } else if (this.listings >= deadline) { + this.pendingConnect = null; + this.setState("connected", "That session no longer exists."); + for (const listener of this.detachedListeners) listener("session not found"); + } + } + } + + private labelFor(row: PaneRow): string { + return paneLabel(row, this.hostName, this.home); + } + + // ---- viewer ---- + + private openViewer(row: PaneRow): void { + const generation = this.generation; + let command: string; + try { + command = viewerCommand(row.sessionId); + } catch (error) { + this.fail(String((error as Error).message ?? error)); + return; + } + this.attachedPane = row; + this.pausedPanes.clear(); + this.pending = []; + this.block = null; + this.setState("connected", "Attaching to session..."); + const stderr: string[] = []; + let attached = false; + let attachError = ""; + this.viewer = this.options.openChannel(command, { + onOpen: () => {}, + onLine: (line) => { + if (generation !== this.generation) return; + if (!attached) { + // The attach-session command's own reply block: %end means tmux + // attached us, %error (then %exit) that the session is gone. + if (line.startsWith("%end ")) { + attached = true; + // The view needs no listings from here on. + this.poller?.close(); + this.poller = null; + this.setState("attached", `Attached to ${this.labelFor(row)}.`); + for (const listener of this.attachedListeners) listener(this.labelFor(row)); + } else if (!line.startsWith("%") && !attachError) { + attachError = line; + } + return; + } + this.handleControlLine(line); + }, + onStderr: (line) => { + stderr.push(line); + if (stderr.length > 5) stderr.shift(); + }, + onClosed: () => { + if (generation !== this.generation) return; + this.viewer = null; + if (!attached && attachError) { + // E.g. "can't find session": it ended between listing and attaching. + this.generation++; + this.closeChannels(); + this.attachedPane = null; + this.setState("connected", `That session no longer exists (${attachError}).`); + for (const listener of this.detachedListeners) listener("session not found"); + return; + } + if (!attached) { + this.fail(stderr.length ? `tmux: ${stderr[stderr.length - 1]}` : "tmux refused to attach."); + return; + } + this.sessionEnded("tmux client exited"); + }, + onFailure: (message) => { + if (generation !== this.generation) return; + this.viewer = null; + this.fail(message); + }, + }); + } + + private handleControlLine(line: string): void { + const block = this.block; + if (block) { + if (line.startsWith("%end ") || line.startsWith("%error ")) { + const [, time, number] = line.split(" "); + if (time === block.time && number === block.number) { + this.block = null; + if (block.ours) this.finishBlock({ ok: line.startsWith("%end "), lines: block.lines }); + return; + } + } + block.lines.push(line); + return; + } + const space = line.indexOf(" "); + const kind = space < 0 ? line : line.slice(0, space); + switch (kind) { + case "%begin": { + const [, time, number, flags] = line.split(" "); + // flags 1: a command this client sent (0: e.g. the initial attach). + this.block = { time: time ?? "", number: number ?? "", ours: flags === "1", lines: [] }; + return; + } + case "%output": { + const second = line.indexOf(" ", space + 1); + if (second < 0) return; + this.handleOutput(line.slice(space + 1, second), line.slice(second + 1)); + return; + } + case "%exit": + this.sessionEnded(line.length > 6 ? line.slice(6) : "tmux session ended"); + return; + case "%layout-change": { + const [, windowId, layout] = line.split(" "); + const pane = this.attachedPane; + if (pane && windowId === pane.windowId) { + const size = /^[0-9a-f]{4},(\d+)x(\d+),/.exec(layout ?? ""); + if (size && this.viewing && (+size[1]! !== this.options.cols || +size[2]! !== this.options.rows)) { + this.sizeDirty = true; + } + this.checkPaneAlive(); + } + return; + } + case "%window-close": + case "%unlinked-window-close": + case "%window-pane-changed": + case "%session-changed": + this.checkPaneAlive(); + return; + default: + // %session-renamed, %window-renamed, %pause, %continue, ... + return; + } + } + + private handleOutput(paneId: string, value: string): void { + const pane = this.attachedPane; + if (!pane || paneId !== pane.paneId) { + // Another pane in the attached session: we never show it, so stop tmux + // sending it to us. + if (!this.pausedPanes.has(paneId) && /^%\d+$/.test(paneId)) { + this.pausedPanes.add(paneId); + this.command([`refresh-client -A '${paneId}:pause'`]); + } + return; + } + // Output that arrives before a snapshot's capture is already in it. + if (!this.viewing || this.snapshotInFlight) return; + const bytes = decodeTmuxOutput(value); + for (const listener of this.terminalDataListeners) listener(bytes, "output"); + } + + private finishBlock(block: Block): void { + const pending = this.pending[0]; + if (!pending) return; + pending.blocks.push(block); + if (pending.blocks.length >= pending.count) { + this.pending.shift(); + pending.done(pending.blocks); + } + } + + /** + * Send commands as one line (tmux runs them back to back, so e.g. a + * capture and the state read with it are consistent); `done` gets one + * block per command, synchronously as the last one arrives — before any + * later %output line is handled — or [] if the viewer went away. + */ + private command(commands: string[], done: (blocks: Block[]) => void = () => {}): void { + if (!this.viewer || !commands.length) { + done([]); + return; + } + this.pending.push({ count: commands.length, blocks: [], done }); + if (!this.viewer.send(commands.join(" ; "))) { + this.pending.pop(); + done([]); + } + } + + private commandAsync(commands: string[]): Promise<Block[]> { + return new Promise((resolve) => this.command(commands, resolve)); + } + + private snapshot(): void { + const pane = this.attachedPane; + if (!pane || this.snapshotInFlight) return; + this.snapshotInFlight = true; + this.sizeDirty = false; + const generation = this.generation; + const { cols, rows } = this.options; + this.command([ + `refresh-client -C ${pane.windowId}:${cols}x${rows}`, + `refresh-client -A '${pane.paneId}:continue'`, + `display -p -t ${pane.paneId} '${SNAPSHOT_FIELDS.join("|")}'`, + `capture-pane -p -e -t ${pane.paneId}`, + `capture-pane -p -e -a -q -t ${pane.paneId}`, + ], (blocks) => { + if (generation !== this.generation) return; + this.snapshotInFlight = false; + if (blocks.length < 5 || !this.viewing) return; + const state = parsePaneState(blocks[2]!.lines[0] ?? ""); + if (!state || state.paneId !== pane.paneId) { + this.sessionEnded("session closed"); + return; + } + this.snapshotGeneration = state.generation; + const data = snapshotBytes(state, blocks[3]!.lines, blocks[4]!.ok ? blocks[4]!.lines : []); + for (const listener of this.terminalDataListeners) listener(data, "snapshot"); + for (const listener of this.snapshotListeners) listener(state.historyNext, state.historyOldest); + }); + } + + private async fetchHistory(pane: PaneRow, before: number, limit: number): Promise<void> { + const generation = this.generation; + const stateCommand = `display -p -t ${pane.paneId} '${SNAPSHOT_FIELDS.join("|")}'`; + let state = parsePaneState((await this.commandAsync([stateCommand]))[0]?.lines[0] ?? ""); + // Absolute index a is at capture-pane line (a - historyNext). If more + // lines scroll into the history between our two requests, the offsets go + // stale; the second request re-reads the state with the capture, so + // retry until they agree. + for (let attempt = 0; attempt < 3 && state && generation === this.generation; attempt++) { + if (state.generation !== this.snapshotGeneration) { + // History was cleared or reflowed: our indices mean nothing now. + this.snapshot(); + return; + } + const start = Math.max(state.historyOldest, before - limit); + const end = Math.min(before, state.historyNext); + if (end <= start) { + this.emitHistory({ start, oldest: state.historyOldest, next: state.historyNext, lines: [] }); + return; + } + const blocks = await this.commandAsync([ + stateCommand, + `capture-pane -p -t ${pane.paneId} -S ${start - state.historyNext} -E ${end - 1 - state.historyNext}`, + ]); + if (generation !== this.generation || blocks.length < 2) return; + const after = parsePaneState(blocks[0]!.lines[0] ?? ""); + if (after && after.historyNext === state.historyNext && after.generation === state.generation) { + this.emitHistory({ + start, + oldest: state.historyOldest, + next: state.historyNext, + lines: blocks[1]!.ok ? blocks[1]!.lines.slice(0, end - start) : [], + }); + return; + } + state = after; + } + } + + private emitHistory(reply: G2MirrorHistoryReply): void { + for (const listener of this.historyListeners) listener(reply); + } + + /** Something structural changed: make sure our pane still exists. */ + private checkPaneAlive(): void { + const pane = this.attachedPane; + if (!pane || this.liveCheckInFlight) return; + this.liveCheckInFlight = true; + const generation = this.generation; + this.command([`display -p -t ${pane.paneId} '#{pane_id} #{window_id}'`], (blocks) => { + this.liveCheckInFlight = false; + if (generation !== this.generation || !blocks.length) return; + const [paneId, windowId] = (blocks[0]!.lines[0] ?? "").split(" "); + if (paneId !== pane.paneId) { + this.sessionEnded("session closed"); + } else if (windowId && windowId !== pane.windowId) { + // The pane moved to another window (break-pane, move-pane). + this.attachedPane = { ...pane, windowId }; + if (this.viewing) this.snapshot(); + } + }); + } + + private sessionEnded(reason: string): void { + if (this.phase !== "attached") return; + this.generation++; + this.closeChannels(); + this.attachedPane = null; + this.viewing = false; + this.setState("connected", `Session ended (${reason}).`); + for (const listener of this.detachedListeners) listener(reason); + } + + // ---- shared ---- + + private fail(message: string): void { + if (this.stopped) return; + this.generation++; + this.closeChannels(); + this.attachedPane = null; + this.viewing = false; + this.setState("failed", message); + } + + private closeChannels(): void { + this.poller?.close(); + this.poller = null; + this.viewer?.close(); + this.viewer = null; + for (const pending of this.pending.splice(0)) pending.done([]); + this.block = null; + this.snapshotInFlight = false; + this.liveCheckInFlight = false; + } + + private resetSessionState(): void { + this.pollerLines = null; + this.rows = new Map(); + this.sessions = []; + this.listings = 0; + this.pendingConnect = null; + this.attachedPane = null; + this.viewing = false; + this.sizeDirty = false; + } + + private setState(phase: G2MirrorPhase, status: string): void { + this.phase = phase; + this.status = status; + this.emitState(); + } + + private emitState(): void { + const state = this.state(); + for (const listener of this.stateListeners) listener(state); + } +} + +function bellMemoryFor(key: string): BellMemory { + let memory = bellMemoryByKey.get(key); + if (!memory) { + memory = new Map(); + bellMemoryByKey.set(key, memory); + } + return memory; +} + +function subscribe<T>(set: Set<T>, listener: T): () => void { + set.add(listener); + return () => set.delete(listener); +} diff --git a/app/native/g2mirror-client.ts b/app/native/g2mirror-client.ts index b93f18c7..16956df8 100644 --- a/app/native/g2mirror-client.ts +++ b/app/native/g2mirror-client.ts @@ -1,5 +1,6 @@ -import { openSocket } from "./socket"; +import { openSocket, type SocketConnection, type SocketListener } from "./socket"; import { toUint8Array } from "../util/array-util"; +import type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState } from "./terminal-session-types"; declare const android: any; declare const java: any; @@ -19,54 +20,7 @@ const LAUNCH_REPLY_TIMEOUT_MS = 10_000; // otherwise treat the "\r" as a pasted newline instead of the Enter key. const SUBMIT_DELAY_MS = 150; -export type G2MirrorSession = { - socket: string; - pid: number; - cwdHint: string; - /** Unix epoch ms of the terminal's last bell, or null if none observed. */ - lastBellAt: number | null; - /** - * Unix epoch ms (host clock) of the app's last output, or null if none - * observed. Fresh to within the wrapper's 2s activity reporting interval - * while we're connected; compare against other host timestamps, not the - * phone clock (see the worker's local-receive-time activity tracking). - */ - lastOutputAt: number | null; - /** Window title the app last set (xterm OSC 0/2), or null if none observed. */ - title: string | null; -}; - -export type G2MirrorPhase = - | "idle" - | "connecting" - | "connected" // handshake accepted; can list/attach - | "attached" // relaying to one session - | "failed"; - -export type G2MirrorState = { - phase: G2MirrorPhase; - status: string; - sessions: G2MirrorSession[]; - attachedCommand: string; - /** - * server_name from the init success reply: a human-readable name for the - * machine the server runs on. "" until the handshake succeeds (or when an - * older server omits the field). - */ - serverName: string; -}; - -/** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */ -export type G2MirrorHistoryReply = { - /** Absolute index of lines[0]; the page covers [start, start + lines.length). */ - start: number; - /** Oldest index still retained by the wrapper (older requests return nothing). */ - oldest: number; - /** Current splice point (next line to be archived). */ - next: number; - /** Plain text, ANSI-stripped, oldest-to-newest. */ - lines: string[]; -}; +export type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState }; export type G2MirrorClientOptions = { /** TLS (g2mirrors:// → wss) vs plain (g2mirror:// → ws). */ @@ -77,6 +31,12 @@ export type G2MirrorClientOptions = { deviceName: string; cols: number; rows: number; + /** + * Opens the websocket some other way than dialing host:port directly + * (e.g. through an SSH tunnel); `label` then names the endpoint in status + * lines instead of host:port. + */ + transport?: { open: (listener: SocketListener) => SocketConnection; label: string }; }; type TerminalDataKind = "snapshot" | "output"; @@ -180,7 +140,8 @@ export class G2MirrorClient { this.stopped = false; const generation = ++this.connectionGeneration; const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`; - this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`); + const transport = this.options.transport; + this.setState("connecting", `Connecting to ${transport ? transport.label : `${this.options.host}:${this.options.port}`}...`); this.listenerProxy = { onOpen: () => { if (this.stopped || generation !== this.connectionGeneration) return; @@ -208,7 +169,7 @@ export class G2MirrorClient { }, }; try { - this.ws = openSocket(url, this.listenerProxy); + this.ws = transport ? transport.open(this.listenerProxy!) : openSocket(url, this.listenerProxy); } catch (error) { this.ws = null; this.handleConnectionLost(`Connection failed: ${shortenError(String((error as Error)?.message ?? error))}`); diff --git a/app/native/ssh-common.ts b/app/native/ssh-common.ts new file mode 100644 index 00000000..6d60cc80 --- /dev/null +++ b/app/native/ssh-common.ts @@ -0,0 +1,153 @@ +/** + * Platform-independent half of the SSH transport bindings (ssh.ts / + * ssh.ios.ts): the types the app uses and the decoding of the Go + * transport's events (native/ssh/faceclawssh.go, Listener). + */ + +/** Where and as whom to connect. */ +export type SshEndpoint = { + host: string; + port: number; + user: string; + /** Pinned host keys (SSH wire format, base64). Empty: first connection reports hostkey-unknown. */ + hostKeys: string[]; + /** Saved password, or "" to try only the device key. */ + password: string; + /** Offer the device's client key. */ + useKey: boolean; +}; + +export type SshChannelSpec = + | { + /** Run a command on the host; text is exchanged a line at a time. */ + type: "exec"; + command: string; + } + | { + /** WebSocket to a URL resolved on the host's side (e.g. ws://127.0.0.1:8737/). */ + type: "websocket"; + url: string; + }; + +export type SshHostKey = { + /** SSH key type, e.g. "ssh-ed25519". */ + type: string; + /** OpenSSH-style "SHA256:..." fingerprint. */ + fingerprint: string; + /** SSH wire format, base64: the value to pin in SshEndpoint.hostKeys. */ + key: string; +}; + +export type SshFailureKind = + | "hostkey-unknown" + | "hostkey-mismatch" + | "auth" + | "network" + | "channel" + | "config" + | "internal"; + +export type SshFailure = { + kind: SshFailureKind; + message: string; + /** For hostkey-*: the key the host presented. */ + hostKey?: SshHostKey; + /** For auth: the host takes passwords / we sent one / we offered our key. */ + passwordAllowed?: boolean; + passwordTried?: boolean; + keyTried?: boolean; +}; + +export type SshClosed = { + /** Exec channels: the command's exit status (and signal, if killed). */ + exitStatus?: number; + signal?: string; + /** WebSocket channels: the close frame's code and reason. */ + code?: number; + reason?: string; +}; + +export type SshChannelListener = { + onOpen(): void; + onText(text: string): void; + onStderr?(line: string): void; + /** Terminal: the channel ended normally. */ + onClosed(info: SshClosed): void; + /** Terminal: the channel couldn't open or was lost. */ + onFailure(failure: SshFailure): void; +}; + +export type SshChannel = { + /** Queue a websocket text frame / an exec stdin line. False once closed. */ + send(text: string): boolean; + /** Flush queued sends, then end the channel. No events follow. */ + close(): void; +}; + +export type SshClientKey = { + /** "ecdsa-sha2-nistp256 AAAA... comment", for ~/.ssh/authorized_keys. */ + authorizedKey: string; + fingerprint: string; +}; + +/** Build the Go transport's openSpec JSON. */ +export function encodeSshSpec(endpoint: SshEndpoint, channel: SshChannelSpec): string { + return JSON.stringify({ + host: endpoint.host, + port: endpoint.port, + user: endpoint.user, + password: endpoint.password, + hostKeys: endpoint.hostKeys, + useKey: endpoint.useKey, + channel, + }); +} + +/** Route one transport event to the listener. Unknown kinds are ignored. */ +export function dispatchSshEvent(listener: SshChannelListener, kind: string, payload: string): void { + switch (kind) { + case "open": + listener.onOpen(); + return; + case "text": + listener.onText(payload); + return; + case "stderr": + listener.onStderr?.(payload); + return; + case "closed": + listener.onClosed(parseJson(payload) ?? {}); + return; + case "failure": { + const failure = parseJson(payload); + listener.onFailure( + failure && typeof failure.kind === "string" + ? failure + : { kind: "internal", message: `bad failure payload: ${payload}` }, + ); + return; + } + } +} + +function parseJson(text: string): any { + try { + return JSON.parse(text); + } catch { + return null; + } +} + +/** Human summary of a failure for status lines. */ +export function describeSshFailure(failure: SshFailure): string { + switch (failure.kind) { + case "hostkey-unknown": + return "Host key not yet trusted."; + case "hostkey-mismatch": + return "HOST KEY CHANGED; refusing to connect."; + case "auth": + return failure.message || "Authentication failed."; + default: + return failure.message || failure.kind; + } +} diff --git a/app/native/ssh.ios.ts b/app/native/ssh.ios.ts new file mode 100644 index 00000000..87cf7f3f --- /dev/null +++ b/app/native/ssh.ios.ts @@ -0,0 +1,69 @@ +import { + dispatchSshEvent, + encodeSshSpec, + type SshChannel, + type SshChannelListener, + type SshChannelSpec, + type SshClientKey, + type SshEndpoint, +} from "./ssh-common"; + +export * from "./ssh-common"; + +declare const FaceclawSshChannel: any; +declare const FaceclawSshKeys: any; + +// Like socket.ios.ts: Go delivers events on its own threads, so the native +// side queues them and this isolate drains the queue on a timer. +const POLL_INTERVAL_MS = 25; + +/** iOS SSH transport: FaceclawSshChannel (ObjC) over the gomobile-bound Go package in native/ssh. */ +export function openSshChannel(endpoint: SshEndpoint, channel: SshChannelSpec, listener: SshChannelListener): SshChannel { + const native = FaceclawSshChannel.alloc().initWithSpecUseKey(encodeSshSpec(endpoint, channel), endpoint.useKey); + let ended = false; + const stop = () => { + if (ended) return; + ended = true; + clearInterval(timer); + native.close(); + }; + const timer = setInterval(() => { + const events = JSON.parse(String(native.takeEvents())) as Array<{ kind: string; payload: string }>; + for (const event of events) { + if (ended) break; + if (event.kind === "closed" || event.kind === "failure") { + // Terminal events: stop polling, then deliver. + ended = true; + clearInterval(timer); + } + dispatchSshEvent(listener, event.kind, event.payload); + } + }, POLL_INTERVAL_MS); + return { + send: (text) => !ended && native.send(text) === true, + close: stop, + }; +} + +export function sshClientKey(comment: string): SshClientKey { + const authorizedKey = FaceclawSshKeys.authorizedKeyWithComment(comment); + const fingerprint = FaceclawSshKeys.fingerprint(); + if (!authorizedKey || !fingerprint) throw new Error("Could not create the SSH client key."); + return { authorizedKey: String(authorizedKey), fingerprint: String(fingerprint) }; +} + +export function getSshSecret(id: string): string { + return String(FaceclawSshKeys.secretForId(id) ?? ""); +} + +export function setSshSecret(id: string, value: string): void { + FaceclawSshKeys.setSecretForId(value, id); +} + +export function removeSshSecret(id: string): void { + FaceclawSshKeys.removeSecretForId(id); +} + +export function copyToPhoneClipboard(_label: string, text: string): void { + FaceclawSshKeys.copyToClipboard(text); +} diff --git a/app/native/ssh.ts b/app/native/ssh.ts new file mode 100644 index 00000000..dd7a2978 --- /dev/null +++ b/app/native/ssh.ts @@ -0,0 +1,66 @@ +import { Utils } from "@nativescript/core"; +import { + dispatchSshEvent, + encodeSshSpec, + type SshChannel, + type SshChannelListener, + type SshChannelSpec, + type SshClientKey, + type SshEndpoint, +} from "./ssh-common"; + +export * from "./ssh-common"; + +declare const com: any; + +/** + * Android SSH transport: FaceclawSshChannel (Kotlin) over the gomobile-bound + * Go package in native/ssh. Callable from the main isolate or a worker; + * events arrive on the calling isolate's thread. + */ +export function openSshChannel(endpoint: SshEndpoint, channel: SshChannelSpec, listener: SshChannelListener): SshChannel { + let closed = false; + const proxy = new com.faceclaw.app.FaceclawSshListener({ + onEvent: (kind: string, payload: string) => { + if (closed) return; + dispatchSshEvent(listener, String(kind), payload == null ? "" : String(payload)); + }, + }); + const native = new com.faceclaw.app.FaceclawSshChannel(encodeSshSpec(endpoint, channel), endpoint.useKey, proxy); + return { + send: (text) => !closed && native.send(text) === true, + close: () => { + if (closed) return; + closed = true; + native.close(); + }, + }; +} + +function context(): any { + return Utils.android.getApplicationContext(); +} + +/** The device's SSH client key (generated on first use). */ +export function sshClientKey(comment: string): SshClientKey { + return { + authorizedKey: String(com.faceclaw.app.FaceclawSshKeys.authorizedKey(comment)), + fingerprint: String(com.faceclaw.app.FaceclawSshKeys.fingerprint()), + }; +} + +export function getSshSecret(id: string): string { + return String(com.faceclaw.app.FaceclawSshKeys.getSecret(context(), id) ?? ""); +} + +export function setSshSecret(id: string, value: string): void { + com.faceclaw.app.FaceclawSshKeys.setSecret(context(), id, value); +} + +export function removeSshSecret(id: string): void { + com.faceclaw.app.FaceclawSshKeys.removeSecret(context(), id); +} + +export function copyToPhoneClipboard(label: string, text: string): void { + com.faceclaw.app.FaceclawSshKeys.copyToClipboard(context(), label, text); +} diff --git a/app/native/terminal-session-types.ts b/app/native/terminal-session-types.ts new file mode 100644 index 00000000..637d9dd3 --- /dev/null +++ b/app/native/terminal-session-types.ts @@ -0,0 +1,59 @@ +/** + * Session-list and connection-state types shared by the Terminal app's + * backends (g2mirror-client.ts, apps/terminal/tmux-client.ts). Kept free of + * platform imports so the tmux client can be unit-tested under node. + */ + +export type G2MirrorSession = { + socket: string; + pid: number; + cwdHint: string; + /** Unix epoch ms of the terminal's last bell, or null if none observed. */ + lastBellAt: number | null; + /** + * Unix epoch ms (host clock) of the app's last output, or null if none + * observed. Fresh to within the wrapper's 2s activity reporting interval + * while we're connected; compare against other host timestamps, not the + * phone clock (see the worker's local-receive-time activity tracking). + */ + lastOutputAt: number | null; + /** Window title the app last set (xterm OSC 0/2), or null if none observed. */ + title: string | null; +}; + +export type G2MirrorPhase = + | "idle" + | "connecting" + | "connected" // handshake accepted; can list/attach + | "attached" // relaying to one session + | "failed"; + +export type G2MirrorState = { + phase: G2MirrorPhase; + status: string; + sessions: G2MirrorSession[]; + attachedCommand: string; + /** + * server_name from the init success reply: a human-readable name for the + * machine the server runs on. "" until the handshake succeeds (or when an + * older server omits the field). + */ + serverName: string; + /** + * False when reconnecting can't help until the user changes something on + * the host (e.g. tmux missing or too old). Absent means retryable. + */ + retryable?: boolean; +}; + +/** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */ +export type G2MirrorHistoryReply = { + /** Absolute index of lines[0]; the page covers [start, start + lines.length). */ + start: number; + /** Oldest index still retained by the wrapper (older requests return nothing). */ + oldest: number; + /** Current splice point (next line to be archived). */ + next: number; + /** Plain text, ANSI-stripped, oldest-to-newest. */ + lines: string[]; +}; diff --git a/app/ui/dashboard-settings.ts b/app/ui/dashboard-settings.ts index 72052c43..5e69dd07 100644 --- a/app/ui/dashboard-settings.ts +++ b/app/ui/dashboard-settings.ts @@ -1340,11 +1340,28 @@ export const terminalNewConnectionSetting = new ConfigSettingString({ label: "New connection", storageKey: "terminal.newConnectionDraft", defaultValue: "", - editorTitle: "g2mirror connection string (g2mirror://token@host)", + editorTitle: "Connection (ssh://user@host or g2mirror://token@host)", glassesEditTitle: "Add connection", normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(), }); +/** + * Staging buffer for the Terminal app's SSH password prompt: the worker opens + * the phone's (masked) text editor on it, then moves what was typed into the + * platform keystore (app/native/ssh) and clears it as soon as the user + * confirms or cancels on the glasses. Not listed in the Settings app. + */ +export const terminalSshPasswordSetting = new ConfigSettingString({ + id: "terminal-ssh-password", + label: "SSH password", + storageKey: "terminal.sshPasswordDraft", + defaultValue: "", + inputKind: "password", + editorTitle: "SSH password", + glassesEditTitle: "SSH password", + normalize: (value) => (value ?? "").replace(/[\r\n]+/g, ""), +}); + /** * Staging buffer for the T3 Code app's Pair-environment screen: the phone * text editor types the `t3 pair` link into it, and the app reads it back diff --git a/hooks/before-prepare/faceclaw-kotlin.js b/hooks/before-prepare/faceclaw-kotlin.js index 435b315f..03dc7ecb 100644 --- a/hooks/before-prepare/faceclaw-kotlin.js +++ b/hooks/before-prepare/faceclaw-kotlin.js @@ -1,8 +1,11 @@ const { buildKotlin, checkAndroidRuntime } = require('../../scripts/kotlin-build.cjs'); +const { buildGoSsh } = require('../../scripts/go-ssh-build.cjs'); module.exports = function (hookArgs) { // NativeScript parses hooks with an older JavaScript parser; avoid optional chaining. const { platform, release } = hookArgs.prepareData; if (platform === 'android') checkAndroidRuntime(); - return buildKotlin(platform, release ? 'release' : 'debug'); + return buildKotlin(platform, release ? 'release' : 'debug').then(function () { + return buildGoSsh(platform); + }); }; diff --git a/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawSshListener.kt b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawSshListener.kt new file mode 100644 index 00000000..f513f3bb --- /dev/null +++ b/native/kotlin/shared/src/commonMain/kotlin/com/faceclaw/app/callbacks/FaceclawSshListener.kt @@ -0,0 +1,9 @@ +package com.faceclaw.app + +/** + * Events from FaceclawSshChannel, delivered on the thread that opened the + * channel. See native/ssh/faceclawssh.go (Listener) for the kinds and payloads. + */ +interface FaceclawSshListener { + fun onEvent(kind: String?, payload: String?): Unit +} diff --git a/native/ssh/README.md b/native/ssh/README.md new file mode 100644 index 00000000..90a77de9 --- /dev/null +++ b/native/ssh/README.md @@ -0,0 +1,43 @@ +# Faceclaw SSH transport + +The Terminal app's SSH client: a small Go package over +[golang.org/x/crypto/ssh](https://pkg.go.dev/golang.org/x/crypto/ssh), bound +into the apps with gomobile. It provides text-message channels over SSH: + +- **exec**: run a command on the host, exchanging newline-delimited text + (used for tmux control mode and the tmux session poller; see + `app/apps/terminal/tmux-client.ts`). +- **websocket**: a WebSocket to an address as seen from the host, through a + `direct-tcpip` channel (used to tunnel g2mirror-server's protocol). + +Channels to the same host and credentials share one SSH connection, with a +keepalive that fails them promptly when the peer silently disappears. Host +keys are pinned by the app (first connection reports the presented key so +the user can verify its fingerprint). Authentication uses a non-exportable +ECDSA P-256 key held by the platform keystore (Android Keystore/StrongBox, +iOS Secure Enclave; see `FaceclawSsh.kt` / `FaceclawSsh.m`) and, if the +server allows it, a password saved encrypted on the phone. + +## Building + +`scripts/go-ssh-build.cjs` runs `gomobile bind` (pinned in `go.mod`'s tool +block) from the NativeScript before-prepare hook and stages +`faceclaw-ssh.aar` / `Faceclawssh.xcframework` into the local +`@faceclaw/kotlin` plugin. It needs Go 1.26+ on PATH, plus the Android NDK +(Android) or Xcode (iOS); a content stamp skips rebuilds when the Go sources +haven't changed. + +## Testing + +`go test -race ./...` runs the transport against an in-process SSH server +(host-key pinning, password and keyboard-interactive auth, key auth through +a fake platform signer, exec framing, the websocket tunnel, connection +sharing and loss). + +## Keeping it current + +x/crypto/ssh is the security boundary against a malicious host or a +man in the middle; update it promptly when advisories appear +(`go get golang.org/x/crypto@latest && go mod tidy`). A Go panic in any +goroutine terminates the app: the package recovers in the goroutines it +owns, but not inside the library's own. diff --git a/native/ssh/channels.go b/native/ssh/channels.go new file mode 100644 index 00000000..cfc03dc7 --- /dev/null +++ b/native/ssh/channels.go @@ -0,0 +1,254 @@ +package faceclawssh + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "net" + "net/url" + "strings" + "time" + "unicode/utf8" + + "github.com/gorilla/websocket" + "golang.org/x/crypto/ssh" +) + +type closedPayload struct { + ExitStatus *int `json:"exitStatus,omitempty"` + Signal string `json:"signal,omitempty"` + Code *int `json:"code,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// runExec runs command on the host and relays newline-delimited text both +// ways until the command exits, the connection drops, or Close. +func (c *Channel) runExec(conn *pooledConn, command string) { + session, err := conn.client.NewSession() + if err != nil { + c.fail(channelOpenFailure(conn, err)) + return + } + defer session.Close() + stdin, err1 := session.StdinPipe() + stdout, err2 := session.StdoutPipe() + stderr, err3 := session.StderrPipe() + if err := errors.Join(err1, err2, err3); err != nil { + c.fail(&failure{Kind: "channel", Message: err.Error()}) + return + } + if err := session.Start(command); err != nil { + c.fail(&failure{Kind: "channel", Message: "could not run command: " + err.Error()}) + return + } + go func() { + <-c.ctx.Done() + session.Close() + }() + c.markOpen() + go func() { + defer c.guard() + for text := range c.sendQ { + if _, err := io.WriteString(stdin, text+"\n"); err != nil { + return + } + } + // Close was called and the queue has drained: EOF tells the command + // we're done (tmux control mode detaches on it). + stdin.Close() + }() + stderrDone := make(chan struct{}) + go func() { + defer close(stderrDone) + defer c.guard() + readLines(stderr, func(line string) { c.emit("stderr", line) }) + }() + readErr := readLines(stdout, func(line string) { c.emit("text", line) }) + // Deliver the command's last words (e.g. "tmux: command not found") + // before the close event, but don't hang on a stderr that never ends. + select { + case <-stderrDone: + case <-time.After(500 * time.Millisecond): + } + if c.ctx.Err() != nil { + return + } + waitErr := session.Wait() + var exitErr *ssh.ExitError + var missing *ssh.ExitMissingError + switch { + case waitErr == nil: + status := 0 + c.finish("closed", closedPayload{ExitStatus: &status}) + case errors.As(waitErr, &exitErr): + status := exitErr.ExitStatus() + c.finish("closed", closedPayload{ExitStatus: &status, Signal: exitErr.Signal()}) + case errors.As(waitErr, &missing): + // The channel closed without an exit status: usually the connection + // went away under it. + c.fail(lostFailure(conn, readErr)) + default: + c.fail(lostFailure(conn, waitErr)) + } +} + +// readLines calls emit for each line of r (without its newline) and returns +// the read error that ended it (nil at EOF). Lines may be arbitrarily long. +func readLines(r io.Reader, emit func(string)) error { + reader := bufio.NewReaderSize(r, 64*1024) + for { + line, err := reader.ReadBytes('\n') + if len(line) > 0 { + if line[len(line)-1] == '\n' { + line = line[:len(line)-1] + } + emit(escapeLine(line)) + } + if err == io.EOF { + return nil + } + if err != nil { + return err + } + } +} + +// escapeLine makes a line safe to hand across the gomobile boundary as a +// string (which must be valid UTF-8). Valid UTF-8 passes through. Otherwise +// every byte >= 0x80 becomes "\ooo" (backslash, three octal digits): the same +// escape tmux control mode uses for control characters and backslashes in +// %output, so a %output line split mid-character still decodes back to its +// exact bytes. (Outside %output a literal backslash is ambiguous with this +// escape; such lines are only ever displayed.) +func escapeLine(line []byte) string { + if utf8.Valid(line) { + return string(line) + } + var b strings.Builder + for _, c := range line { + if c >= 0x80 { + fmt.Fprintf(&b, "\\%03o", c) + } else { + b.WriteByte(c) + } + } + return b.String() +} + +// runWebSocket opens rawURL (ws://host:port/path) through the SSH +// connection — host:port is resolved on the SSH server's side — and relays +// text frames. +func (c *Channel) runWebSocket(conn *pooledConn, rawURL string) { + parsed, err := url.Parse(rawURL) + if err != nil || parsed.Scheme != "ws" || parsed.Host == "" { + c.fail(&failure{Kind: "config", Message: fmt.Sprintf("bad websocket URL %q", rawURL)}) + return + } + target := parsed.Host + if parsed.Port() == "" { + target = net.JoinHostPort(parsed.Hostname(), "80") + } + dialer := websocket.Dialer{ + NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + forwarded, err := conn.client.DialContext(ctx, "tcp", target) + if err != nil { + return nil, err + } + return noDeadlineConn{forwarded}, nil + }, + } + // The handshake timeout rides the context: SSH channels can't do deadlines. + handshakeCtx, cancelHandshake := context.WithTimeout(c.ctx, defaultConnectTimeout) + ws, _, err := dialer.DialContext(handshakeCtx, rawURL, nil) + cancelHandshake() + if err != nil { + if c.ctx.Err() != nil { + return + } + c.fail(channelOpenFailure(conn, fmt.Errorf("could not reach %s on the host: %w", target, err))) + return + } + defer ws.Close() + go func() { + <-c.ctx.Done() + ws.Close() + }() + c.markOpen() + go func() { + defer c.guard() + for text := range c.sendQ { + if err := ws.WriteMessage(websocket.TextMessage, []byte(text)); err != nil { + return + } + } + ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye"), + time.Now().Add(time.Second)) + }() + for { + kind, data, err := ws.ReadMessage() + if err != nil { + if c.ctx.Err() != nil { + return + } + var closeErr *websocket.CloseError + if errors.As(err, &closeErr) { + code := closeErr.Code + c.finish("closed", closedPayload{Code: &code, Reason: closeErr.Text}) + return + } + c.fail(lostFailure(conn, err)) + return + } + if kind == websocket.TextMessage { + c.emit("text", string(data)) + } + } +} + +// noDeadlineConn adapts an SSH direct-tcpip channel for the websocket +// library, which sets deadlines the channel doesn't support. Timeouts come +// from contexts and the SSH keepalive instead. +type noDeadlineConn struct{ net.Conn } + +func (noDeadlineConn) SetDeadline(time.Time) error { return nil } +func (noDeadlineConn) SetReadDeadline(time.Time) error { return nil } +func (noDeadlineConn) SetWriteDeadline(time.Time) error { return nil } + +// channelOpenFailure classifies a failure to open a channel: if the SSH +// connection itself is gone it's a network failure (reconnect), otherwise +// the host refused this particular channel. +func channelOpenFailure(conn *pooledConn, err error) *failure { + if isConnDead(conn) { + return &failure{Kind: "network", Message: "connection lost: " + err.Error()} + } + return &failure{Kind: "channel", Message: err.Error()} +} + +func lostFailure(conn *pooledConn, err error) *failure { + message := "connection lost" + if err != nil && !errors.Is(err, io.EOF) { + message += ": " + err.Error() + } + if !isConnDead(conn) { + // The connection is fine; only this channel ended abruptly. + return &failure{Kind: "channel", Message: "channel closed unexpectedly"} + } + return &failure{Kind: "network", Message: message} +} + +func isConnDead(conn *pooledConn) bool { + // client.Wait's goroutine marks the connection dead slightly after the + // channels see their streams end; give it a moment to catch up. + deadline := time.Now().Add(200 * time.Millisecond) + for { + poolMu.Lock() + dead := conn.dead + poolMu.Unlock() + if dead || time.Now().After(deadline) { + return dead + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/native/ssh/faceclawssh.go b/native/ssh/faceclawssh.go new file mode 100644 index 00000000..6ca260a2 --- /dev/null +++ b/native/ssh/faceclawssh.go @@ -0,0 +1,304 @@ +// Package faceclawssh is Faceclaw's SSH transport, bound into the Android and +// iOS apps with gomobile. It exposes text-message channels over SSH: +// +// - "exec": run a command on the host and exchange newline-delimited text +// with it (stdin lines in, stdout lines out). Used for tmux control mode +// and the tmux session poller. +// - "websocket": open a direct-tcpip channel to an address as seen from the +// host (normally g2mirror-server on 127.0.0.1:8737) and speak WebSocket +// text frames over it. +// +// Channels to the same host, user and credentials share one SSH connection +// (see pool.go). Host keys are pinned by the caller: a connection whose host +// presents a key that isn't in the spec's hostKeys fails with a +// "hostkey-unknown" or "hostkey-mismatch" failure carrying the presented key, +// so the app can show the fingerprint and retry once the user has trusted it. +// Authentication uses a platform-held, non-exportable ECDSA P-256 key (the +// Signer interface; Android Keystore / iOS Secure Enclave) and, if the server +// allows it, a password. +// +// Everything crossing the gomobile boundary is a string, []byte or one of the +// interfaces below; structured values are JSON strings. +package faceclawssh + +import ( + "context" + "encoding/json" + "fmt" + "runtime/debug" + "sync" + "time" +) + +// Signer is implemented by the platform: an ECDSA P-256 key whose private +// half never leaves the device's keystore. +type Signer interface { + // PublicKey returns the key's public half, either as X.509 + // SubjectPublicKeyInfo DER (Android's PublicKey.getEncoded()) or as an + // uncompressed X9.62 point, 0x04 || X || Y (iOS's + // SecKeyCopyExternalRepresentation). + PublicKey() []byte + // Sign returns the ASN.1 DER ECDSA signature of SHA-256(data). + Sign(data []byte) ([]byte, error) +} + +// Listener receives a channel's events. Calls arrive on arbitrary goroutines +// (never concurrently for one channel); the platform wrapper hops them onto +// the thread that owns the channel. +// +// Event kinds and payloads: +// - "open": the channel is ready; payload empty. Sends made before this are +// queued and delivered once open. +// - "text": one message (websocket text frame, or one stdout line without +// its newline). Exec lines that aren't valid UTF-8 have every byte >= 0x80 +// escaped as a backslash and three octal digits, matching tmux control +// mode's escaping of control characters (see escapeLine). +// - "stderr": one stderr line of an exec channel, escaped the same way. +// - "closed": the channel ended normally; payload is JSON +// {"exitStatus": n, "signal": "...", "code": n, "reason": "..."} with the +// fields that apply (exec exit status/signal, websocket close code/reason). +// Terminal: no events follow. +// - "failure": the channel could not be opened or was lost; payload is a +// JSON Failure. Terminal: no events follow. +type Listener interface { + OnEvent(kind string, payload string) +} + +// Failure describes why a channel failed, as the JSON payload of a "failure" +// event. +type failure struct { + // "hostkey-unknown": no host key is pinned yet; HostKey is what the host + // presented. "hostkey-mismatch": the host presented a key that isn't + // pinned. "auth": the host refused every credential we have. + // "network": couldn't reach the host, or the connection dropped. + // "channel": the SSH connection is fine but the channel couldn't be + // opened (exec refused, nothing listening at the forwarded address...). + // "config": the spec was malformed. "internal": a bug. + Kind string `json:"kind"` + Message string `json:"message"` + HostKey *hostKeyInfo `json:"hostKey,omitempty"` + // For "auth": the host accepts password (or keyboard-interactive) + // authentication, whether a password was sent, and whether our key was + // offered. + PasswordAllowed bool `json:"passwordAllowed,omitempty"` + PasswordTried bool `json:"passwordTried,omitempty"` + KeyTried bool `json:"keyTried,omitempty"` +} + +func (f *failure) Error() string { return f.Message } + +type hostKeyInfo struct { + // SSH key type, e.g. "ssh-ed25519". + Type string `json:"type"` + // OpenSSH-style SHA-256 fingerprint, "SHA256:<base64>". + Fingerprint string `json:"fingerprint"` + // The key in SSH wire format, base64: what goes in a spec's hostKeys. + Key string `json:"key"` +} + +type channelSpec struct { + // "exec" or "websocket". + Type string `json:"type"` + // exec: the command line, run by the user's login shell. + Command string `json:"command"` + // websocket: ws:// URL, resolved on the host's side of the connection. + URL string `json:"url"` +} + +type openSpec struct { + Host string `json:"host"` + Port int `json:"port"` + User string `json:"user"` + Password string `json:"password"` + // Pinned host keys, SSH wire format, base64. Empty: the first connection + // fails with "hostkey-unknown". + HostKeys []string `json:"hostKeys"` + // Offer the platform key (the Signer passed to Open). + UseKey bool `json:"useKey"` + ConnectTimeoutMs int `json:"connectTimeoutMs"` + KeepaliveIntervalMs int `json:"keepaliveIntervalMs"` + Channel channelSpec `json:"channel"` +} + +const ( + defaultConnectTimeout = 15 * time.Second + defaultKeepaliveInterval = 20 * time.Second + // Messages queued on a channel before Send starts refusing them. + sendQueueCapacity = 4096 + // How long Close waits for queued messages to flush and the far end to + // finish before tearing the channel down. + closeGracePeriod = 2 * time.Second +) + +// Channel is one open (or opening) channel. Methods are safe to call from +// any thread. +type Channel struct { + listener Listener + ctx context.Context + cancel context.CancelFunc + + mu sync.Mutex + closed bool // Close was called: no more sends, no more events + opened bool + sendQ chan string + + finishOnce sync.Once +} + +// Open starts opening a channel described by spec (a JSON openSpec) and +// returns immediately; progress arrives as listener events. signer may be +// nil (no key authentication). +func Open(spec string, signer Signer, listener Listener) *Channel { + ctx, cancel := context.WithCancel(context.Background()) + c := &Channel{ + listener: listener, + ctx: ctx, + cancel: cancel, + sendQ: make(chan string, sendQueueCapacity), + } + go c.run(spec, signer) + return c +} + +// Send queues one message: a websocket text frame, or a line for an exec +// channel's stdin (the newline is added). Returns false if the channel is +// closed or its queue is full. +func (c *Channel) Send(text string) bool { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return false + } + select { + case c.sendQ <- text: + return true + default: + return false + } +} + +// Close ends the channel. Messages already queued are still sent (so a +// parting "unview" reaches the host), then the channel's write side is +// closed and, after a short grace period, the channel is torn down. No +// events are delivered after Close. +func (c *Channel) Close() { + c.mu.Lock() + if c.closed { + c.mu.Unlock() + return + } + c.closed = true + opened := c.opened + close(c.sendQ) + c.mu.Unlock() + if !opened { + c.cancel() + return + } + time.AfterFunc(closeGracePeriod, c.cancel) +} + +func (c *Channel) isClosed() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.closed +} + +func (c *Channel) emit(kind, payload string) { + if c.isClosed() { + return + } + c.listener.OnEvent(kind, payload) +} + +func (c *Channel) markOpen() { + c.mu.Lock() + c.opened = true + c.mu.Unlock() + c.emit("open", "") +} + +// finish delivers the channel's one terminal event ("closed" or "failure"). +func (c *Channel) finish(kind string, payload any) { + c.finishOnce.Do(func() { + encoded, err := json.Marshal(payload) + if err != nil { + encoded = []byte(`{"kind":"internal","message":"unencodable event"}`) + } + c.emit(kind, string(encoded)) + c.cancel() + }) +} + +func (c *Channel) fail(f *failure) { c.finish("failure", f) } + +// guard turns a panic in one of our goroutines into a failure event instead +// of crashing the app (an unrecovered Go panic kills the whole process). +func (c *Channel) guard() { + if r := recover(); r != nil { + c.fail(&failure{Kind: "internal", Message: fmt.Sprintf("internal error: %v\n%s", r, debug.Stack())}) + } +} + +func (c *Channel) run(specJSON string, signer Signer) { + defer c.guard() + var spec openSpec + if err := json.Unmarshal([]byte(specJSON), &spec); err != nil { + c.fail(&failure{Kind: "config", Message: "bad channel spec: " + err.Error()}) + return + } + if spec.Host == "" || spec.User == "" { + c.fail(&failure{Kind: "config", Message: "host and user are required"}) + return + } + if spec.Port == 0 { + spec.Port = 22 + } + if !spec.UseKey { + signer = nil + } + conn, err := acquire(c.ctx, &spec, signer) + if err != nil { + if c.ctx.Err() != nil { + return + } + c.fail(asFailure(err)) + return + } + defer conn.release() + switch spec.Channel.Type { + case "exec": + c.runExec(conn, spec.Channel.Command) + case "websocket": + c.runWebSocket(conn, spec.Channel.URL) + default: + c.fail(&failure{Kind: "config", Message: fmt.Sprintf("unknown channel type %q", spec.Channel.Type)}) + } +} + +func asFailure(err error) *failure { + if f, ok := err.(*failure); ok { + return f + } + return &failure{Kind: "network", Message: err.Error()} +} + +// AuthorizedKey formats a platform public key (see Signer.PublicKey) as an +// authorized_keys line: "ecdsa-sha2-nistp256 AAAA... comment". +func AuthorizedKey(publicKey []byte, comment string) (string, error) { + key, err := sshPublicKey(publicKey) + if err != nil { + return "", err + } + return authorizedKeyLine(key, comment), nil +} + +// Fingerprint returns the OpenSSH SHA-256 fingerprint ("SHA256:...") of a +// platform public key. +func Fingerprint(publicKey []byte) (string, error) { + key, err := sshPublicKey(publicKey) + if err != nil { + return "", err + } + return fingerprint(key), nil +} diff --git a/native/ssh/faceclawssh_test.go b/native/ssh/faceclawssh_test.go new file mode 100644 index 00000000..cb6da45c --- /dev/null +++ b/native/ssh/faceclawssh_test.go @@ -0,0 +1,526 @@ +package faceclawssh + +import ( + "bufio" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gorilla/websocket" + "golang.org/x/crypto/ssh" +) + +// ---- test SSH server ---- + +type testServer struct { + addr string + hostKey ssh.Signer + accepts atomic.Int32 + listener net.Listener +} + +type serverOptions struct { + password string // "" = password auth disabled + keyboardInteractive bool // offer the password via keyboard-interactive instead + authorizedKey ssh.PublicKey +} + +func newTestServer(t *testing.T, opts serverOptions) *testServer { + t.Helper() + _, priv, _ := ed25519.GenerateKey(rand.Reader) + hostKey, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + config := &ssh.ServerConfig{} + if opts.password != "" && !opts.keyboardInteractive { + config.PasswordCallback = func(_ ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) { + if string(password) == opts.password { + return nil, nil + } + return nil, fmt.Errorf("wrong password") + } + } + if opts.password != "" && opts.keyboardInteractive { + config.KeyboardInteractiveCallback = func(_ ssh.ConnMetadata, challenge ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) { + answers, err := challenge("", "", []string{"Password: "}, []bool{false}) + if err != nil { + return nil, err + } + if len(answers) == 1 && answers[0] == opts.password { + return nil, nil + } + return nil, fmt.Errorf("wrong password") + } + } + if opts.authorizedKey != nil { + config.PublicKeyCallback = func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + if string(key.Marshal()) == string(opts.authorizedKey.Marshal()) { + return nil, nil + } + return nil, fmt.Errorf("unknown key") + } + } + config.AddHostKey(hostKey) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := &testServer{addr: listener.Addr().String(), hostKey: hostKey, listener: listener} + t.Cleanup(func() { listener.Close() }) + go func() { + for { + tcp, err := listener.Accept() + if err != nil { + return + } + server.accepts.Add(1) + go server.serve(tcp, config) + } + }() + return server +} + +func (s *testServer) serve(tcp net.Conn, config *ssh.ServerConfig) { + conn, chans, reqs, err := ssh.NewServerConn(tcp, config) + if err != nil { + tcp.Close() + return + } + defer conn.Close() + go ssh.DiscardRequests(reqs) // replies false to keepalives, which still counts as alive + for newChannel := range chans { + switch newChannel.ChannelType() { + case "session": + go serveSession(newChannel) + case "direct-tcpip": + go serveDirectTCPIP(newChannel) + default: + newChannel.Reject(ssh.UnknownChannelType, "nope") + } + } +} + +// serveSession implements a few fake commands: +// - "echo": echo stdin lines back with a "> " prefix until EOF, exit 0 +// - "bytes": print an invalid-UTF-8 line and a stderr line, exit 3 +func serveSession(newChannel ssh.NewChannel) { + channel, requests, err := newChannel.Accept() + if err != nil { + return + } + defer channel.Close() + for req := range requests { + if req.Type != "exec" { + req.Reply(false, nil) + continue + } + var payload struct{ Command string } + ssh.Unmarshal(req.Payload, &payload) + req.Reply(true, nil) + status := 0 + switch payload.Command { + case "echo": + scanner := bufio.NewScanner(channel) + for scanner.Scan() { + fmt.Fprintf(channel, "> %s\n", scanner.Text()) + } + case "bytes": + channel.Write([]byte("%output %1 caf\xc3\n%output %1 \xa9 ok\nplain ✓\n")) + channel.Stderr().Write([]byte("oops\n")) + status = 3 + default: + channel.Stderr().Write([]byte("unknown command\n")) + status = 127 + } + channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{uint32(status)})) + return + } +} + +func serveDirectTCPIP(newChannel ssh.NewChannel) { + var target struct { + Host string + Port uint32 + OriginHost string + OriginPort uint32 + } + if err := ssh.Unmarshal(newChannel.ExtraData(), &target); err != nil { + newChannel.Reject(ssh.ConnectionFailed, "bad payload") + return + } + upstream, err := net.Dial("tcp", net.JoinHostPort(target.Host, fmt.Sprint(target.Port))) + if err != nil { + newChannel.Reject(ssh.ConnectionFailed, err.Error()) + return + } + channel, requests, err := newChannel.Accept() + if err != nil { + upstream.Close() + return + } + go ssh.DiscardRequests(requests) + go func() { io.Copy(upstream, channel); upstream.Close() }() + io.Copy(channel, upstream) + channel.Close() +} + +// ---- test client plumbing ---- + +type event struct{ kind, payload string } + +type recorder struct { + events chan event +} + +func newRecorder() *recorder { return &recorder{events: make(chan event, 256)} } + +func (r *recorder) OnEvent(kind, payload string) { r.events <- event{kind, payload} } + +func (r *recorder) next(t *testing.T) event { + t.Helper() + select { + case e := <-r.events: + return e + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for event") + return event{} + } +} + +func (r *recorder) expect(t *testing.T, kind string) event { + t.Helper() + e := r.next(t) + if e.kind != kind { + t.Fatalf("got event %s(%s), want %s", e.kind, e.payload, kind) + } + return e +} + +func (r *recorder) expectFailure(t *testing.T) failure { + t.Helper() + e := r.expect(t, "failure") + var f failure + if err := json.Unmarshal([]byte(e.payload), &f); err != nil { + t.Fatal(err) + } + return f +} + +type softwareSigner struct{ key *ecdsa.PrivateKey } + +func newSoftwareSigner(t *testing.T) *softwareSigner { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + return &softwareSigner{key: key} +} + +func (s *softwareSigner) PublicKey() []byte { + der, _ := x509.MarshalPKIXPublicKey(&s.key.PublicKey) + return der +} + +func (s *softwareSigner) Sign(data []byte) ([]byte, error) { + digest := sha256.Sum256(data) + return ecdsa.SignASN1(rand.Reader, s.key, digest[:]) +} + +func (s *softwareSigner) sshKey(t *testing.T) ssh.PublicKey { + key, err := ssh.NewPublicKey(&s.key.PublicKey) + if err != nil { + t.Fatal(err) + } + return key +} + +func specFor(server *testServer, mutate func(*openSpec)) string { + host, port, _ := net.SplitHostPort(server.addr) + var portNumber int + fmt.Sscan(port, &portNumber) + spec := openSpec{ + Host: host, + Port: portNumber, + User: "jim", + HostKeys: []string{base64.StdEncoding.EncodeToString(server.hostKey.PublicKey().Marshal())}, + Channel: channelSpec{Type: "exec", Command: "echo"}, + } + if mutate != nil { + mutate(&spec) + } + encoded, _ := json.Marshal(spec) + return string(encoded) +} + +func resetPool() { + poolMu.Lock() + defer poolMu.Unlock() + for key, conn := range pool { + conn.client.Close() + delete(pool, key) + } +} + +// ---- tests ---- + +func TestHostKeyPinning(t *testing.T) { + defer resetPool() + server := newTestServer(t, serverOptions{password: "pw"}) + wantKey := base64.StdEncoding.EncodeToString(server.hostKey.PublicKey().Marshal()) + + rec := newRecorder() + Open(specFor(server, func(s *openSpec) { s.HostKeys = nil; s.Password = "pw" }), nil, rec) + f := rec.expectFailure(t) + if f.Kind != "hostkey-unknown" || f.HostKey == nil || f.HostKey.Key != wantKey || + f.HostKey.Type != ssh.KeyAlgoED25519 || !strings.HasPrefix(f.HostKey.Fingerprint, "SHA256:") { + t.Fatalf("unexpected failure %+v", f) + } + + _, otherPriv, _ := ed25519.GenerateKey(rand.Reader) + other, _ := ssh.NewSignerFromKey(otherPriv) + rec = newRecorder() + Open(specFor(server, func(s *openSpec) { + s.HostKeys = []string{base64.StdEncoding.EncodeToString(other.PublicKey().Marshal())} + s.Password = "pw" + }), nil, rec) + f = rec.expectFailure(t) + if f.Kind != "hostkey-mismatch" || f.HostKey.Key != wantKey { + t.Fatalf("unexpected failure %+v", f) + } + + rec = newRecorder() + ch := Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec) + rec.expect(t, "open") + ch.Close() +} + +func TestPasswordAuth(t *testing.T) { + for _, interactive := range []bool{false, true} { + t.Run(fmt.Sprintf("keyboardInteractive=%v", interactive), func(t *testing.T) { + defer resetPool() + server := newTestServer(t, serverOptions{password: "secret", keyboardInteractive: interactive}) + + rec := newRecorder() + Open(specFor(server, nil), nil, rec) + f := rec.expectFailure(t) + if f.Kind != "auth" || !f.PasswordAllowed || f.PasswordTried { + t.Fatalf("no password: %+v", f) + } + + rec = newRecorder() + Open(specFor(server, func(s *openSpec) { s.Password = "wrong" }), nil, rec) + f = rec.expectFailure(t) + if f.Kind != "auth" || !f.PasswordTried { + t.Fatalf("wrong password: %+v", f) + } + + rec = newRecorder() + ch := Open(specFor(server, func(s *openSpec) { s.Password = "secret" }), nil, rec) + rec.expect(t, "open") + ch.Send("hi") + if e := rec.expect(t, "text"); e.payload != "> hi" { + t.Fatalf("got %q", e.payload) + } + ch.Close() + }) + } +} + +func TestKeyAuth(t *testing.T) { + defer resetPool() + signer := newSoftwareSigner(t) + server := newTestServer(t, serverOptions{authorizedKey: signer.sshKey(t)}) + + rec := newRecorder() + ch := Open(specFor(server, func(s *openSpec) { s.UseKey = true }), signer, rec) + rec.expect(t, "open") + ch.Close() + + // A key the server doesn't know, and no password support. + resetPool() + rec = newRecorder() + Open(specFor(server, func(s *openSpec) { s.UseKey = true }), newSoftwareSigner(t), rec) + f := rec.expectFailure(t) + if f.Kind != "auth" || !f.KeyTried || f.PasswordAllowed { + t.Fatalf("unexpected failure %+v", f) + } + + line, err := AuthorizedKey(signer.PublicKey(), "Faceclaw on my phone") + if err != nil || !strings.HasPrefix(line, "ecdsa-sha2-nistp256 AAAA") || !strings.HasSuffix(line, " Faceclaw-on-my-phone") { + t.Fatalf("AuthorizedKey = %q, %v", line, err) + } + parsed, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line)) + if err != nil || string(parsed.Marshal()) != string(signer.sshKey(t).Marshal()) { + t.Fatalf("authorized key does not round-trip: %v", err) + } + // The uncompressed-point form iOS hands us parses to the same key. + point := elliptic.Marshal(elliptic.P256(), signer.key.X, signer.key.Y) //nolint:staticcheck + fromPoint, err := Fingerprint(point) + fromDER, _ := Fingerprint(signer.PublicKey()) + if err != nil || fromPoint != fromDER { + t.Fatalf("fingerprints differ: %s vs %s (%v)", fromPoint, fromDER, err) + } +} + +func TestExecFraming(t *testing.T) { + defer resetPool() + server := newTestServer(t, serverOptions{password: "pw"}) + rec := newRecorder() + Open(specFor(server, func(s *openSpec) { s.Password = "pw"; s.Channel.Command = "bytes" }), nil, rec) + rec.expect(t, "open") + var texts, stderr []string + var closed closedPayload + for done := false; !done; { + e := rec.next(t) + switch e.kind { + case "text": + texts = append(texts, e.payload) + case "stderr": + stderr = append(stderr, e.payload) + case "closed": + json.Unmarshal([]byte(e.payload), &closed) + done = true + default: + t.Fatalf("unexpected %s(%s)", e.kind, e.payload) + } + } + want := []string{`%output %1 caf\303`, `%output %1 \251 ok`, "plain ✓"} + if strings.Join(texts, "|") != strings.Join(want, "|") { + t.Fatalf("texts = %q, want %q", texts, want) + } + if len(stderr) != 1 || stderr[0] != "oops" { + t.Fatalf("stderr = %q", stderr) + } + if closed.ExitStatus == nil || *closed.ExitStatus != 3 { + t.Fatalf("closed = %+v", closed) + } +} + +func TestWebSocketTunnelAndSharing(t *testing.T) { + defer resetPool() + upgrader := websocket.Upgrader{} + var serverConns sync.WaitGroup + wsServer := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + return + } + serverConns.Add(1) + defer serverConns.Done() + defer conn.Close() + for { + kind, data, err := conn.ReadMessage() + if err != nil { + return + } + if string(data) == "quit" { + conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(4000, "asked to quit")) + return + } + conn.WriteMessage(kind, append([]byte("echo:"), data...)) + } + })} + wsListener, _ := net.Listen("tcp", "127.0.0.1:0") + go wsServer.Serve(wsListener) + defer wsServer.Close() + + server := newTestServer(t, serverOptions{password: "pw"}) + wsSpec := specFor(server, func(s *openSpec) { + s.Password = "pw" + s.Channel = channelSpec{Type: "websocket", URL: "ws://" + wsListener.Addr().String() + "/"} + }) + recA, recB := newRecorder(), newRecorder() + a := Open(wsSpec, nil, recA) + b := Open(wsSpec, nil, recB) + // Sent before open: queued until the channel is up. + a.Send(`{"type":"init"}`) + recA.expect(t, "open") + recB.expect(t, "open") + if e := recA.expect(t, "text"); e.payload != `echo:{"type":"init"}` { + t.Fatalf("got %q", e.payload) + } + b.Send("quit") + e := recB.expect(t, "closed") + var closed closedPayload + json.Unmarshal([]byte(e.payload), &closed) + if closed.Code == nil || *closed.Code != 4000 || closed.Reason != "asked to quit" { + t.Fatalf("closed = %+v", closed) + } + if n := server.accepts.Load(); n != 1 { + t.Fatalf("expected both channels on one SSH connection, got %d connections", n) + } + + // Close flushes queued messages before tearing down. + a.Send("last words") + a.Close() + time.Sleep(300 * time.Millisecond) + select { + case e := <-recA.events: + t.Fatalf("event after Close: %s(%s)", e.kind, e.payload) + default: + } + + // Nothing listening at the forwarded address: a channel failure, not a + // network one (the SSH connection is fine). + recC := newRecorder() + Open(specFor(server, func(s *openSpec) { + s.Password = "pw" + s.Channel = channelSpec{Type: "websocket", URL: "ws://127.0.0.1:1/"} + }), nil, recC) + if f := recC.expectFailure(t); f.Kind != "channel" { + t.Fatalf("unexpected failure %+v", f) + } +} + +func TestConnectionLoss(t *testing.T) { + defer resetPool() + server := newTestServer(t, serverOptions{password: "pw"}) + rec := newRecorder() + Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec) + rec.expect(t, "open") + // Kill the SSH connection under the channel. + poolMu.Lock() + for _, conn := range pool { + conn.client.Close() + } + poolMu.Unlock() + if f := rec.expectFailure(t); f.Kind != "network" { + t.Fatalf("unexpected failure %+v", f) + } + // The next channel dials a fresh connection. + rec = newRecorder() + ch := Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec) + rec.expect(t, "open") + ch.Close() + if n := server.accepts.Load(); n != 2 { + t.Fatalf("expected a second connection, got %d", n) + } +} + +func TestNetworkFailure(t *testing.T) { + rec := newRecorder() + Open(`{"host":"127.0.0.1","port":1,"user":"jim","channel":{"type":"exec","command":"x"}}`, nil, rec) + if f := rec.expectFailure(t); f.Kind != "network" { + t.Fatalf("unexpected failure %+v", f) + } + rec = newRecorder() + Open(`not json`, nil, rec) + if f := rec.expectFailure(t); f.Kind != "config" { + t.Fatalf("unexpected failure %+v", f) + } +} diff --git a/native/ssh/go.mod b/native/ssh/go.mod new file mode 100644 index 00000000..b2d34a18 --- /dev/null +++ b/native/ssh/go.mod @@ -0,0 +1,21 @@ +module github.com/jimrandomh/faceclaw/native/ssh + +go 1.26.0 + +require ( + github.com/gorilla/websocket v1.5.3 + golang.org/x/crypto v0.59.0 +) + +require ( + golang.org/x/mobile v0.0.0-20261011034528-197770444867 // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/tools v0.52.0 // indirect +) + +tool ( + golang.org/x/mobile/cmd/gobind + golang.org/x/mobile/cmd/gomobile +) diff --git a/native/ssh/go.sum b/native/ssh/go.sum new file mode 100644 index 00000000..02707999 --- /dev/null +++ b/native/ssh/go.sum @@ -0,0 +1,16 @@ +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/mobile v0.0.0-20261011034528-197770444867 h1:rav73cdd7OQUPgt1aIFbZQTiPNnjfueKXvfOiLCY0Ss= +golang.org/x/mobile v0.0.0-20261011034528-197770444867/go.mod h1:HR/iBzuQmVTl/us733QPwrqHp43a8m9ZLgyKXD3ST6U= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= diff --git a/native/ssh/interop_test.go b/native/ssh/interop_test.go new file mode 100644 index 00000000..1e5167b1 --- /dev/null +++ b/native/ssh/interop_test.go @@ -0,0 +1,58 @@ +package faceclawssh + +import ( + "encoding/json" + "net" + "os" + "strconv" + "testing" +) + +// TestOpenSSHInterop checks the parts of the handshake that need no +// credentials against a real sshd: key exchange, host key reporting and +// pinning, and how an authentication refusal is classified. Opt-in: +// +// FACECLAW_SSH_INTEROP_ADDR=127.0.0.1:22 go test -run Interop -v +// +// Compare the logged fingerprint with `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub`. +// It makes one failed login attempt (no password, an unknown key) as +// FACECLAW_SSH_INTEROP_USER (default: $USER). +func TestOpenSSHInterop(t *testing.T) { + addr := os.Getenv("FACECLAW_SSH_INTEROP_ADDR") + if addr == "" { + t.Skip("FACECLAW_SSH_INTEROP_ADDR not set") + } + defer resetPool() + user := os.Getenv("FACECLAW_SSH_INTEROP_USER") + if user == "" { + user = os.Getenv("USER") + } + host, portText, err := net.SplitHostPort(addr) + if err != nil { + t.Fatal(err) + } + port, _ := strconv.Atoi(portText) + spec := func(hostKeys []string) string { + encoded, _ := json.Marshal(openSpec{ + Host: host, Port: port, User: user, HostKeys: hostKeys, UseKey: true, + Channel: channelSpec{Type: "exec", Command: "true"}, + }) + return string(encoded) + } + + rec := newRecorder() + Open(spec(nil), newSoftwareSigner(t), rec) + f := rec.expectFailure(t) + if f.Kind != "hostkey-unknown" || f.HostKey == nil { + t.Fatalf("first contact: %+v", f) + } + t.Logf("host key: %s %s", f.HostKey.Type, f.HostKey.Fingerprint) + + rec = newRecorder() + Open(spec([]string{f.HostKey.Key}), newSoftwareSigner(t), rec) + auth := rec.expectFailure(t) + if auth.Kind != "auth" || !auth.KeyTried { + t.Fatalf("pinned, unknown key: %+v", auth) + } + t.Logf("auth refusal: %+v", auth) +} diff --git a/native/ssh/keys.go b/native/ssh/keys.go new file mode 100644 index 00000000..3d876086 --- /dev/null +++ b/native/ssh/keys.go @@ -0,0 +1,91 @@ +package faceclawssh + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/sha256" + "crypto/x509" + "encoding/asn1" + "encoding/base64" + "errors" + "fmt" + "io" + "math/big" + "strings" + + "golang.org/x/crypto/ssh" +) + +// platformSigner adapts the platform's keystore-backed Signer to ssh.Signer. +// The platform signs SHA-256(data) with ECDSA P-256 and returns ASN.1 DER; +// SSH wants the signature as two mpints (RFC 5656 §3.1.2). +type platformSigner struct { + signer Signer + pub ssh.PublicKey +} + +func newPlatformSigner(signer Signer) (*platformSigner, error) { + pub, err := sshPublicKey(signer.PublicKey()) + if err != nil { + return nil, err + } + return &platformSigner{signer: signer, pub: pub}, nil +} + +func (p *platformSigner) PublicKey() ssh.PublicKey { return p.pub } + +func (p *platformSigner) Sign(_ io.Reader, data []byte) (*ssh.Signature, error) { + der, err := p.signer.Sign(data) + if err != nil { + return nil, fmt.Errorf("platform key signing failed: %w", err) + } + var sig struct{ R, S *big.Int } + rest, err := asn1.Unmarshal(der, &sig) + if err != nil || len(rest) != 0 || sig.R == nil || sig.S == nil || sig.R.Sign() <= 0 || sig.S.Sign() <= 0 { + return nil, errors.New("platform key returned a malformed signature") + } + blob := ssh.Marshal(struct{ R, S *big.Int }{sig.R, sig.S}) + return &ssh.Signature{Format: p.pub.Type(), Blob: blob}, nil +} + +// sshPublicKey parses a platform public key (SubjectPublicKeyInfo DER or an +// uncompressed P-256 point) into an ecdsa-sha2-nistp256 SSH key. +func sshPublicKey(encoded []byte) (ssh.PublicKey, error) { + var pub *ecdsa.PublicKey + if len(encoded) == 65 && encoded[0] == 4 { + parsed, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), encoded) + if err != nil { + return nil, fmt.Errorf("bad P-256 point: %v", err) + } + pub = parsed + } else { + parsed, err := x509.ParsePKIXPublicKey(encoded) + if err != nil { + return nil, fmt.Errorf("bad public key: %v", err) + } + ecdsaKey, ok := parsed.(*ecdsa.PublicKey) + if !ok { + return nil, fmt.Errorf("unsupported public key type %T", parsed) + } + pub = ecdsaKey + } + if pub.Curve != elliptic.P256() { + return nil, errors.New("only P-256 keys are supported") + } + return ssh.NewPublicKey(pub) +} + +func authorizedKeyLine(key ssh.PublicKey, comment string) string { + line := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) + comment = strings.Join(strings.Fields(comment), "-") + if comment != "" { + line += " " + comment + } + return line +} + +// fingerprint is OpenSSH's SHA256 fingerprint format (unpadded base64). +func fingerprint(key ssh.PublicKey) string { + sum := sha256.Sum256(key.Marshal()) + return "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:]) +} diff --git a/native/ssh/pool.go b/native/ssh/pool.go new file mode 100644 index 00000000..8720c439 --- /dev/null +++ b/native/ssh/pool.go @@ -0,0 +1,416 @@ +package faceclawssh + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "log" + "net" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/crypto/ssh" +) + +// SSH connections are shared between channels with the same host, port, +// user, credentials and pinned keys: the Terminal app's session poller and +// each of its view windows ride one TCP connection. A connection with no +// channels left lingers briefly (a view window closing and reopening shouldn't +// pay a fresh handshake) and is then closed. A keepalive probe closes +// connections whose peer has silently gone away, which fails every channel on +// them so the app's reconnect logic takes over. + +const idleLinger = 15 * time.Second + +type pooledConn struct { + key string + client *ssh.Client + + // Guarded by poolMu. + refs int + dead bool + linger *time.Timer +} + +type dialCall struct { + done chan struct{} + err error +} + +var ( + poolMu sync.Mutex + pool = map[string]*pooledConn{} + dialing = map[string]*dialCall{} +) + +func poolKey(spec *openSpec, signer *platformSigner) string { + h := sha256.New() + fmt.Fprintf(h, "%s\x00%d\x00%s\x00%s\x00", spec.Host, spec.Port, spec.User, spec.Password) + for _, key := range spec.HostKeys { + fmt.Fprintf(h, "%s\x00", key) + } + if signer != nil { + h.Write(signer.pub.Marshal()) + } + fmt.Fprintf(h, "\x00%d", spec.KeepaliveIntervalMs) + return hex.EncodeToString(h.Sum(nil)) +} + +// acquire returns a live pooled connection for spec, dialing one if needed +// (concurrent callers for the same key share a single dial). The caller must +// release() it. +func acquire(ctx context.Context, spec *openSpec, signer Signer) (*pooledConn, error) { + var ps *platformSigner + if signer != nil { + var err error + if ps, err = newPlatformSigner(signer); err != nil { + return nil, &failure{Kind: "config", Message: "client key unusable: " + err.Error()} + } + } + key := poolKey(spec, ps) + for { + poolMu.Lock() + if conn := pool[key]; conn != nil && !conn.dead { + conn.refs++ + if conn.linger != nil { + conn.linger.Stop() + conn.linger = nil + } + poolMu.Unlock() + return conn, nil + } + if call := dialing[key]; call != nil { + poolMu.Unlock() + select { + case <-call.done: + case <-ctx.Done(): + return nil, ctx.Err() + } + if call.err != nil { + return nil, call.err + } + continue + } + call := &dialCall{done: make(chan struct{})} + dialing[key] = call + poolMu.Unlock() + + conn, err := dial(spec, ps, key) + poolMu.Lock() + delete(dialing, key) + if err == nil { + pool[key] = conn + } + call.err = err + close(call.done) + poolMu.Unlock() + if err != nil { + return nil, err + } + // Loop around to take a reference like any other caller. + } +} + +func (conn *pooledConn) release() { + poolMu.Lock() + defer poolMu.Unlock() + conn.refs-- + if conn.refs > 0 || conn.dead { + return + } + conn.linger = time.AfterFunc(idleLinger, func() { + poolMu.Lock() + idle := conn.refs == 0 && !conn.dead + if idle { + conn.dead = true + if pool[conn.key] == conn { + delete(pool, conn.key) + } + } + poolMu.Unlock() + if idle { + conn.client.Close() + } + }) +} + +// markDead removes a connection from the pool once its transport has ended, +// so the next acquire dials afresh. +func (conn *pooledConn) markDead() { + poolMu.Lock() + defer poolMu.Unlock() + conn.dead = true + if conn.linger != nil { + conn.linger.Stop() + conn.linger = nil + } + if pool[conn.key] == conn { + delete(pool, conn.key) + } +} + +// hostKeyChecker pins the host key: only keys listed in the spec are +// accepted, and whatever the host presented is kept for the failure report. +type hostKeyChecker struct { + known [][]byte + presented ssh.PublicKey + rejected bool +} + +func newHostKeyChecker(encoded []string) (*hostKeyChecker, error) { + checker := &hostKeyChecker{} + for _, entry := range encoded { + wire, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entry)) + if err != nil { + return nil, fmt.Errorf("bad pinned host key: %v", err) + } + if _, err := ssh.ParsePublicKey(wire); err != nil { + return nil, fmt.Errorf("bad pinned host key: %v", err) + } + checker.known = append(checker.known, wire) + } + return checker, nil +} + +func (h *hostKeyChecker) check(_ string, _ net.Addr, key ssh.PublicKey) error { + h.presented = key + wire := key.Marshal() + for _, known := range h.known { + if bytes.Equal(known, wire) { + return nil + } + } + h.rejected = true + return errors.New("host key not trusted") +} + +// algorithms lists host key algorithms with the pinned keys' types first, so +// a host with several host keys presents the one we pinned rather than +// whichever the default preference order favors. +func (h *hostKeyChecker) algorithms() []string { + var preferred []string + seen := map[string]bool{} + add := func(algorithm string) { + if !seen[algorithm] { + seen[algorithm] = true + preferred = append(preferred, algorithm) + } + } + for _, wire := range h.known { + key, err := ssh.ParsePublicKey(wire) + if err != nil { + continue + } + if key.Type() == ssh.KeyAlgoRSA { + add(ssh.KeyAlgoRSASHA512) + add(ssh.KeyAlgoRSASHA256) + continue + } + add(key.Type()) + } + if len(preferred) == 0 { + return nil // the library default + } + for _, algorithm := range ssh.SupportedAlgorithms().HostKeys { + add(algorithm) + } + return preferred +} + +func (h *hostKeyChecker) failure() *failure { + if h.presented == nil { + return nil + } + info := &hostKeyInfo{ + Type: h.presented.Type(), + Fingerprint: fingerprint(h.presented), + Key: base64.StdEncoding.EncodeToString(h.presented.Marshal()), + } + if len(h.known) == 0 { + return &failure{Kind: "hostkey-unknown", Message: "Unknown host key " + info.Fingerprint, HostKey: info} + } + return &failure{Kind: "hostkey-mismatch", Message: "Host key changed: now " + info.Fingerprint, HostKey: info} +} + +// errNoPassword aborts authentication when the host would accept a password +// but we don't have one; the "auth" failure then asks the app to prompt. +var errNoPassword = errors.New("password required") + +type authState struct { + mu sync.Mutex + passwordAllowed bool + passwordTried bool + keyTried bool +} + +func (a *authState) set(update func(*authState)) { + a.mu.Lock() + update(a) + a.mu.Unlock() +} + +func authMethods(spec *openSpec, signer *platformSigner, state *authState) []ssh.AuthMethod { + var methods []ssh.AuthMethod + if signer != nil { + methods = append(methods, ssh.PublicKeysCallback(func() ([]ssh.Signer, error) { + state.set(func(a *authState) { a.keyTried = true }) + return []ssh.Signer{signer}, nil + })) + } + password := spec.Password + methods = append(methods, + ssh.PasswordCallback(func() (string, error) { + state.set(func(a *authState) { a.passwordAllowed = true }) + if password == "" { + return "", errNoPassword + } + state.set(func(a *authState) { a.passwordTried = true }) + return password, nil + }), + // Many hosts (PAM-backed sshd, e.g. macOS) take passwords through + // keyboard-interactive. Answer hidden prompts with the password and + // visible ones with nothing. + ssh.KeyboardInteractive(func(_, _ string, questions []string, echos []bool) ([]string, error) { + if len(questions) == 0 { + return nil, nil + } + state.set(func(a *authState) { a.passwordAllowed = true }) + if password == "" { + return nil, errNoPassword + } + state.set(func(a *authState) { a.passwordTried = true }) + answers := make([]string, len(questions)) + for i := range questions { + if !echos[i] { + answers[i] = password + } + } + return answers, nil + }), + ) + return methods +} + +func dial(spec *openSpec, signer *platformSigner, key string) (*pooledConn, error) { + timeout := defaultConnectTimeout + if spec.ConnectTimeoutMs > 0 { + timeout = time.Duration(spec.ConnectTimeoutMs) * time.Millisecond + } + checker, err := newHostKeyChecker(spec.HostKeys) + if err != nil { + return nil, &failure{Kind: "config", Message: err.Error()} + } + addr := net.JoinHostPort(spec.Host, strconv.Itoa(spec.Port)) + dialer := net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second} + tcp, err := dialer.Dial("tcp", addr) + if err != nil { + return nil, &failure{Kind: "network", Message: describeNetError(err)} + } + // Bound the whole handshake, not just the TCP connect. + tcp.SetDeadline(time.Now().Add(timeout)) + state := &authState{} + config := &ssh.ClientConfig{ + User: spec.User, + Auth: authMethods(spec, signer, state), + HostKeyCallback: checker.check, + HostKeyAlgorithms: checker.algorithms(), + ClientVersion: "SSH-2.0-Faceclaw", + Timeout: timeout, + } + sshConn, chans, reqs, err := ssh.NewClientConn(tcp, addr, config) + if err != nil { + tcp.Close() + if checker.rejected { + return nil, checker.failure() + } + state.mu.Lock() + defer state.mu.Unlock() + if errors.Is(err, errNoPassword) || strings.Contains(err.Error(), "unable to authenticate") { + message := "The host refused this device's key." + switch { + case state.passwordTried: + message = "The host refused the password." + case state.passwordAllowed: + message = "The host wants a password." + case signer == nil: + message = "The host accepts neither passwords nor keys we have." + } + return nil, &failure{ + Kind: "auth", + Message: message, + PasswordAllowed: state.passwordAllowed, + PasswordTried: state.passwordTried, + KeyTried: state.keyTried, + } + } + return nil, &failure{Kind: "network", Message: "SSH handshake failed: " + describeNetError(err)} + } + tcp.SetDeadline(time.Time{}) + client := ssh.NewClient(sshConn, chans, reqs) + conn := &pooledConn{key: key, client: client} + log.Printf("faceclawssh: connected to %s@%s", spec.User, addr) + go func() { + err := client.Wait() + log.Printf("faceclawssh: connection to %s ended: %v", addr, err) + conn.markDead() + }() + interval := defaultKeepaliveInterval + if spec.KeepaliveIntervalMs > 0 { + interval = time.Duration(spec.KeepaliveIntervalMs) * time.Millisecond + } + go keepalive(conn, interval) + return conn, nil +} + +// keepalive probes the host every interval and closes the connection if a +// probe goes unanswered for a whole interval, so a dead peer (phone switched +// networks, laptop asleep) fails the channels promptly instead of hanging. +func keepalive(conn *pooledConn, interval time.Duration) { + defer func() { + if r := recover(); r != nil { + log.Printf("faceclawssh: keepalive panic: %v", r) + conn.client.Close() + } + }() + ticker := time.NewTicker(interval) + defer ticker.Stop() + for range ticker.C { + poolMu.Lock() + dead := conn.dead + poolMu.Unlock() + if dead { + return + } + reply := make(chan error, 1) + go func() { + _, _, err := conn.client.SendRequest("keepalive@openssh.com", true, nil) + reply <- err + }() + select { + case err := <-reply: + if err != nil { + conn.client.Close() + return + } + case <-time.After(interval): + log.Printf("faceclawssh: keepalive timed out; closing") + conn.client.Close() + return + } + } +} + +func describeNetError(err error) string { + message := err.Error() + // "dial tcp 1.2.3.4:22: connect: connection refused" → keep the tail. + if index := strings.LastIndex(message, ": "); index >= 0 && strings.HasPrefix(message, "dial ") { + return message[index+2:] + } + return message +} diff --git a/scripts/go-ssh-build.cjs b/scripts/go-ssh-build.cjs new file mode 100644 index 00000000..b947914e --- /dev/null +++ b/scripts/go-ssh-build.cjs @@ -0,0 +1,129 @@ +// Builds the Go SSH transport (native/ssh) with gomobile and stages it into +// the local @faceclaw/kotlin NativeScript plugin next to the shared Kotlin +// artifacts: platforms/android/faceclaw-ssh.aar and +// platforms/ios/Faceclawssh.xcframework. Run from the before-prepare hook; +// a content stamp skips the (~10 s) gomobile build when nothing changed. +const { spawn, spawnSync } = require('node:child_process'); +const crypto = require('node:crypto'); +const { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } = require('node:fs'); +const path = require('node:path'); + +const root = path.resolve(__dirname, '..'); +const source = path.join(root, 'native/ssh'); +const buildDir = path.join(source, 'build'); +const plugin = path.join(root, 'native/kotlin/plugin/platforms'); + +// Bump to force a rebuild when the gomobile invocation below changes. +const BUILD_RECIPE = 2; + +function sourceHash(platform) { + const hash = crypto.createHash('sha256'); + hash.update(`${BUILD_RECIPE}\n${platform}\n`); + const files = readdirSync(source) + .filter(name => (name.endsWith('.go') && !name.endsWith('_test.go')) || name === 'go.mod' || name === 'go.sum') + .sort(); + for (const name of files) { + hash.update(`${name}\n`); + hash.update(readFileSync(path.join(source, name))); + } + return hash.digest('hex'); +} + +function findGo() { + const probe = spawnSync('go', ['version'], { encoding: 'utf8' }); + if (probe.status !== 0) { + throw new Error('Building the SSH transport needs Go 1.26 or newer on PATH (e.g. "brew install go").'); + } +} + +function newestNdk() { + if (process.env.ANDROID_NDK_HOME && existsSync(process.env.ANDROID_NDK_HOME)) return process.env.ANDROID_NDK_HOME; + const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT; + if (!sdk) throw new Error('ANDROID_HOME must be set to build the SSH transport for Android.'); + const ndkRoot = path.join(sdk, 'ndk'); + const versions = existsSync(ndkRoot) ? readdirSync(ndkRoot).sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) : []; + if (!versions.length) throw new Error(`No Android NDK under ${ndkRoot}; install one with the SDK manager.`); + return path.join(ndkRoot, versions[0]); +} + +// gomobile's ObjC headers say "@import Foundation;", which fails wherever +// Clang modules are off (the NativeScript app target's compile, and its +// metadata generator). A plain #import means the same thing everywhere. +function patchGomobileHeaders(xcframework) { + const walk = (dir) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, entry.name); + if (entry.isDirectory()) walk(file); + else if (entry.name.endsWith('.h')) { + const text = readFileSync(file, 'utf8'); + const patched = text.replace(/^@import Foundation;$/gm, '#import <Foundation/Foundation.h>'); + if (patched !== text) writeFileSync(file, patched); + } + } + }; + walk(xcframework); +} + +function run(command, args, env) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { cwd: source, stdio: 'inherit', env }); + child.on('error', reject); + child.on('exit', (code, signal) => { + if (code === 0) resolve(); + else reject(new Error(`${command} ${args[0]} failed (${signal || code})`)); + }); + }); +} + +async function buildGoSsh(platform) { + if (!['android', 'ios'].includes(platform)) throw new Error(`Unsupported platform: ${platform}`); + const stampFile = path.join(buildDir, `.stamp-${platform}`); + const output = platform === 'android' + ? path.join(buildDir, 'faceclaw-ssh.aar') + : path.join(buildDir, 'Faceclawssh.xcframework'); + const staged = platform === 'android' + ? path.join(plugin, 'android/faceclaw-ssh.aar') + : path.join(plugin, 'ios/Faceclawssh.xcframework'); + const hash = sourceHash(platform); + const fresh = existsSync(output) && existsSync(stampFile) && readFileSync(stampFile, 'utf8') === hash; + if (!fresh) { + findGo(); + console.log(`[go-ssh] Building ${platform}`); + mkdirSync(path.join(buildDir, 'bin'), { recursive: true }); + const env = { ...process.env, PATH: `${path.join(buildDir, 'bin')}${path.delimiter}${process.env.PATH}` }; + // gomobile bind finds gobind on PATH; build both from the versions pinned + // in go.mod's tool block. + await run('go', ['build', '-o', path.join(buildDir, 'bin') + path.sep, 'golang.org/x/mobile/cmd/gomobile', 'golang.org/x/mobile/cmd/gobind'], env); + const common = ['-ldflags=-s -w', '-trimpath']; + rmSync(output, { recursive: true, force: true }); + if (platform === 'android') { + env.ANDROID_NDK_HOME = newestNdk(); + await run('gomobile', ['bind', '-target=android/arm64', '-androidapi', '24', '-javapkg', 'com.faceclaw.ssh', ...common, '-o', output, '.'], env); + } else { + await run('gomobile', ['bind', '-target=ios,iossimulator', '-iosversion', '15.0', ...common, '-o', output, '.'], env); + patchGomobileHeaders(output); + } + writeFileSync(stampFile, hash); + } + // Stage only when the staged copy is missing or stale; preserve mtimes on + // no-op builds (NativeScript uses them to detect changes). + const stagedStamp = path.join(buildDir, `.staged-${platform}`); + if (existsSync(staged) && existsSync(stagedStamp) && readFileSync(stagedStamp, 'utf8') === hash) return; + mkdirSync(path.dirname(staged), { recursive: true }); + rmSync(staged, { recursive: true, force: true }); + cpSync(output, staged, { recursive: true }); + writeFileSync(stagedStamp, hash); + if (platform === 'android') { + // As in kotlin-build.cjs: NativeScript's metadata task tracks jars by + // path, so force it to regenerate for the new classes. + rmSync(path.join(root, 'platforms/android/app/src/main/assets/metadata'), { recursive: true, force: true }); + } +} + +module.exports = { buildGoSsh }; +if (require.main === module) { + buildGoSsh(process.argv[2]).catch(error => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/scripts/hooks/faceclaw-kotlin.before-prepare.js b/scripts/hooks/faceclaw-kotlin.before-prepare.js index 435b315f..03dc7ecb 100644 --- a/scripts/hooks/faceclaw-kotlin.before-prepare.js +++ b/scripts/hooks/faceclaw-kotlin.before-prepare.js @@ -1,8 +1,11 @@ const { buildKotlin, checkAndroidRuntime } = require('../../scripts/kotlin-build.cjs'); +const { buildGoSsh } = require('../../scripts/go-ssh-build.cjs'); module.exports = function (hookArgs) { // NativeScript parses hooks with an older JavaScript parser; avoid optional chaining. const { platform, release } = hookArgs.prepareData; if (platform === 'android') checkAndroidRuntime(); - return buildKotlin(platform, release ? 'release' : 'debug'); + return buildKotlin(platform, release ? 'release' : 'debug').then(function () { + return buildGoSsh(platform); + }); }; diff --git a/tests/terminal-connections.test.cjs b/tests/terminal-connections.test.cjs new file mode 100644 index 00000000..19c46fbc --- /dev/null +++ b/tests/terminal-connections.test.cjs @@ -0,0 +1,56 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { loader } = require('./helpers/load-typescript.cjs'); + +const settings = new Map(); +const connections = loader({}, { + '../../native/settings-store': { + getStringSetting: (key, fallback) => (settings.has(key) ? settings.get(key) : fallback), + setStringSetting: (key, value) => settings.set(key, value), + }, +})('app/apps/terminal/connections.ts'); + +// vm-realm objects: compare as plain JSON. +const plain = (value) => JSON.parse(JSON.stringify(value)); + +test('ssh:// strings select tmux by default', () => { + assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@laptop')), { user: 'jim', host: 'laptop', port: 22, mode: 'tmux' }); + assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@laptop:2222/')), { user: 'jim', host: 'laptop', port: 2222, mode: 'tmux' }); + assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@[fd7a::1]:22')), { user: 'jim', host: 'fd7a::1', port: 22, mode: 'tmux' }); + assert.equal(connections.parseSshConnectionString('ssh://jim%40corp@laptop').user, 'jim@corp'); +}); + +test('?g2mirror= tunnels a g2mirror server over ssh', () => { + assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@laptop?g2mirror=tok')), { + user: 'jim', host: 'laptop', port: 22, mode: 'g2mirror', authToken: 'tok', targetHost: '127.0.0.1', targetPort: 8737, + }); + const custom = connections.parseSshConnectionString('ssh://jim@laptop?g2mirror=tok@en@localhost:9000'); + assert.equal(custom.authToken, 'tok@en'); + assert.equal(custom.targetHost, 'localhost'); + assert.equal(custom.targetPort, 9000); +}); + +test('malformed ssh:// strings are rejected', () => { + for (const url of ['ssh://laptop', 'ssh://jim@', 'ssh://jim@laptop:0', 'ssh://jim@laptop?mode=tmux', 'ssh://jim@laptop?g2mirror=', 'ssh://jim@laptop?g2mirror=tok@host:99999', 'ssh://jim@laptop?g2mirror']) { + assert.equal(connections.parseSshConnectionString(url), null, url); + } +}); + +test('any-kind parsing and host labels', () => { + assert.equal(connections.parseAnyConnectionString('g2mirror://tok@laptop').kind, 'g2mirror'); + assert.equal(connections.parseAnyConnectionString('ssh://jim@laptop').kind, 'ssh'); + assert.equal(connections.parseAnyConnectionString('http://laptop'), null); + assert.equal(connections.connectionStringHostLabel('ssh://jim@laptop?g2mirror=secret'), 'jim@laptop'); + assert.equal(connections.connectionStringHostLabel('ssh://jim@laptop:2222'), 'jim@laptop:2222'); + assert.equal(connections.connectionStringHostLabel('ssh://jim@[fd7a::1]'), 'jim@[fd7a::1]'); + assert.equal(connections.connectionStringHostLabel('g2mirror://tok@laptop'), 'laptop'); +}); + +test('stored connections keep pinned host keys', () => { + connections.saveConnections([{ id: 'c1', url: 'ssh://jim@laptop', serverName: null, enabled: true, hostKeys: ['AAAA'] }]); + connections.updateConnection('c1', { hostKeys: ['AAAA', 'BBBB'] }); + assert.deepEqual(plain(connections.loadConnections()[0].hostKeys), ['AAAA', 'BBBB']); + // Entries saved before SSH support have no hostKeys. + settings.set(connections.TERMINAL_CONNECTIONS_KEY, JSON.stringify([{ id: 'c2', url: 'g2mirror://t@h', enabled: true }])); + assert.deepEqual(plain(connections.loadConnections()[0].hostKeys), []); +}); diff --git a/tests/terminal-in-place-view.test.cjs b/tests/terminal-in-place-view.test.cjs index b0550b07..0c582c89 100644 --- a/tests/terminal-in-place-view.test.cjs +++ b/tests/terminal-in-place-view.test.cjs @@ -117,6 +117,12 @@ function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } = }, '../../ui/gestures': { GESTURE_DOUBLE_CLICK: 'double-tap' }, '../../native/g2mirror-client': { G2MirrorClient: FakeClient }, + '../../native/ssh': { + copyToPhoneClipboard() {}, describeSshFailure: (failure) => failure.message, getSshSecret: () => '', + openSshChannel() { throw new Error('no SSH in this test'); }, removeSshSecret() {}, setSshSecret() {}, + sshClientKey: () => ({ authorizedKey: 'ecdsa-sha2-nistp256 AAAA test', fingerprint: 'SHA256:test' }), + }, + './tmux-client': { TmuxClient: class {} }, '../../native/settings-store': { onSettingsStoreChanged() {} }, '../../ui/dashboard-settings': { enumSettingMenuItem() {}, textSettingMenuItem() {}, toggleSettingMenuItem() {}, @@ -124,6 +130,7 @@ function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } = terminalDisplayLayoutSetting: setting('default'), terminalLaunchPresetsSetting: setting(presets), terminalNewConnectionSetting: setting(''), + terminalSshPasswordSetting: setting(''), terminalWakeOnBellSetting: setting(bellWake), }, '../../ui/font-picker': { terminalFontPickerMenuItem() {} }, @@ -132,6 +139,8 @@ function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } = connectionDisplayName: (config) => config.id, loadConnections: () => [{ id: 'c1', url: 'ok', serverName: 'host', enabled: true }], parseConnectionString: () => ({ host: 'host' }), + parseAnyConnectionString: () => ({ kind: 'g2mirror', secure: false, host: 'host', port: 8737, authToken: 'token' }), + connectionStringHostLabel: () => 'host', saveConnections() {}, updateConnection() {}, }, './terminal-emulator': { TerminalEmulator: FakeEmulator }, diff --git a/tests/tmux-client.test.cjs b/tests/tmux-client.test.cjs new file mode 100644 index 00000000..b32f1958 --- /dev/null +++ b/tests/tmux-client.test.cjs @@ -0,0 +1,202 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { spawn, spawnSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); + +const tmux = require('../.test-build/app/apps/terminal/tmux-client.js'); + +// ---- pure helpers ---- + +test('tmux version gate', () => { + assert.deepEqual(tmux.parseTmuxVersion('tmux 3.2a'), [3, 2]); + assert.equal(tmux.tmuxVersionSupported('tmux 3.2a'), true); + assert.equal(tmux.tmuxVersionSupported('tmux 3.8'), true); + assert.equal(tmux.tmuxVersionSupported('tmux 3.1c'), false); + assert.equal(tmux.tmuxVersionSupported('tmux 2.7'), false); + assert.equal(tmux.tmuxVersionSupported('tmux next-3.9'), true); + assert.equal(tmux.tmuxVersionSupported('tmux master'), true); +}); + +test('decodeTmuxOutput undoes tmux and transport escaping', () => { + const bytes = (text) => Array.from(tmux.decodeTmuxOutput(text)); + assert.deepEqual(bytes('a\\015\\012b'), [0x61, 0x0d, 0x0a, 0x62]); + assert.deepEqual(bytes('back\\134slash'), [...Buffer.from('back\\slash')]); + assert.deepEqual(bytes('héllo ✓'), [...Buffer.from('héllo ✓')]); + // A UTF-8 character split across two %output lines arrives escaped. + assert.deepEqual([...bytes('caf\\303'), ...bytes('\\251')], [...Buffer.from('café')]); + // A lone backslash without three octal digits is literal. + assert.deepEqual(bytes('\\9'), [0x5c, 0x39]); +}); + +test('hostCommand keeps scripts portable across login shells', () => { + assert.equal(tmux.hostCommand('echo hi'), "exec /bin/sh -c 'echo hi'"); + assert.throws(() => tmux.hostCommand("echo 'hi'")); + assert.throws(() => tmux.hostCommand('echo \\\\')); + for (const command of [tmux.pollerCommand(), tmux.viewerCommand('$3'), tmux.launchCommand('shell'), tmux.launchCommand('htop -d 5')]) { + assert.match(command, /^exec \/bin\/sh -c '[^']*'$/); + } + assert.throws(() => tmux.viewerCommand('work')); + assert.throws(() => tmux.launchCommand('rm -rf ~; echo $HOME')); +}); + +test('pane rows and labels', () => { + const fields = ['%3', '$1', 'work', '@2', '1', 'zsh', '2', '0', '4242', '0', '1700000000', '3', 'zsh', '/home/jim/src', 'build\twatcher']; + const row = tmux.parsePaneRow(fields.join('\t')); + assert.equal(row.title, 'build\twatcher'); + assert.equal(row.bells, 3); + assert.equal(row.windowPanes, 2); + assert.equal(tmux.paneLabel(row, 'laptop.local', '/home/jim'), 'work:1.0 build\twatcher'); + assert.equal(tmux.paneLabel({ ...row, title: 'laptop.local' }, 'laptop.local', '/home/jim'), 'work:1.0 zsh ~/src'); + assert.equal(tmux.paneLabel({ ...row, title: 'laptop', windowPanes: 1 }, 'laptop.local', '/home/jim'), 'work:1 zsh ~/src'); + assert.equal(tmux.parsePaneRow('garbage'), null); +}); + +test('snapshot bytes restore cursor and key modes', () => { + const state = tmux.parsePaneState('%1|4|1|1|1|0|1|0|0|0|1|80|2|10|57|5|0'); + assert.equal(state.historyNext, 57); + assert.equal(state.historyOldest, 5); + const text = Buffer.from(tmux.snapshotBytes(state, ['$ ls', 'a b'], [])).toString(); + assert.equal(text, '$ ls\x1b[0m\r\na b\x1b[0m\x1b[2;5H\x1b[?1h'); + // Without history_added (tmux < 3.8), history_size stands in. + assert.equal(tmux.parsePaneState('%1|0|0|1|0|0|1|0|0|0|23|80|24|10||||').historyNext, 10); +}); + +test('send-keys commands are hex and chunked', () => { + const commands = tmux.sendKeysCommands('%4', new Uint8Array(300).fill(0x41)); + assert.equal(commands.length, 2); + assert.match(commands[0], /^send-keys -t %4 -H 41 41 /); +}); + +// ---- against a real tmux server ---- + +const tmuxVersion = spawnSync('tmux', ['-V'], { encoding: 'utf8' }); +const haveTmux = tmuxVersion.status === 0 && tmux.tmuxVersionSupported(tmuxVersion.stdout); + +/** Mimic the SSH transport: run through a shell, split stdout/stderr into lines, escape non-UTF-8 lines. */ +function localChannel(env) { + return (command, listener) => { + const child = spawn('/bin/sh', ['-c', command], { env, stdio: ['pipe', 'pipe', 'pipe'] }); + let closed = false; + // Like the SSH transport, a write to a channel whose command just exited is dropped, not thrown. + child.stdin.on('error', () => {}); + const lines = (stream, emit) => { + let buffered = Buffer.alloc(0); + stream.on('data', (chunk) => { + buffered = Buffer.concat([buffered, chunk]); + let index; + while ((index = buffered.indexOf(0x0a)) >= 0) { + emit(escapeLine(buffered.subarray(0, index))); + buffered = buffered.subarray(index + 1); + } + }); + }; + lines(child.stdout, (line) => !closed && listener.onLine(line)); + lines(child.stderr, (line) => !closed && listener.onStderr(line)); + child.on('spawn', () => listener.onOpen()); + child.on('exit', (status) => { if (!closed) { closed = true; listener.onClosed(status); } }); + return { + send: (line) => { if (closed) return false; child.stdin.write(`${line}\n`); return true; }, + close: () => { if (closed) return; closed = true; child.stdin.end(); setTimeout(() => child.kill(), 500); }, + }; + }; +} + +function escapeLine(bytes) { + const text = bytes.toString('utf8'); + if (Buffer.from(text, 'utf8').equals(bytes)) return text; + return Array.from(bytes, (byte) => (byte >= 0x80 ? `\\${byte.toString(8).padStart(3, '0')}` : String.fromCharCode(byte))).join(''); +} + +function waitFor(predicate, what, timeoutMs = 10_000) { + return new Promise((resolve, reject) => { + const started = Date.now(); + const timer = setInterval(() => { + let value; + try { value = predicate(); } catch (error) { clearInterval(timer); reject(error); return; } + if (value) { clearInterval(timer); resolve(value); } + else if (Date.now() - started > timeoutMs) { clearInterval(timer); reject(new Error(`timed out waiting for ${what}`)); } + }, 50); + }); +} + +test('TmuxClient against a local tmux server', { skip: !haveTmux && 'tmux >= 3.2 not installed' }, async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fc-tmux-')); + const env = { ...process.env, TMUX_TMPDIR: dir, SHELL: '/bin/sh', PS1: '$ ' }; + delete env.TMUX; + const tm = (...args) => spawnSync('tmux', args, { env, encoding: 'utf8' }); + const openChannel = localChannel(env); + const clients = []; + try { + tm('new-session', '-d', '-s', 'work', '-x', '120', '-y', '40', '/bin/sh'); + const control = new tmux.TmuxClient({ openChannel, label: 'test', cols: 80, rows: 20, stateKey: 'test-connection' }); + clients.push(control); + const bells = []; + control.onBell((socket) => bells.push(socket)); + control.start(); + await waitFor(() => control.state().phase === 'connected' && control.state().sessions.length === 1, 'listing'); + assert.equal(control.state().sessions[0].socket, '%0'); + assert.match(control.state().sessions[0].title, /^work:0 /); + + // A bell in the session's current window (tmux's own bell flag misses these). + tm('send-keys', '-t', '%0', '-l', "printf '\\a'"); + tm('send-keys', '-t', '%0', 'Enter'); + await waitFor(() => bells.includes('%0'), 'bell'); + + const launched = await control.launchSession('shell'); + assert.match(launched, /^%\d+$/); + await waitFor(() => control.state().sessions.some((s) => s.socket === launched), 'launched pane in listing'); + + // View the original pane. + const view = new tmux.TmuxClient({ openChannel, label: 'test', cols: 80, rows: 20, stateKey: '' }); + clients.push(view); + let screen = ''; + const snapshots = []; + const histories = []; + view.onTerminalData((data, kind) => { + if (kind === 'snapshot') { screen = ''; snapshots.push(Buffer.from(data).toString()); } + screen += Buffer.from(data).toString(); + }); + view.onSnapshot((next, oldest) => snapshots.push({ next, oldest })); + view.onHistoryLines((reply) => histories.push(reply)); + view.onStateChange((state) => { + if (state.phase === 'connected' && !view.requested) { view.requested = true; view.connectSession('%0'); } + }); + view.onSessionAttached(() => view.view()); + view.start(); + await waitFor(() => snapshots.length >= 2, 'snapshot'); + assert.equal(view.state().phase, 'attached'); + assert.equal(tm('display', '-p', '-t', '%0', '#{window_width}x#{window_height}').stdout.trim(), '80x20'); + + view.sendInput('for i in $(seq 1 60); do echo row$i; done\r'); + await waitFor(() => screen.includes('row60'), 'typed command output'); + + // Re-snapshot: rows have scrolled into the history; page some back. + view.unview(); + view.view(); + await waitFor(() => snapshots.length >= 4, 'second snapshot'); + const { next } = snapshots[snapshots.length - 1]; + assert.ok(next > 20, `history should have grown, next=${next}`); + view.requestHistory(next, 5); + await waitFor(() => histories.length === 1, 'history page'); + assert.equal(histories[0].lines.length, 5); + assert.equal(histories[0].start, next - 5); + assert.ok(histories[0].lines.some((line) => /^row\d+$/.test(line)), JSON.stringify(histories[0].lines)); + + // Unviewing gives the window back its own size. + view.unview(); + await waitFor(() => tm('display', '-p', '-t', '%0', '#{window_width}').stdout.trim() !== '80', 'size restored', 3000).catch(() => {}); + + // The pane going away ends the view. + let detached = null; + view.onSessionDetached((reason) => { detached = reason; }); + view.view(); + tm('kill-pane', '-t', '%0'); + await waitFor(() => detached !== null, 'detach on pane exit'); + } finally { + for (const client of clients) client.stop(); + tm('kill-server'); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index 8f812beb..dc704cf4 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -25,6 +25,9 @@ "../app/g2/keyboard/key-router.ts", "../app/g2/keyboard/pointer.ts", "../app/apps/terminal/terminal-keys.ts", + "../app/native/terminal-session-types.ts", + "../app/apps/terminal/terminal-client.ts", + "../app/apps/terminal/tmux-client.ts", "../app/phone-ui/ble-bandwidth-meter.ts", "../app/apps/terminal/hub-header.ts", "../app/g2/ios-peripheral-identity.ts",