diff --git a/lib/core/ssh/client.dart b/lib/core/ssh/client.dart index 6d77519b8e..71b3bb27fd 100644 --- a/lib/core/ssh/client.dart +++ b/lib/core/ssh/client.dart @@ -17,6 +17,7 @@ import 'package:server_box/core/ssh/noninteractive.dart'; import 'package:server_box/core/ssh/owning_socket.dart'; import 'package:server_box/core/ssh/proxy_command_socket.dart'; import 'package:server_box/core/ssh/proxy_socket.dart'; +import 'package:server_box/core/ssh/tailcat_socket.dart'; import 'package:server_box/data/model/app/error.dart'; import 'package:server_box/data/model/server/host_cert_authority.dart'; import 'package:server_box/data/model/server/server_private_info.dart'; @@ -75,11 +76,15 @@ Future genClient( ); } // Also detect address-level cycles for cloned servers. - final addrKey = 'addr:${ssh.ip}:${ssh.port}'; + final addrKey = ssh.hasTailcat + ? 'tailcat:${Redact.host(ssh.tailcatAddress!.trim())}:${ssh.port}' + : 'addr:${ssh.ip}:${ssh.port}'; if (!chainVisitedServerIds.add(addrKey)) { throw SSHErr( type: SSHErrType.connect, - message: 'Invalid jump chain: address cycle at ${ssh.ip}:${ssh.port}', + message: ssh.hasTailcat + ? 'Invalid jump chain: Tailcat cycle at ${spi.name}:${ssh.port}' + : 'Invalid jump chain: address cycle at ${ssh.ip}:${ssh.port}', ); } @@ -96,6 +101,7 @@ Future genClient( _ when spi.resolvedJumpIds.isNotEmpty => 'jump', _ when ssh.proxyId != null && ssh.proxyId!.trim().isNotEmpty => 'ssh_proxy', _ when ssh.proxyCommand != null => 'proxy', + _ when ssh.hasTailcat => 'tailcat', _ => 'direct', }; if (Diag.enabled) { @@ -104,7 +110,9 @@ Future genClient( 'ssh connect', data: { 'server': Redact.id(spi.id), - 'host': Redact.host(ssh.ip), + 'host': ssh.hasTailcat + ? SshCredential.tailcatPlaceholderHost + : Redact.host(ssh.ip), 'via': via, }, ); @@ -147,7 +155,9 @@ Future genClient( String? alterUser; // Where the socket goes: the configured host, or `alterUrl`'s when the // first did not answer. The authorities are scoped to the host dialled. - var dialHost = ssh.ip; + var dialHost = ssh.hasTailcat + ? SshCredential.tailcatPlaceholderHost + : ssh.ip; var dialPort = ssh.port; final socket = @@ -296,6 +306,15 @@ Future genClient( ); } + if (ssh.hasTailcat) { + return await TailcatSocket.connect( + address: ssh.tailcatAddress!.trim(), + port: ssh.port, + derpMapUrl: ssh.tailcatDerpMapUrl?.trim(), + timeout: timeout, + ); + } + // Direct try { return await DirectSshSocket.connect( diff --git a/lib/core/ssh/host_key_probe.dart b/lib/core/ssh/host_key_probe.dart index af176fe8b0..c8de2367a9 100644 --- a/lib/core/ssh/host_key_probe.dart +++ b/lib/core/ssh/host_key_probe.dart @@ -4,6 +4,7 @@ import 'package:dartssh2/dartssh2.dart'; import 'package:server_box/core/ssh/algorithms.dart'; import 'package:server_box/core/ssh/host_keys.dart'; import 'package:server_box/core/ssh/proxy_socket.dart'; +import 'package:server_box/core/ssh/tailcat_socket.dart'; import 'package:server_box/data/model/server/ssh_credential.dart'; import 'package:server_box/data/model/server/ssh_proxy.dart'; import 'package:server_box/data/store/stores.dart'; @@ -43,6 +44,13 @@ Future probeHostKey( port: ssh.port, timeout: timeout, ) + : ssh.hasTailcat + ? await TailcatSocket.connect( + address: ssh.tailcatAddress!.trim(), + port: ssh.port, + derpMapUrl: ssh.tailcatDerpMapUrl?.trim(), + timeout: timeout, + ) : await SSHSocket.connect( ssh.ip, ssh.port, diff --git a/lib/core/ssh/tailcat_ffi.dart b/lib/core/ssh/tailcat_ffi.dart new file mode 100644 index 0000000000..85530c3803 --- /dev/null +++ b/lib/core/ssh/tailcat_ffi.dart @@ -0,0 +1,839 @@ +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter/foundation.dart' show visibleForTesting; + +/// Status codes returned by upstream `libtailcat` (C ABI v1, `tailcat.h`). +abstract final class TailcatStatus { + static const ok = 0; + static const invalidArgument = 1; + static const closed = 2; + static const timeout = 3; + static const cancelled = 4; + static const failure = 5; + static const eof = 6; +} + +/// Network protocol selectors for `tc_client_dial` and `tc_server_listen`. +abstract final class TailcatNetwork { + static const tcp = 1; + static const udp = 2; +} + +/// Pure-Dart helpers for validating Tailcat addresses and relay map URLs +/// without logging or echoing secret address material. +abstract final class TailcatAddress { + static final _base64UrlChars = RegExp(r'^[A-Za-z0-9_-]+$'); + + /// Minimum plausible length for a `tc`-prefixed CBOR-encoded Tailcat address. + static const _minLength = 16; + + /// Returns whether [raw] has the syntactic shape of a `tc...` Tailcat + /// address (`"tc"` followed by unpadded Base64URL bytes). + /// + /// Full cryptographic/CBOR verification is performed locally by + /// `tc_address_parse` when `libtailcat` is available. + static bool isPlausible(String raw) { + final trimmed = raw.trim(); + if (trimmed.length < _minLength || !trimmed.startsWith('tc')) { + return false; + } + final payload = trimmed.substring(2); + if (!_base64UrlChars.hasMatch(payload)) return false; + try { + final decoded = base64Url.decode(base64Url.normalize(payload)); + return decoded.isNotEmpty; + } on FormatException { + return false; + } + } + + /// Returns whether an optional custom DERP relay map URL is valid. + static bool isValidDerpMapUrl(String raw) { + final trimmed = raw.trim(); + if (trimmed.isEmpty) return true; + final uri = Uri.tryParse(trimmed); + if (uri == null || !uri.hasScheme) return false; + final scheme = uri.scheme.toLowerCase(); + return (scheme == 'https' || scheme == 'http') && uri.host.isNotEmpty; + } +} + +/// Raised when `libtailcat` cannot be loaded or has an incompatible ABI. +final class TailcatUnavailableException implements Exception { + const TailcatUnavailableException(this.message); + + final String message; + + @override + String toString() => 'TailcatUnavailableException: $message'; +} + +/// Raised when a `libtailcat` C API call returns a non-zero `TC_*` status. +final class TailcatApiException implements Exception { + const TailcatApiException(this.status, this.message); + + final int status; + final String message; + + bool get isTimeout => status == TailcatStatus.timeout; + bool get isCancelled => status == TailcatStatus.cancelled; + bool get isClosed => status == TailcatStatus.closed; + bool get isInvalidArgument => status == TailcatStatus.invalidArgument; + + @override + String toString() => 'TailcatApiException($status): $message'; +} + +/// Zero-dependency native memory allocator backed by the platform C runtime. +final class _NativeAlloc { + _NativeAlloc._(this._calloc, this._free); + + static _NativeAlloc? _instance; + + final Pointer Function(int count, int size) _calloc; + final void Function(Pointer ptr) _free; + + static _NativeAlloc get instance => _instance ??= _open(); + + static _NativeAlloc _open() { + final DynamicLibrary lib; + if (Platform.isWindows) { + DynamicLibrary? winLib; + for (final name in const ['ucrtbase.dll', 'msvcrt.dll']) { + try { + winLib = DynamicLibrary.open(name); + break; + } on ArgumentError { + // Try next CRT DLL. + } + } + if (winLib == null) { + throw const TailcatUnavailableException( + 'Unable to load Windows C runtime for Tailcat FFI.', + ); + } + lib = winLib; + } else { + lib = DynamicLibrary.process(); + } + final callocFn = lib.lookupFunction< + Pointer Function(Size, Size), + Pointer Function(int, int)>('calloc'); + final freeFn = lib.lookupFunction< + Void Function(Pointer), + void Function(Pointer)>('free'); + return _NativeAlloc._(callocFn, freeFn); + } + + Pointer calloc(int count, int elementSize) { + final ptr = _calloc(count, elementSize); + if (ptr == nullptr) { + throw StateError('Out of native memory allocating ${count * elementSize}B'); + } + return ptr.cast(); + } + + Pointer allocateUtf8(String value) { + final bytes = utf8.encode(value); + final ptr = calloc(bytes.length + 1, 1); + final view = ptr.asTypedList(bytes.length + 1); + view.setAll(0, bytes); + view[bytes.length] = 0; + return ptr; + } + + void free(Pointer ptr) { + if (ptr == nullptr) return; + _free(ptr.cast()); + } +} + +String _readCString(Pointer ptr) { + if (ptr == nullptr) return ''; + var len = 0; + while (ptr[len] != 0) { + len++; + } + if (len == 0) return ''; + return utf8.decode(ptr.asTypedList(len), allowMalformed: true); +} + +// Native FFI typedefs matching `tailcat.h` (ABI v1). +typedef _TcAbiVersionNative = Uint32 Function(); +typedef _TcAbiVersionDart = int Function(); + +typedef _TcFreeNative = Void Function(Pointer); +typedef _TcFreeDart = void Function(Pointer); + +typedef _TcTokenNewNative = Int32 Function( + Int64 timeoutNs, + Pointer out, + Pointer> error, +); +typedef _TcTokenNewDart = int Function( + int timeoutNs, + Pointer out, + Pointer> error, +); + +typedef _TcHandleOpNative = Int32 Function( + Uint64 handle, + Pointer> error, +); +typedef _TcHandleOpDart = int Function( + int handle, + Pointer> error, +); + +typedef _TcNewFromJsonNative = Int32 Function( + Pointer configJson, + Pointer out, + Pointer> error, +); +typedef _TcNewFromJsonDart = int Function( + Pointer configJson, + Pointer out, + Pointer> error, +); + +typedef _TcClientDialNative = Int32 Function( + Uint64 client, + Uint64 token, + Uint16 port, + Int32 network, + Pointer out, + Pointer> error, +); +typedef _TcClientDialDart = int Function( + int client, + int token, + int port, + int network, + Pointer out, + Pointer> error, +); + +typedef _TcConnIoNative = Int32 Function( + Uint64 connection, + Uint64 token, + Pointer buffer, + Size length, + Pointer count, + Pointer> error, +); +typedef _TcConnIoDart = int Function( + int connection, + int token, + Pointer buffer, + int length, + Pointer count, + Pointer> error, +); + +typedef _TcHandleTokenOpNative = Int32 Function( + Uint64 handle, + Uint64 token, + Pointer> error, +); +typedef _TcHandleTokenOpDart = int Function( + int handle, + int token, + Pointer> error, +); + +typedef _TcAddressParseNative = Int32 Function( + Pointer address, + Pointer> out, + Pointer> error, +); +typedef _TcAddressParseDart = int Function( + Pointer address, + Pointer> out, + Pointer> error, +); + +typedef _TcServerListenNative = Int32 Function( + Uint64 server, + Uint64 token, + Uint16 port, + Int32 network, + Pointer out, + Pointer> error, +); +typedef _TcServerListenDart = int Function( + int server, + int token, + int port, + int network, + Pointer out, + Pointer> error, +); + +typedef _TcListenerAcceptNative = Int32 Function( + Uint64 listener, + Uint64 token, + Pointer out, + Pointer> error, +); +typedef _TcListenerAcceptDart = int Function( + int listener, + int token, + Pointer out, + Pointer> error, +); + +typedef _TcInfoNative = Int32 Function( + Uint64 resource, + Uint64 token, + Pointer> out, + Pointer> error, +); +typedef _TcInfoDart = int Function( + int resource, + int token, + Pointer> out, + Pointer> error, +); + +/// Result of a single `tc_conn_read` call. +final class TailcatReadResult { + const TailcatReadResult({ + required this.status, + required this.bytes, + this.error, + }); + + final int status; + final Uint8List bytes; + final String? error; +} + +/// Result of a single `tc_conn_write` call. +final class TailcatWriteResult { + const TailcatWriteResult({ + required this.status, + required this.written, + this.error, + }); + + final int status; + final int written; + final String? error; +} + +/// Direct `dart:ffi` wrapper around upstream `libtailcat` (ABI v1). +/// +/// Handles are opaque process-wide 64-bit integers owned by the embedded Go +/// runtime, so handles created in one Dart isolate may be read, written, +/// cancelled, or closed from another isolate in the same process. +final class TailcatLibrary { + TailcatLibrary._(DynamicLibrary lib) + : _abiVersion = lib.lookupFunction<_TcAbiVersionNative, _TcAbiVersionDart>( + 'tc_abi_version', + ), + _free = lib.lookupFunction<_TcFreeNative, _TcFreeDart>('tc_free'), + _tokenNew = lib.lookupFunction<_TcTokenNewNative, _TcTokenNewDart>( + 'tc_token_new', + ), + _tokenCancel = lib.lookupFunction<_TcHandleOpNative, _TcHandleOpDart>( + 'tc_token_cancel', + ), + _close = lib.lookupFunction<_TcHandleOpNative, _TcHandleOpDart>( + 'tc_close', + ), + _clientNew = + lib.lookupFunction<_TcNewFromJsonNative, _TcNewFromJsonDart>( + 'tc_client_new', + ), + _clientDial = + lib.lookupFunction<_TcClientDialNative, _TcClientDialDart>( + 'tc_client_dial', + ), + _connRead = lib.lookupFunction<_TcConnIoNative, _TcConnIoDart>( + 'tc_conn_read', + ), + _connWrite = lib.lookupFunction<_TcConnIoNative, _TcConnIoDart>( + 'tc_conn_write', + ), + _connCloseWrite = lib.lookupFunction<_TcHandleTokenOpNative, + _TcHandleTokenOpDart>('tc_conn_close_write'), + _drain = lib.lookupFunction<_TcHandleTokenOpNative, + _TcHandleTokenOpDart>('tc_drain'), + _addressParse = + lib.lookupFunction<_TcAddressParseNative, _TcAddressParseDart>( + 'tc_address_parse', + ), + _serverNew = + lib.lookupFunction<_TcNewFromJsonNative, _TcNewFromJsonDart>( + 'tc_server_new', + ), + _serverStart = lib.lookupFunction<_TcHandleTokenOpNative, + _TcHandleTokenOpDart>('tc_server_start'), + _serverListen = + lib.lookupFunction<_TcServerListenNative, _TcServerListenDart>( + 'tc_server_listen', + ), + _listenerAccept = + lib.lookupFunction<_TcListenerAcceptNative, _TcListenerAcceptDart>( + 'tc_listener_accept', + ), + _info = lib.lookupFunction<_TcInfoNative, _TcInfoDart>('tc_info'); + + static const supportedAbiVersion = 1; + static const envLibPath = 'SERVERBOX_TAILCAT_LIB'; + static const noCancel = 0; + + static final Map _cache = {}; + + final _TcAbiVersionDart _abiVersion; + final _TcFreeDart _free; + final _TcTokenNewDart _tokenNew; + final _TcHandleOpDart _tokenCancel; + final _TcHandleOpDart _close; + final _TcNewFromJsonDart _clientNew; + final _TcClientDialDart _clientDial; + final _TcConnIoDart _connRead; + final _TcConnIoDart _connWrite; + final _TcHandleTokenOpDart _connCloseWrite; + final _TcHandleTokenOpDart _drain; + final _TcAddressParseDart _addressParse; + final _TcNewFromJsonDart _serverNew; + final _TcHandleTokenOpDart _serverStart; + final _TcServerListenDart _serverListen; + final _TcListenerAcceptDart _listenerAccept; + final _TcInfoDart _info; + + /// Resolves and opens `libtailcat` for the current platform, caching the + /// wrapper per isolate. + static TailcatLibrary open({String? libraryPath}) { + final overridePath = + libraryPath?.trim().isNotEmpty == true + ? libraryPath!.trim() + : Platform.environment[envLibPath]?.trim(); + final cacheKey = overridePath ?? ''; + final cached = _cache[cacheKey]; + if (cached != null) return cached; + + final dylib = _loadDynamicLibrary(overridePath); + final wrapper = TailcatLibrary._(dylib); + final abi = wrapper.abiVersion(); + if (abi != supportedAbiVersion) { + throw TailcatUnavailableException( + 'Unsupported libtailcat ABI version $abi (expected $supportedAbiVersion).', + ); + } + _cache[cacheKey] = wrapper; + return wrapper; + } + + /// Returns whether `libtailcat` is loadable in this build/environment. + static bool isAvailable({String? libraryPath}) { + try { + open(libraryPath: libraryPath); + return true; + } on TailcatUnavailableException { + return false; + } + } + + static DynamicLibrary _loadDynamicLibrary(String? overridePath) { + if (overridePath != null && overridePath.isNotEmpty) { + try { + return DynamicLibrary.open(overridePath); + } on ArgumentError catch (e) { + throw TailcatUnavailableException( + 'Failed to load libtailcat from "$overridePath": $e', + ); + } + } + + // Statically linked builds (notably iOS CTailcat.xcframework / c-archive) + // expose `tc_*` symbols directly in the host process image. + if (Platform.isIOS || Platform.isMacOS) { + final proc = DynamicLibrary.process(); + if (proc.providesSymbol('tc_abi_version')) { + return proc; + } + } + + final candidates = _defaultLibraryNames(); + for (final candidate in candidates) { + try { + return DynamicLibrary.open(candidate); + } on ArgumentError { + // Try next candidate. + } + } + + throw TailcatUnavailableException( + 'Native Tailcat library (${candidates.join(', ')}) is not bundled in ' + 'this build. Build libtailcat with tools/tailcat-lib/build.sh or set ' + '$envLibPath.', + ); + } + + static List _defaultLibraryNames() { + if (Platform.isIOS) { + return const ['CTailcat.framework/CTailcat']; + } + if (Platform.isMacOS) { + return const [ + 'libtailcat.dylib', + '@executable_path/../Frameworks/libtailcat.dylib', + 'CTailcat.framework/CTailcat', + ]; + } + if (Platform.isWindows) { + return const ['libtailcat.dll']; + } + // Linux and Android. + return const ['libtailcat.so']; + } + + int abiVersion() => _abiVersion(); + + /// Creates a cancellation/deadline token. Pass `null` for no deadline. + int tokenNew({Duration? timeout}) { + final alloc = _NativeAlloc.instance; + final outPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final timeoutNs = timeout == null + ? -1 + : timeout.isNegative + ? 0 + : timeout.inMicroseconds * 1000; + final status = _tokenNew(timeoutNs, outPtr, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_token_new failed'); + } + return outPtr.value; + } finally { + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + /// Signals cancellation of [token]; safe to call from any thread/isolate. + void tokenCancel(int token) { + if (token == noCancel) return; + final alloc = _NativeAlloc.instance; + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + _tokenCancel(token, errPtr); + _takeCString(errPtr.value); + } finally { + alloc.free(errPtr); + } + } + + /// Retires [handle] and frees its resources. Safe to call on already-closed + /// handles (returns silently on `TC_CLOSED`). + void closeHandle(int handle) { + if (handle == noCancel) return; + final alloc = _NativeAlloc.instance; + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + _close(handle, errPtr); + _takeCString(errPtr.value); + } finally { + alloc.free(errPtr); + } + } + + /// Parses [address] locally and returns its public metadata JSON map + /// (never includes the pre-shared key). + Map parseAddress(String address) { + final alloc = _NativeAlloc.instance; + final addrPtr = alloc.allocateUtf8(address); + final outPtr = alloc.calloc>(1, sizeOf>()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _addressParse(addrPtr, outPtr, errPtr); + final out = _takeCString(outPtr.value); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok || out == null) { + throw TailcatApiException(status, err ?? 'invalid tailcat address'); + } + return json.decode(out) as Map; + } finally { + alloc.free(addrPtr); + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + /// Creates a Tailcat client handle without starting network I/O yet. + int clientNew({ + required String address, + String? privateKey, + String? derpMapUrl, + }) { + final cfg = { + 'address': address, + if (privateKey != null && privateKey.isNotEmpty) 'key': privateKey, + if (derpMapUrl != null && derpMapUrl.isNotEmpty) + 'derp_map_url': derpMapUrl, + }; + final alloc = _NativeAlloc.instance; + final cfgPtr = alloc.allocateUtf8(json.encode(cfg)); + final outPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _clientNew(cfgPtr, outPtr, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_client_new failed'); + } + return outPtr.value; + } finally { + alloc.free(cfgPtr); + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + /// Synchronously dials TCP [port] on [client]'s Tailcat peer. + int clientDialTcp({ + required int client, + required int port, + int token = noCancel, + }) { + final alloc = _NativeAlloc.instance; + final outPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = + _clientDial(client, token, port, TailcatNetwork.tcp, outPtr, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_client_dial failed'); + } + return outPtr.value; + } finally { + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + /// Performs one blocking read into [nativeBuffer] (capacity [capacity]). + /// Always copies any returned bytes before surfacing status/error. + TailcatReadResult connRead({ + required int connection, + required Pointer nativeBuffer, + required int capacity, + int token = noCancel, + }) { + final alloc = _NativeAlloc.instance; + final countPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _connRead( + connection, + token, + nativeBuffer.cast(), + capacity, + countPtr, + errPtr, + ); + final count = countPtr.value; + final err = _takeCString(errPtr.value); + final bytes = count > 0 + ? Uint8List.fromList(nativeBuffer.asTypedList(count)) + : Uint8List(0); + return TailcatReadResult(status: status, bytes: bytes, error: err); + } finally { + alloc.free(countPtr); + alloc.free(errPtr); + } + } + + /// Writes all bytes of [data] to [connection], looping over short writes. + void connWriteAll({ + required int connection, + required Uint8List data, + int token = noCancel, + }) { + if (data.isEmpty) return; + final alloc = _NativeAlloc.instance; + final buf = alloc.calloc(data.length, 1); + final countPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + buf.asTypedList(data.length).setAll(0, data); + var offset = 0; + while (offset < data.length) { + countPtr.value = 0; + errPtr.value = nullptr; + final remaining = data.length - offset; + final slicePtr = Pointer.fromAddress(buf.address + offset); + final status = _connWrite( + connection, + token, + slicePtr.cast(), + remaining, + countPtr, + errPtr, + ); + final written = countPtr.value; + final err = _takeCString(errPtr.value); + offset += written; + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_conn_write failed'); + } + if (written == 0) { + throw const TailcatApiException( + TailcatStatus.failure, + 'tc_conn_write made no progress', + ); + } + } + } finally { + alloc.free(buf); + alloc.free(countPtr); + alloc.free(errPtr); + } + } + + /// Half-closes TCP writes on [connection]. + void connCloseWrite(int connection, {int token = noCancel}) { + final alloc = _NativeAlloc.instance; + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _connCloseWrite(connection, token, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok && status != TailcatStatus.closed) { + throw TailcatApiException(status, err ?? 'tc_conn_close_write failed'); + } + } finally { + alloc.free(errPtr); + } + } + + /// Best-effort bounded drain of TCP shutdown traffic on [clientHandle]. + void drain(int clientHandle, {required Duration timeout}) { + final token = tokenNew(timeout: timeout); + final alloc = _NativeAlloc.instance; + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + _drain(clientHandle, token, errPtr); + _takeCString(errPtr.value); + } finally { + alloc.free(errPtr); + closeHandle(token); + } + } + + /// Allocates a native byte buffer; release with [freeBuffer]. + Pointer allocateBuffer(int bytes) => + _NativeAlloc.instance.calloc(bytes, 1); + + /// Releases a buffer allocated by [allocateBuffer]. + void freeBuffer(Pointer ptr) => _NativeAlloc.instance.free(ptr); + + // --- Server primitives (used by integration tests) --- + + @visibleForTesting + int serverNew(Map config) { + final alloc = _NativeAlloc.instance; + final cfgPtr = alloc.allocateUtf8(json.encode(config)); + final outPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _serverNew(cfgPtr, outPtr, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_server_new failed'); + } + return outPtr.value; + } finally { + alloc.free(cfgPtr); + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + @visibleForTesting + void serverStart(int server, {int token = noCancel}) { + final alloc = _NativeAlloc.instance; + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _serverStart(server, token, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_server_start failed'); + } + } finally { + alloc.free(errPtr); + } + } + + @visibleForTesting + int serverListenTcp(int server, int port, {int token = noCancel}) { + final alloc = _NativeAlloc.instance; + final outPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = + _serverListen(server, token, port, TailcatNetwork.tcp, outPtr, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_server_listen failed'); + } + return outPtr.value; + } finally { + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + @visibleForTesting + int listenerAccept(int listener, {int token = noCancel}) { + final alloc = _NativeAlloc.instance; + final outPtr = alloc.calloc(1, sizeOf()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _listenerAccept(listener, token, outPtr, errPtr); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok) { + throw TailcatApiException(status, err ?? 'tc_listener_accept failed'); + } + return outPtr.value; + } finally { + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + @visibleForTesting + Map info(int handle, {int token = noCancel}) { + final alloc = _NativeAlloc.instance; + final outPtr = alloc.calloc>(1, sizeOf>()); + final errPtr = alloc.calloc>(1, sizeOf>()); + try { + final status = _info(handle, token, outPtr, errPtr); + final out = _takeCString(outPtr.value); + final err = _takeCString(errPtr.value); + if (status != TailcatStatus.ok || out == null) { + throw TailcatApiException(status, err ?? 'tc_info failed'); + } + return json.decode(out) as Map; + } finally { + alloc.free(outPtr); + alloc.free(errPtr); + } + } + + String? _takeCString(Pointer ptr) { + if (ptr == nullptr) return null; + try { + return _readCString(ptr); + } finally { + _free(ptr.cast()); + } + } +} diff --git a/lib/core/ssh/tailcat_socket.dart b/lib/core/ssh/tailcat_socket.dart new file mode 100644 index 0000000000..fd19bd6e31 --- /dev/null +++ b/lib/core/ssh/tailcat_socket.dart @@ -0,0 +1,444 @@ +import 'dart:async'; +import 'dart:isolate'; +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:server_box/core/ssh/tailcat_ffi.dart'; +import 'package:server_box/data/model/app/error.dart'; + +/// Cross-platform [SSHSocket] backed by upstream `libtailcat` (C ABI v1). +/// +/// Connects directly to a Tailcat peer's TCP port (such as `22` for `tailcat +/// serve ssh` or `tailcat serve 22`) over Tailscale's WireGuard/DERP data +/// plane without a Tailscale account, system VPN, or mobile Linux rootfs. +/// +/// Blocking C calls run in dedicated reader and writer isolates so the Flutter +/// UI isolate never stalls. Closing or destroying the socket immediately +/// retires the native connection and client handles, interrupting any blocked +/// read or write. +class TailcatSocket implements SSHSocket { + TailcatSocket._({ + required this._clientHandle, + required this._connHandle, + required this._port, + required this._libraryPath, + required this._readerPort, + required this._writerSendPort, + required this._writerExitPort, + }) { + _readerSub = _readerPort.listen(_onReaderMessage); + _outgoing.stream.listen( + _enqueueWrite, + onDone: _onOutgoingDone, + cancelOnError: true, + ); + } + + static const _readChunkSize = 32 * 1024; + static const _drainTimeout = Duration(milliseconds: 500); + static const _writeCloseTimeout = Duration(seconds: 2); + + final int _clientHandle; + final int _connHandle; + final int _port; + final String? _libraryPath; + final ReceivePort _readerPort; + final SendPort _writerSendPort; + final ReceivePort _writerExitPort; + + final _incoming = StreamController(); + final _outgoing = StreamController>(); + final _done = Completer(); + + StreamSubscription? _readerSub; + Future _writeChain = Future.value(); + Future? _closeFuture; + bool _tearingDown = false; + bool _closed = false; + + /// Connects to TCP [port] on the Tailcat peer identified by [address]. + /// + /// Throws [SSHErr] on invalid configuration, missing `libtailcat`, timeout, + /// or transport failure. Never includes the secret [address] in errors. + static Future connect({ + required String address, + required int port, + String? derpMapUrl, + Duration timeout = const Duration(seconds: 15), + String? libraryPath, + }) async { + final trimmedAddr = address.trim(); + if (!TailcatAddress.isPlausible(trimmedAddr)) { + throw SSHErr( + type: SSHErrType.connect, + message: 'Invalid Tailcat address format.', + ); + } + if (port < 1 || port > 65535) { + throw SSHErr( + type: SSHErrType.connect, + message: 'Invalid Tailcat SSH port: $port.', + ); + } + final trimmedDerp = derpMapUrl?.trim(); + if (trimmedDerp != null && + trimmedDerp.isNotEmpty && + !TailcatAddress.isValidDerpMapUrl(trimmedDerp)) { + throw SSHErr( + type: SSHErrType.connect, + message: 'Invalid Tailcat DERP map URL.', + ); + } + + // Verify library availability and create non-blocking client/token handles + // before spawning the dial isolate. + final TailcatLibrary lib; + try { + lib = TailcatLibrary.open(libraryPath: libraryPath); + } on TailcatUnavailableException catch (e) { + throw SSHErr(type: SSHErrType.connect, message: e.message); + } + + int clientHandle = 0; + int dialToken = 0; + int connHandle = 0; + try { + clientHandle = lib.clientNew( + address: trimmedAddr, + derpMapUrl: trimmedDerp?.isNotEmpty == true ? trimmedDerp : null, + ); + dialToken = lib.tokenNew(timeout: timeout); + + connHandle = await _dialTcpInIsolate( + libraryPath, + clientHandle, + port, + dialToken, + ); + } on TailcatApiException catch (e) { + if (clientHandle != 0) { + final toClose = clientHandle; + clientHandle = 0; + unawaited(_closeHandlesOffThread( + libraryPath: libraryPath, + connHandle: 0, + clientHandle: toClose, + drain: false, + )); + } + throw SSHErr( + type: SSHErrType.connect, + message: _sanitizeError(e, trimmedAddr, port), + ); + } catch (e) { + if (clientHandle != 0) { + final toClose = clientHandle; + clientHandle = 0; + unawaited(_closeHandlesOffThread( + libraryPath: libraryPath, + connHandle: 0, + clientHandle: toClose, + drain: false, + )); + } + if (e is SSHErr) rethrow; + throw SSHErr( + type: SSHErrType.connect, + message: 'Tailcat connect failed on port $port: $e', + ); + } finally { + if (dialToken != 0) { + lib.closeHandle(dialToken); + } + } + + final readerPort = ReceivePort(); + final writerReady = ReceivePort(); + final writerExitPort = ReceivePort(); + try { + await Isolate.spawn( + _readerIsolateEntry, + (connHandle, libraryPath, readerPort.sendPort), + debugName: 'tailcat-reader-$port', + ); + await Isolate.spawn( + _writerIsolateEntry, + (connHandle, libraryPath, writerReady.sendPort), + onExit: writerExitPort.sendPort, + debugName: 'tailcat-writer-$port', + ); + final writerSendPort = await writerReady.first as SendPort; + writerReady.close(); + + return TailcatSocket._( + clientHandle: clientHandle, + connHandle: connHandle, + port: port, + libraryPath: libraryPath, + readerPort: readerPort, + writerSendPort: writerSendPort, + writerExitPort: writerExitPort, + ); + } catch (e) { + readerPort.close(); + writerReady.close(); + writerExitPort.close(); + await _closeHandlesOffThread( + libraryPath: libraryPath, + connHandle: connHandle, + clientHandle: clientHandle, + drain: false, + ); + throw SSHErr( + type: SSHErrType.connect, + message: 'Failed to start Tailcat I/O workers: $e', + ); + } + } + + static String _sanitizeError( + TailcatApiException e, + String secretAddress, + int port, + ) { + final cleaned = e.message.replaceAll(secretAddress, ''); + if (e.isTimeout) { + return 'Tailcat connection timed out (port $port): $cleaned'; + } + if (e.isInvalidArgument) { + return 'Invalid Tailcat configuration: $cleaned'; + } + return 'Tailcat transport error (port $port): $cleaned'; + } + + void _onReaderMessage(dynamic message) { + if (_closed) return; + if (message is TransferableTypedData) { + if (!_incoming.isClosed) { + _incoming.add(message.materialize().asUint8List()); + } + return; + } + if (message is Uint8List) { + if (!_incoming.isClosed) { + _incoming.add(message); + } + return; + } + if (message is String && !_tearingDown && !_incoming.isClosed) { + _incoming.addError( + SSHErr(type: SSHErrType.connect, message: 'Tailcat read failed: $message'), + ); + } + // `null` (EOF/closed) or error terminates the reader loop. + unawaited(_finish(drain: false)); + } + + void _enqueueWrite(List data) { + if (_closed || _tearingDown || data.isEmpty) return; + final bytes = data is Uint8List ? data : Uint8List.fromList(data); + _writeChain = _writeChain.then((_) async { + if (_closed || _tearingDown) return; + final ack = ReceivePort(); + try { + _writerSendPort.send(( + 'write', + TransferableTypedData.fromList([bytes]), + ack.sendPort, + )); + final err = await ack.first; + if (err is String && !_tearingDown && !_incoming.isClosed) { + _incoming.addError( + SSHErr(type: SSHErrType.connect, message: 'Tailcat write failed: $err'), + ); + unawaited(_finish(drain: false)); + } + } finally { + ack.close(); + } + }); + } + + void _onOutgoingDone() { + if (_closed || _tearingDown) return; + _writeChain = _writeChain.then((_) async { + if (_closed || _tearingDown) return; + final ack = ReceivePort(); + try { + _writerSendPort.send(('close_write', null, ack.sendPort)); + await ack.first.timeout(_writeCloseTimeout, onTimeout: () => null); + } finally { + ack.close(); + } + }); + } + + @override + Stream get stream => _incoming.stream; + + @override + StreamSink> get sink => _outgoing.sink; + + @override + Future get done => _done.future; + + @override + Future flush() => _writeChain; + + @override + Future close() => _finish(drain: true); + + @override + void destroy() { + unawaited(_finish(drain: false)); + } + + Future _finish({required bool drain}) { + return _closeFuture ??= _runFinish(drain: drain); + } + + Future _runFinish({required bool drain}) async { + _tearingDown = true; + if (drain) { + try { + await _writeChain.timeout(_writeCloseTimeout); + } catch (_) {} + final ack = ReceivePort(); + try { + _writerSendPort.send(('close_write', null, ack.sendPort)); + await ack.first.timeout(_writeCloseTimeout, onTimeout: () => null); + } catch (_) { + } finally { + ack.close(); + } + } + + // Stop accepting further writes and retire the native handles off the UI + // isolate. Closing the connection immediately interrupts the reader loop. + try { + _writerSendPort.send(('stop', null, null)); + } catch (_) {} + + await _closeHandlesOffThread( + libraryPath: _libraryPath, + connHandle: _connHandle, + clientHandle: _clientHandle, + drain: drain, + ); + + _closed = true; + await _readerSub?.cancel(); + _readerPort.close(); + _writerExitPort.close(); + if (!_incoming.isClosed) { + unawaited(_incoming.close()); + } + if (!_outgoing.isClosed) { + unawaited(_outgoing.close()); + } + if (!_done.isCompleted) { + _done.complete(); + } + } + + static Future _closeHandlesOffThread({ + required String? libraryPath, + required int connHandle, + required int clientHandle, + required bool drain, + }) async { + try { + await Isolate.run(() { + final lib = TailcatLibrary.open(libraryPath: libraryPath); + if (connHandle != 0) { + lib.closeHandle(connHandle); + } + if (clientHandle != 0) { + if (drain) { + lib.drain(clientHandle, timeout: _drainTimeout); + } + lib.closeHandle(clientHandle); + } + }); + } catch (_) { + // Best-effort cleanup during teardown. + } + } + + @override + String toString() => 'TailcatSocket(port: $_port)'; +} + +Future _dialTcpInIsolate( + String? libraryPath, + int clientHandle, + int port, + int dialToken, +) { + return Isolate.run(() { + final isoLib = TailcatLibrary.open(libraryPath: libraryPath); + return isoLib.clientDialTcp( + client: clientHandle, + port: port, + token: dialToken, + ); + }); +} + +void _readerIsolateEntry((int, String?, SendPort) args) { + final (connHandle, libraryPath, sendPort) = args; + final lib = TailcatLibrary.open(libraryPath: libraryPath); + final buf = lib.allocateBuffer(TailcatSocket._readChunkSize); + try { + while (true) { + final res = lib.connRead( + connection: connHandle, + nativeBuffer: buf, + capacity: TailcatSocket._readChunkSize, + ); + if (res.bytes.isNotEmpty) { + sendPort.send(TransferableTypedData.fromList([res.bytes])); + } + if (res.status == TailcatStatus.ok) continue; + if (res.status == TailcatStatus.eof || + res.status == TailcatStatus.closed || + res.status == TailcatStatus.cancelled) { + sendPort.send(null); + } else { + sendPort.send(res.error ?? 'status ${res.status}'); + } + return; + } + } catch (e) { + sendPort.send(e.toString()); + } finally { + lib.freeBuffer(buf); + } +} + +void _writerIsolateEntry((int, String?, SendPort) args) { + final (connHandle, libraryPath, readyPort) = args; + final lib = TailcatLibrary.open(libraryPath: libraryPath); + final cmdPort = ReceivePort(); + readyPort.send(cmdPort.sendPort); + cmdPort.listen((dynamic raw) { + final (op, payload, ackPort) = raw as (String, Object?, SendPort?); + if (op == 'stop') { + cmdPort.close(); + return; + } + try { + if (op == 'write') { + final data = (payload! as TransferableTypedData).materialize().asUint8List(); + lib.connWriteAll(connection: connHandle, data: data); + } else if (op == 'close_write') { + lib.connCloseWrite(connHandle); + } + ackPort?.send(null); + } on TailcatApiException catch (e) { + ackPort?.send(e.message); + } catch (e) { + ackPort?.send(e.toString()); + } + }); +} diff --git a/lib/data/model/server/server_private_info.dart b/lib/data/model/server/server_private_info.dart index d21bd2ec91..55b509b4cf 100644 --- a/lib/data/model/server/server_private_info.dart +++ b/lib/data/model/server/server_private_info.dart @@ -22,6 +22,10 @@ enum SpiValidationError { /// [SshCredential.proxyCommand]. sshProxyConflict, + /// [SshCredential.tailcatAddress] cannot be combined with jump servers, + /// [SshCredential.proxyId], or [SshCredential.proxyCommand]. + tailcatConflict, + /// Neither [Spi.ssh] nor [Spi.monitorHttp] is configured, and the server /// is not [Spi.local]. /// @@ -243,6 +247,10 @@ extension Spix on Spi { final proxy = s.proxyCommand; final hasProxyCommand = proxy != null && proxy.trim().isNotEmpty; final hasProxy = s.proxyId != null && s.proxyId!.trim().isNotEmpty; + final hasTailcat = s.hasTailcat; + if (hasTailcat && (hasJumpServer || hasProxy || hasProxyCommand)) { + return SpiValidationError.tailcatConflict; + } if (hasJumpServer && hasProxyCommand) { return SpiValidationError.jumpServerAndProxyCommandConflict; } @@ -265,8 +273,12 @@ extension Spix on Spi { if (local) return 'localhost'; final s = ssh; // A tunneled server has no address of its own — showing `user@:22` would - // be noise, and showing `127.0.0.1` would be wrong on every such server - if (s != null) return '${s.user}@${s.ip}:${s.port}'; + // be noise, and showing `127.0.0.1` would be wrong on every such server. + // Tailcat addresses are secret capability tokens and are never shown here. + if (s != null) { + final host = s.hasTailcat ? SshCredential.tailcatPlaceholderHost : s.ip; + return '${s.user}@$host:${s.port}'; + } return monitorHttp?.addr ?? id; } diff --git a/lib/data/model/server/ssh_credential.dart b/lib/data/model/server/ssh_credential.dart index f95cc9619d..2b301b61d2 100644 --- a/lib/data/model/server/ssh_credential.dart +++ b/lib/data/model/server/ssh_credential.dart @@ -102,11 +102,26 @@ final class SshCredential { final List? jumpIds; /// Reusable SOCKS5 / HTTP CONNECT proxy (`SshProxy.id`), mutually exclusive - /// with [jumpIds] and [proxyCommand]. + /// with [jumpIds], [proxyCommand], and [tailcatAddress]. final String? proxyId; final String? proxyCommand; + /// Tailcat peer address (`tc...`) dialed directly over Tailcat's WireGuard + /// data plane without a Tailscale account or system VPN. Mutually exclusive + /// with [jumpIds], [proxyId], and [proxyCommand]. + /// + /// Treat as a secret capability token: never log or expose in display strings. + final String? tailcatAddress; + + /// Optional custom DERP relay map URL override for [tailcatAddress]. + /// Null uses Tailcat's default relay map (`https://tailcat.dev/derpmap.json`). + final String? tailcatDerpMapUrl; + + /// Non-secret host placeholder stored in [ip] when a server connects only + /// via [tailcatAddress] and has no direct host/IP. + static const tailcatPlaceholderHost = 'tailcat'; + /// Which protocol carries file contents to and from this host. /// /// Defaulted rather than nullable: every record written before this existed @@ -164,6 +179,8 @@ final class SshCredential { this.jumpIds, this.proxyId, this.proxyCommand, + this.tailcatAddress, + this.tailcatDerpMapUrl, this.fileTransport = SshFileTransport.sftp, this.allowLegacyAlgorithms = false, this.moshEnabled = false, @@ -329,15 +346,21 @@ final class SshCredential { bool get isRoot => user == 'root'; + /// Whether this credential connects through a Tailcat peer address. + bool get hasTailcat => + tailcatAddress != null && tailcatAddress!.trim().isNotEmpty; + /// Whether Mosh can be used for this host's interactive terminal. /// /// Mosh requires direct UDP connectivity to the server and therefore cannot - /// traverse SSH jump hosts, proxies, or custom ProxyCommand streams. + /// traverse SSH jump hosts, proxies, Tailcat tunnels, or custom ProxyCommand + /// streams. bool get canUseMosh => moshEnabled && resolvedJumpIds.isEmpty && (proxyId == null || proxyId!.trim().isEmpty) && - (proxyCommand == null || proxyCommand!.trim().isEmpty); + (proxyCommand == null || proxyCommand!.trim().isEmpty) && + !hasTailcat; SshCredential copyWith({ String? ip, @@ -354,6 +377,8 @@ final class SshCredential { List? Function()? jumpIds, String? Function()? proxyId, String? Function()? proxyCommand, + String? Function()? tailcatAddress, + String? Function()? tailcatDerpMapUrl, SshFileTransport? fileTransport, bool? allowLegacyAlgorithms, bool? moshEnabled, @@ -388,6 +413,12 @@ final class SshCredential { jumpIds: jumpIds != null ? jumpIds() : this.jumpIds, proxyId: proxyId != null ? proxyId() : this.proxyId, proxyCommand: proxyCommand != null ? proxyCommand() : this.proxyCommand, + tailcatAddress: tailcatAddress != null + ? tailcatAddress() + : this.tailcatAddress, + tailcatDerpMapUrl: tailcatDerpMapUrl != null + ? tailcatDerpMapUrl() + : this.tailcatDerpMapUrl, fileTransport: fileTransport ?? this.fileTransport, allowLegacyAlgorithms: allowLegacyAlgorithms ?? this.allowLegacyAlgorithms, @@ -415,6 +446,8 @@ final class SshCredential { forwardAgent == other.forwardAgent && proxyId == other.proxyId && proxyCommand == other.proxyCommand && + tailcatAddress == other.tailcatAddress && + tailcatDerpMapUrl == other.tailcatDerpMapUrl && // Changing how the socket is obtained needs a reconnect just as much // as changing the address does listEquals(resolvedJumpIds, other.resolvedJumpIds) && @@ -442,7 +475,7 @@ final class SshCredential { } @override - int get hashCode => Object.hash( + int get hashCode => Object.hashAll([ ip, port, user, @@ -464,11 +497,13 @@ final class SshCredential { Object.hashAll(resolvedJumpIds), proxyId, proxyCommand, + tailcatAddress, + tailcatDerpMapUrl, fileTransport, allowLegacyAlgorithms, moshEnabled, moshPort, moshServerPath, moshPrediction, - ); + ]); } diff --git a/lib/data/model/server/ssh_credential.g.dart b/lib/data/model/server/ssh_credential.g.dart index 572d55f14e..f5a58d3571 100644 --- a/lib/data/model/server/ssh_credential.g.dart +++ b/lib/data/model/server/ssh_credential.g.dart @@ -28,6 +28,8 @@ SshCredential _$SshCredentialFromJson(Map json) => .toList(), proxyId: json['proxyId'] as String?, proxyCommand: json['proxyCommand'] as String?, + tailcatAddress: json['tailcatAddress'] as String?, + tailcatDerpMapUrl: json['tailcatDerpMapUrl'] as String?, fileTransport: $enumDecodeNullable( _$SshFileTransportEnumMap, @@ -63,6 +65,8 @@ Map _$SshCredentialToJson(SshCredential instance) => 'jumpIds': ?instance.jumpIds, 'proxyId': ?instance.proxyId, 'proxyCommand': ?instance.proxyCommand, + 'tailcatAddress': ?instance.tailcatAddress, + 'tailcatDerpMapUrl': ?instance.tailcatDerpMapUrl, 'fileTransport': _$SshFileTransportEnumMap[instance.fileTransport]!, 'allowLegacyAlgorithms': instance.allowLegacyAlgorithms, 'moshEnabled': instance.moshEnabled, diff --git a/lib/data/store/db.dart b/lib/data/store/db.dart index e4f52208ab..2e23827322 100644 --- a/lib/data/store/db.dart +++ b/lib/data/store/db.dart @@ -247,6 +247,10 @@ class Servers extends Table with SyncMeta { .nullable() .references(SshProxies, #id, onDelete: KeyAction.setNull)(); + /// [SshCredential.tailcatAddress] and [SshCredential.tailcatDerpMapUrl]. + TextColumn get sshTailcatAddress => text().nullable()(); + TextColumn get sshTailcatDerpMapUrl => text().nullable()(); + @override Set get primaryKey => {id}; diff --git a/lib/data/store/db.g.dart b/lib/data/store/db.g.dart index 6ebc43a187..be8f3eaa56 100644 --- a/lib/data/store/db.g.dart +++ b/lib/data/store/db.g.dart @@ -1841,6 +1841,29 @@ class $ServersTable extends Servers with TableInfo<$ServersTable, ServerRow> { 'REFERENCES ssh_proxy (id) ON DELETE SET NULL', ), ); + static const VerificationMeta _sshTailcatAddressMeta = const VerificationMeta( + 'sshTailcatAddress', + ); + @override + late final GeneratedColumn sshTailcatAddress = + GeneratedColumn( + 'ssh_tailcat_address', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + static const VerificationMeta _sshTailcatDerpMapUrlMeta = + const VerificationMeta('sshTailcatDerpMapUrl'); + @override + late final GeneratedColumn sshTailcatDerpMapUrl = + GeneratedColumn( + 'ssh_tailcat_derp_map_url', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); @override List get $columns => [ updatedAt, @@ -1888,6 +1911,8 @@ class $ServersTable extends Servers with TableInfo<$ServersTable, ServerRow> { sshMoshServerPath, sshMoshPrediction, sshProxyId, + sshTailcatAddress, + sshTailcatDerpMapUrl, ]; @override String get aliasedName => _alias ?? actualTableName; @@ -2244,6 +2269,24 @@ class $ServersTable extends Servers with TableInfo<$ServersTable, ServerRow> { ), ); } + if (data.containsKey('ssh_tailcat_address')) { + context.handle( + _sshTailcatAddressMeta, + sshTailcatAddress.isAcceptableOrUnknown( + data['ssh_tailcat_address']!, + _sshTailcatAddressMeta, + ), + ); + } + if (data.containsKey('ssh_tailcat_derp_map_url')) { + context.handle( + _sshTailcatDerpMapUrlMeta, + sshTailcatDerpMapUrl.isAcceptableOrUnknown( + data['ssh_tailcat_derp_map_url']!, + _sshTailcatDerpMapUrlMeta, + ), + ); + } return context; } @@ -2433,6 +2476,14 @@ class $ServersTable extends Servers with TableInfo<$ServersTable, ServerRow> { DriftSqlType.string, data['${effectivePrefix}ssh_proxy_id'], ), + sshTailcatAddress: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}ssh_tailcat_address'], + ), + sshTailcatDerpMapUrl: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}ssh_tailcat_derp_map_url'], + ), ); } @@ -2558,6 +2609,10 @@ class ServerRow extends DataClass implements Insertable { /// [SshCredential.proxyId]. Last, for the reason [diskCountsNetwork] is. final String? sshProxyId; + + /// [SshCredential.tailcatAddress] and [SshCredential.tailcatDerpMapUrl]. + final String? sshTailcatAddress; + final String? sshTailcatDerpMapUrl; const ServerRow({ required this.updatedAt, required this.rev, @@ -2604,6 +2659,8 @@ class ServerRow extends DataClass implements Insertable { this.sshMoshServerPath, this.sshMoshPrediction, this.sshProxyId, + this.sshTailcatAddress, + this.sshTailcatDerpMapUrl, }); @override Map toColumns(bool nullToAbsent) { @@ -2719,6 +2776,12 @@ class ServerRow extends DataClass implements Insertable { if (!nullToAbsent || sshProxyId != null) { map['ssh_proxy_id'] = Variable(sshProxyId); } + if (!nullToAbsent || sshTailcatAddress != null) { + map['ssh_tailcat_address'] = Variable(sshTailcatAddress); + } + if (!nullToAbsent || sshTailcatDerpMapUrl != null) { + map['ssh_tailcat_derp_map_url'] = Variable(sshTailcatDerpMapUrl); + } return map; } @@ -2833,6 +2896,12 @@ class ServerRow extends DataClass implements Insertable { sshProxyId: sshProxyId == null && nullToAbsent ? const Value.absent() : Value(sshProxyId), + sshTailcatAddress: sshTailcatAddress == null && nullToAbsent + ? const Value.absent() + : Value(sshTailcatAddress), + sshTailcatDerpMapUrl: sshTailcatDerpMapUrl == null && nullToAbsent + ? const Value.absent() + : Value(sshTailcatDerpMapUrl), ); } @@ -2901,6 +2970,12 @@ class ServerRow extends DataClass implements Insertable { json['sshMoshPrediction'], ), sshProxyId: serializer.fromJson(json['sshProxyId']), + sshTailcatAddress: serializer.fromJson( + json['sshTailcatAddress'], + ), + sshTailcatDerpMapUrl: serializer.fromJson( + json['sshTailcatDerpMapUrl'], + ), ); } @override @@ -2954,6 +3029,8 @@ class ServerRow extends DataClass implements Insertable { 'sshMoshServerPath': serializer.toJson(sshMoshServerPath), 'sshMoshPrediction': serializer.toJson(sshMoshPrediction), 'sshProxyId': serializer.toJson(sshProxyId), + 'sshTailcatAddress': serializer.toJson(sshTailcatAddress), + 'sshTailcatDerpMapUrl': serializer.toJson(sshTailcatDerpMapUrl), }; } @@ -3003,6 +3080,8 @@ class ServerRow extends DataClass implements Insertable { Value sshMoshServerPath = const Value.absent(), Value sshMoshPrediction = const Value.absent(), Value sshProxyId = const Value.absent(), + Value sshTailcatAddress = const Value.absent(), + Value sshTailcatDerpMapUrl = const Value.absent(), }) => ServerRow( updatedAt: updatedAt ?? this.updatedAt, rev: rev ?? this.rev, @@ -3072,6 +3151,12 @@ class ServerRow extends DataClass implements Insertable { ? sshMoshPrediction.value : this.sshMoshPrediction, sshProxyId: sshProxyId.present ? sshProxyId.value : this.sshProxyId, + sshTailcatAddress: sshTailcatAddress.present + ? sshTailcatAddress.value + : this.sshTailcatAddress, + sshTailcatDerpMapUrl: sshTailcatDerpMapUrl.present + ? sshTailcatDerpMapUrl.value + : this.sshTailcatDerpMapUrl, ); ServerRow copyWithCompanion(ServersCompanion data) { return ServerRow( @@ -3174,6 +3259,12 @@ class ServerRow extends DataClass implements Insertable { sshProxyId: data.sshProxyId.present ? data.sshProxyId.value : this.sshProxyId, + sshTailcatAddress: data.sshTailcatAddress.present + ? data.sshTailcatAddress.value + : this.sshTailcatAddress, + sshTailcatDerpMapUrl: data.sshTailcatDerpMapUrl.present + ? data.sshTailcatDerpMapUrl.value + : this.sshTailcatDerpMapUrl, ); } @@ -3224,7 +3315,9 @@ class ServerRow extends DataClass implements Insertable { ..write('sshMoshPort: $sshMoshPort, ') ..write('sshMoshServerPath: $sshMoshServerPath, ') ..write('sshMoshPrediction: $sshMoshPrediction, ') - ..write('sshProxyId: $sshProxyId') + ..write('sshProxyId: $sshProxyId, ') + ..write('sshTailcatAddress: $sshTailcatAddress, ') + ..write('sshTailcatDerpMapUrl: $sshTailcatDerpMapUrl') ..write(')')) .toString(); } @@ -3276,6 +3369,8 @@ class ServerRow extends DataClass implements Insertable { sshMoshServerPath, sshMoshPrediction, sshProxyId, + sshTailcatAddress, + sshTailcatDerpMapUrl, ]); @override bool operator ==(Object other) => @@ -3325,7 +3420,9 @@ class ServerRow extends DataClass implements Insertable { other.sshMoshPort == this.sshMoshPort && other.sshMoshServerPath == this.sshMoshServerPath && other.sshMoshPrediction == this.sshMoshPrediction && - other.sshProxyId == this.sshProxyId); + other.sshProxyId == this.sshProxyId && + other.sshTailcatAddress == this.sshTailcatAddress && + other.sshTailcatDerpMapUrl == this.sshTailcatDerpMapUrl); } class ServersCompanion extends UpdateCompanion { @@ -3374,6 +3471,8 @@ class ServersCompanion extends UpdateCompanion { final Value sshMoshServerPath; final Value sshMoshPrediction; final Value sshProxyId; + final Value sshTailcatAddress; + final Value sshTailcatDerpMapUrl; const ServersCompanion({ this.updatedAt = const Value.absent(), this.rev = const Value.absent(), @@ -3420,6 +3519,8 @@ class ServersCompanion extends UpdateCompanion { this.sshMoshServerPath = const Value.absent(), this.sshMoshPrediction = const Value.absent(), this.sshProxyId = const Value.absent(), + this.sshTailcatAddress = const Value.absent(), + this.sshTailcatDerpMapUrl = const Value.absent(), }); ServersCompanion.insert({ this.updatedAt = const Value.absent(), @@ -3467,6 +3568,8 @@ class ServersCompanion extends UpdateCompanion { this.sshMoshServerPath = const Value.absent(), this.sshMoshPrediction = const Value.absent(), this.sshProxyId = const Value.absent(), + this.sshTailcatAddress = const Value.absent(), + this.sshTailcatDerpMapUrl = const Value.absent(), }) : id = Value(id), name = Value(name); static Insertable custom({ @@ -3515,6 +3618,8 @@ class ServersCompanion extends UpdateCompanion { Expression? sshMoshServerPath, Expression? sshMoshPrediction, Expression? sshProxyId, + Expression? sshTailcatAddress, + Expression? sshTailcatDerpMapUrl, }) { return RawValuesInsertable({ if (updatedAt != null) 'updated_at': updatedAt, @@ -3565,6 +3670,9 @@ class ServersCompanion extends UpdateCompanion { if (sshMoshServerPath != null) 'ssh_mosh_server_path': sshMoshServerPath, if (sshMoshPrediction != null) 'ssh_mosh_prediction': sshMoshPrediction, if (sshProxyId != null) 'ssh_proxy_id': sshProxyId, + if (sshTailcatAddress != null) 'ssh_tailcat_address': sshTailcatAddress, + if (sshTailcatDerpMapUrl != null) + 'ssh_tailcat_derp_map_url': sshTailcatDerpMapUrl, }); } @@ -3614,6 +3722,8 @@ class ServersCompanion extends UpdateCompanion { Value? sshMoshServerPath, Value? sshMoshPrediction, Value? sshProxyId, + Value? sshTailcatAddress, + Value? sshTailcatDerpMapUrl, }) { return ServersCompanion( updatedAt: updatedAt ?? this.updatedAt, @@ -3662,6 +3772,8 @@ class ServersCompanion extends UpdateCompanion { sshMoshServerPath: sshMoshServerPath ?? this.sshMoshServerPath, sshMoshPrediction: sshMoshPrediction ?? this.sshMoshPrediction, sshProxyId: sshProxyId ?? this.sshProxyId, + sshTailcatAddress: sshTailcatAddress ?? this.sshTailcatAddress, + sshTailcatDerpMapUrl: sshTailcatDerpMapUrl ?? this.sshTailcatDerpMapUrl, ); } @@ -3809,6 +3921,14 @@ class ServersCompanion extends UpdateCompanion { if (sshProxyId.present) { map['ssh_proxy_id'] = Variable(sshProxyId.value); } + if (sshTailcatAddress.present) { + map['ssh_tailcat_address'] = Variable(sshTailcatAddress.value); + } + if (sshTailcatDerpMapUrl.present) { + map['ssh_tailcat_derp_map_url'] = Variable( + sshTailcatDerpMapUrl.value, + ); + } return map; } @@ -3859,7 +3979,9 @@ class ServersCompanion extends UpdateCompanion { ..write('sshMoshPort: $sshMoshPort, ') ..write('sshMoshServerPath: $sshMoshServerPath, ') ..write('sshMoshPrediction: $sshMoshPrediction, ') - ..write('sshProxyId: $sshProxyId') + ..write('sshProxyId: $sshProxyId, ') + ..write('sshTailcatAddress: $sshTailcatAddress, ') + ..write('sshTailcatDerpMapUrl: $sshTailcatDerpMapUrl') ..write(')')) .toString(); } @@ -13208,6 +13330,8 @@ typedef $$ServersTableCreateCompanionBuilder = ServersCompanion Function({ Value sshMoshServerPath, Value sshMoshPrediction, Value sshProxyId, + Value sshTailcatAddress, + Value sshTailcatDerpMapUrl, }); typedef $$ServersTableUpdateCompanionBuilder = ServersCompanion Function({ Value updatedAt, @@ -13255,6 +13379,8 @@ typedef $$ServersTableUpdateCompanionBuilder = ServersCompanion Function({ Value sshMoshServerPath, Value sshMoshPrediction, Value sshProxyId, + Value sshTailcatAddress, + Value sshTailcatDerpMapUrl, }); final class $$ServersTableReferences @@ -13827,6 +13953,16 @@ class $$ServersTableFilterComposer extends Composer<_$AppDb, $ServersTable> { builder: (column) => ColumnFilters(column), ); + ColumnFilters get sshTailcatAddress => $composableBuilder( + column: $table.sshTailcatAddress, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get sshTailcatDerpMapUrl => $composableBuilder( + column: $table.sshTailcatDerpMapUrl, + builder: (column) => ColumnFilters(column), + ); + $$PrivateKeysTableFilterComposer get sshKeyId { final $$PrivateKeysTableFilterComposer composer = $composerBuilder( composer: this, @@ -14498,6 +14634,16 @@ class $$ServersTableOrderingComposer extends Composer<_$AppDb, $ServersTable> { builder: (column) => ColumnOrderings(column), ); + ColumnOrderings get sshTailcatAddress => $composableBuilder( + column: $table.sshTailcatAddress, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get sshTailcatDerpMapUrl => $composableBuilder( + column: $table.sshTailcatDerpMapUrl, + builder: (column) => ColumnOrderings(column), + ); + $$PrivateKeysTableOrderingComposer get sshKeyId { final $$PrivateKeysTableOrderingComposer composer = $composerBuilder( composer: this, @@ -14735,6 +14881,16 @@ class $$ServersTableAnnotationComposer builder: (column) => column, ); + GeneratedColumn get sshTailcatAddress => $composableBuilder( + column: $table.sshTailcatAddress, + builder: (column) => column, + ); + + GeneratedColumn get sshTailcatDerpMapUrl => $composableBuilder( + column: $table.sshTailcatDerpMapUrl, + builder: (column) => column, + ); + $$PrivateKeysTableAnnotationComposer get sshKeyId { final $$PrivateKeysTableAnnotationComposer composer = $composerBuilder( composer: this, @@ -15278,6 +15434,8 @@ class $$ServersTableTableManager Value sshMoshServerPath = const Value.absent(), Value sshMoshPrediction = const Value.absent(), Value sshProxyId = const Value.absent(), + Value sshTailcatAddress = const Value.absent(), + Value sshTailcatDerpMapUrl = const Value.absent(), }) => ServersCompanion( updatedAt: updatedAt, rev: rev, @@ -15324,6 +15482,8 @@ class $$ServersTableTableManager sshMoshServerPath: sshMoshServerPath, sshMoshPrediction: sshMoshPrediction, sshProxyId: sshProxyId, + sshTailcatAddress: sshTailcatAddress, + sshTailcatDerpMapUrl: sshTailcatDerpMapUrl, ), createCompanionCallback: ({ @@ -15372,6 +15532,8 @@ class $$ServersTableTableManager Value sshMoshServerPath = const Value.absent(), Value sshMoshPrediction = const Value.absent(), Value sshProxyId = const Value.absent(), + Value sshTailcatAddress = const Value.absent(), + Value sshTailcatDerpMapUrl = const Value.absent(), }) => ServersCompanion.insert( updatedAt: updatedAt, rev: rev, @@ -15418,6 +15580,8 @@ class $$ServersTableTableManager sshMoshServerPath: sshMoshServerPath, sshMoshPrediction: sshMoshPrediction, sshProxyId: sshProxyId, + sshTailcatAddress: sshTailcatAddress, + sshTailcatDerpMapUrl: sshTailcatDerpMapUrl, ), withReferenceMapper: (p0) => p0 .map( diff --git a/lib/data/store/migrations/all.dart b/lib/data/store/migrations/all.dart index 9b0d1311db..badb9f979a 100644 --- a/lib/data/store/migrations/all.dart +++ b/lib/data/store/migrations/all.dart @@ -41,6 +41,7 @@ import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m044_server_keys.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; /// Every migration, ordered, in the one place that names them. @@ -104,6 +105,7 @@ const kSchemaMigrations = [ ServerKeysMigration(), SshMoshMigration(), SshProxyMigration(), + SshTailcatMigration(), ]; /// The steps a restore runs on the settings it brought back, in schema order. diff --git a/lib/data/store/migrations/m047_ssh_tailcat.dart b/lib/data/store/migrations/m047_ssh_tailcat.dart new file mode 100644 index 0000000000..9524b01abf --- /dev/null +++ b/lib/data/store/migrations/m047_ssh_tailcat.dart @@ -0,0 +1,32 @@ +import 'package:fl_lib/fl_lib.dart'; +import 'package:server_box/data/store/schema.dart'; + +/// Adds `server.ssh_tailcat_address` and `server.ssh_tailcat_derp_map_url` +/// for per-server native Tailcat SSH transport configuration. +/// +/// Written by hand: Drift creates tables only for a new database. +/// `m047_ssh_tailcat_test.dart` checks the two agree. +class SshTailcatMigration extends SchemaMigration { + const SshTailcatMigration(); + + @override + int get from => 47; + + @override + bool get olderBuildsRead => true; + + @override + Future apply() async { + final db = SqliteDb.instance; + final columns = db + .select('PRAGMA table_info(server);') + .map((row) => row['name'] as String) + .toSet(); + if (!columns.contains('ssh_tailcat_address')) { + db.execute('ALTER TABLE server ADD COLUMN ssh_tailcat_address TEXT;'); + } + if (!columns.contains('ssh_tailcat_derp_map_url')) { + db.execute('ALTER TABLE server ADD COLUMN ssh_tailcat_derp_map_url TEXT;'); + } + } +} diff --git a/lib/data/store/schema.dart b/lib/data/store/schema.dart index 46c653260b..fe077e1ca5 100644 --- a/lib/data/store/schema.dart +++ b/lib/data/store/schema.dart @@ -131,7 +131,8 @@ abstract final class SchemaVersion { /// v45: `server_key`, ordered stored private keys per server /// v46: `server.ssh_mosh_*` (Mosh toggle, UDP port, server binary path, prediction) /// v47: `ssh_proxy` table and `server.ssh_proxy_id` - static const current = 47; + /// v48: `server.ssh_tailcat_address` and `server.ssh_tailcat_derp_map_url` + static const current = 48; /// Internal key names in the `'setting'` SQLite KV store. static const versionKey = '${StoreDefaults.prefixKey}schemaVersion'; diff --git a/lib/data/store/server.dart b/lib/data/store/server.dart index f9613479ce..c629892b63 100644 --- a/lib/data/store/server.dart +++ b/lib/data/store/server.dart @@ -261,6 +261,8 @@ class ServerStore extends EntityStore { alterUrl: row['ssh_alter_url'] as String?, proxyId: (row['ssh_proxy_id'] as String?) ?? pendingProxyId, proxyCommand: row['ssh_proxy_command'] as String?, + tailcatAddress: row['ssh_tailcat_address'] as String?, + tailcatDerpMapUrl: row['ssh_tailcat_derp_map_url'] as String?, identityAgent: row['ssh_identity_agent'] as String?, forwardAgent: (row['ssh_forward_agent'] as int? ?? 0) == 1, controlPath: row['ssh_control_path'] as String?, @@ -405,6 +407,8 @@ class ServerStore extends EntityStore { 'geo_lon', 'disk_counts_network', 'ssh_proxy_id', + 'ssh_tailcat_address', + 'ssh_tailcat_derp_map_url', ]; upsert(columns, [ item.id, @@ -464,6 +468,8 @@ class ServerStore extends EntityStore { (custom?.diskCountsNetwork ?? false) ? 1 : 0, // Populated in [writeLinks] once every referenced proxy exists. null, + ssh?.tailcatAddress, + ssh?.tailcatDerpMapUrl, ]); // Replaced wholesale rather than diffed: the record arrives as one object, diff --git a/lib/generated/l10n/l10n.dart b/lib/generated/l10n/l10n.dart index e500d68d74..1eff4c6c1b 100644 --- a/lib/generated/l10n/l10n.dart +++ b/lib/generated/l10n/l10n.dart @@ -13199,6 +13199,42 @@ abstract class AppLocalizations { /// **'Command'** String get sshRouteCommand; + /// No description provided for @sshRouteTailcat. + /// + /// In en, this message translates to: + /// **'Tailcat'** + String get sshRouteTailcat; + + /// No description provided for @tailcatAddress. + /// + /// In en, this message translates to: + /// **'Tailcat address'** + String get tailcatAddress; + + /// No description provided for @tailcatDerpMapUrl. + /// + /// In en, this message translates to: + /// **'Custom DERP map URL'** + String get tailcatDerpMapUrl; + + /// No description provided for @tailcatAddressInvalid. + /// + /// In en, this message translates to: + /// **'Invalid Tailcat address (expected tc...)'** + String get tailcatAddressInvalid; + + /// No description provided for @tailcatDerpMapUrlInvalid. + /// + /// In en, this message translates to: + /// **'Invalid DERP map URL (expected http:// or https://)'** + String get tailcatDerpMapUrlInvalid; + + /// No description provided for @tailcatConflict. + /// + /// In en, this message translates to: + /// **'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'** + String get tailcatConflict; + /// No description provided for @sshProxyConflict. /// /// In en, this message translates to: diff --git a/lib/generated/l10n/l10n_az.dart b/lib/generated/l10n/l10n_az.dart index e5e5a1afe3..d7e7df8055 100644 --- a/lib/generated/l10n/l10n_az.dart +++ b/lib/generated/l10n/l10n_az.dart @@ -7688,6 +7688,27 @@ class AppLocalizationsAz extends AppLocalizations { @override String get sshRouteCommand => 'Əmr'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Proksi vasitəçi server və ya ProxyCommand ilə birlikdə istifadə edilə bilməz.'; diff --git a/lib/generated/l10n/l10n_de.dart b/lib/generated/l10n/l10n_de.dart index dc2c0b1c16..e3e2afb890 100644 --- a/lib/generated/l10n/l10n_de.dart +++ b/lib/generated/l10n/l10n_de.dart @@ -7792,6 +7792,27 @@ class AppLocalizationsDe extends AppLocalizations { @override String get sshRouteCommand => 'Befehl'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Proxy kann nicht zusammen mit Jump-Server oder ProxyCommand verwendet werden.'; diff --git a/lib/generated/l10n/l10n_en.dart b/lib/generated/l10n/l10n_en.dart index cd1ea5c97b..77fd236674 100644 --- a/lib/generated/l10n/l10n_en.dart +++ b/lib/generated/l10n/l10n_en.dart @@ -7693,6 +7693,27 @@ class AppLocalizationsEn extends AppLocalizations { @override String get sshRouteCommand => 'Command'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Proxy cannot be used together with jump server or ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_es.dart b/lib/generated/l10n/l10n_es.dart index 7e4818762d..7ee6b35f4b 100644 --- a/lib/generated/l10n/l10n_es.dart +++ b/lib/generated/l10n/l10n_es.dart @@ -7796,6 +7796,27 @@ class AppLocalizationsEs extends AppLocalizations { @override String get sshRouteCommand => 'Comando'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'El proxy no se puede usar junto con un servidor de salto ni con ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_fa.dart b/lib/generated/l10n/l10n_fa.dart index 806bca2161..ed051bfe75 100644 --- a/lib/generated/l10n/l10n_fa.dart +++ b/lib/generated/l10n/l10n_fa.dart @@ -7748,6 +7748,27 @@ class AppLocalizationsFa extends AppLocalizations { @override String get sshRouteCommand => 'دستور'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'پراکسی را نمی‌توان هم‌زمان با سرور واسط یا ProxyCommand استفاده کرد.'; diff --git a/lib/generated/l10n/l10n_fr.dart b/lib/generated/l10n/l10n_fr.dart index f7d38aab3d..ed38f06580 100644 --- a/lib/generated/l10n/l10n_fr.dart +++ b/lib/generated/l10n/l10n_fr.dart @@ -7809,6 +7809,27 @@ class AppLocalizationsFr extends AppLocalizations { @override String get sshRouteCommand => 'Commande'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Un proxy ne peut pas être utilisé avec un serveur de rebond ou ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_id.dart b/lib/generated/l10n/l10n_id.dart index e1f3e1c3c6..b9e7ebeadc 100644 --- a/lib/generated/l10n/l10n_id.dart +++ b/lib/generated/l10n/l10n_id.dart @@ -7695,6 +7695,27 @@ class AppLocalizationsId extends AppLocalizations { @override String get sshRouteCommand => 'Perintah'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Proksi tidak dapat digunakan bersamaan dengan server jump atau ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_it.dart b/lib/generated/l10n/l10n_it.dart index 3642ef66e0..afdf5ae5a9 100644 --- a/lib/generated/l10n/l10n_it.dart +++ b/lib/generated/l10n/l10n_it.dart @@ -7770,6 +7770,27 @@ class AppLocalizationsIt extends AppLocalizations { @override String get sshRouteCommand => 'Comando'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Il proxy non può essere usato insieme a un jump server o a ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_ja.dart b/lib/generated/l10n/l10n_ja.dart index 0790730477..c330ba0fc5 100644 --- a/lib/generated/l10n/l10n_ja.dart +++ b/lib/generated/l10n/l10n_ja.dart @@ -7402,6 +7402,27 @@ class AppLocalizationsJa extends AppLocalizations { @override String get sshRouteCommand => 'コマンド'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'プロキシはジャンプサーバーや ProxyCommand と併用できません。'; diff --git a/lib/generated/l10n/l10n_ko.dart b/lib/generated/l10n/l10n_ko.dart index 23439eda04..be33f10a69 100644 --- a/lib/generated/l10n/l10n_ko.dart +++ b/lib/generated/l10n/l10n_ko.dart @@ -7403,6 +7403,27 @@ class AppLocalizationsKo extends AppLocalizations { @override String get sshRouteCommand => '명령'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => '프록시는 점프 서버나 ProxyCommand와 함께 사용할 수 없습니다.'; diff --git a/lib/generated/l10n/l10n_nl.dart b/lib/generated/l10n/l10n_nl.dart index bf11d49b8e..18da1b4f2d 100644 --- a/lib/generated/l10n/l10n_nl.dart +++ b/lib/generated/l10n/l10n_nl.dart @@ -7763,6 +7763,27 @@ class AppLocalizationsNl extends AppLocalizations { @override String get sshRouteCommand => 'Opdracht'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Proxy kan niet samen met een jumpserver of ProxyCommand worden gebruikt.'; diff --git a/lib/generated/l10n/l10n_pt.dart b/lib/generated/l10n/l10n_pt.dart index 9cbbebe9d9..0de573c56b 100644 --- a/lib/generated/l10n/l10n_pt.dart +++ b/lib/generated/l10n/l10n_pt.dart @@ -7765,6 +7765,27 @@ class AppLocalizationsPt extends AppLocalizations { @override String get sshRouteCommand => 'Comando'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'O proxy não pode ser usado junto com servidor de salto ou ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_ru.dart b/lib/generated/l10n/l10n_ru.dart index 8634006ed9..19d6950d40 100644 --- a/lib/generated/l10n/l10n_ru.dart +++ b/lib/generated/l10n/l10n_ru.dart @@ -7747,6 +7747,27 @@ class AppLocalizationsRu extends AppLocalizations { @override String get sshRouteCommand => 'Команда'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Прокси нельзя использовать одновременно с промежуточным сервером или ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_tr.dart b/lib/generated/l10n/l10n_tr.dart index da21c967d5..0913162a0b 100644 --- a/lib/generated/l10n/l10n_tr.dart +++ b/lib/generated/l10n/l10n_tr.dart @@ -7680,6 +7680,27 @@ class AppLocalizationsTr extends AppLocalizations { @override String get sshRouteCommand => 'Komut'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Vekil sunucu, atlama sunucusu veya ProxyCommand ile birlikte kullanılamaz.'; diff --git a/lib/generated/l10n/l10n_uk.dart b/lib/generated/l10n/l10n_uk.dart index 81a209f237..77bdea1034 100644 --- a/lib/generated/l10n/l10n_uk.dart +++ b/lib/generated/l10n/l10n_uk.dart @@ -7745,6 +7745,27 @@ class AppLocalizationsUk extends AppLocalizations { @override String get sshRouteCommand => 'Команда'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => 'Проксі не можна використовувати разом із проміжним сервером або ProxyCommand.'; diff --git a/lib/generated/l10n/l10n_zh.dart b/lib/generated/l10n/l10n_zh.dart index 75bf279eb2..f76525b86c 100644 --- a/lib/generated/l10n/l10n_zh.dart +++ b/lib/generated/l10n/l10n_zh.dart @@ -7285,6 +7285,27 @@ class AppLocalizationsZh extends AppLocalizations { @override String get sshRouteCommand => '命令'; + @override + String get sshRouteTailcat => 'Tailcat'; + + @override + String get tailcatAddress => 'Tailcat address'; + + @override + String get tailcatDerpMapUrl => 'Custom DERP map URL'; + + @override + String get tailcatAddressInvalid => + 'Invalid Tailcat address (expected tc...)'; + + @override + String get tailcatDerpMapUrlInvalid => + 'Invalid DERP map URL (expected http:// or https://)'; + + @override + String get tailcatConflict => + 'Tailcat cannot be used together with jump server, proxy, or ProxyCommand.'; + @override String get sshProxyConflict => '代理不能与跳板服务器或 ProxyCommand 同时使用。'; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 38b7befa9c..ad4b4fd0e0 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -9597,6 +9597,12 @@ "sshRouteDirect": "Direct", "sshRouteJump": "Jump", "sshRouteCommand": "Command", + "sshRouteTailcat": "Tailcat", + "tailcatAddress": "Tailcat address", + "tailcatDerpMapUrl": "Custom DERP map URL", + "tailcatAddressInvalid": "Invalid Tailcat address (expected tc...)", + "tailcatDerpMapUrlInvalid": "Invalid DERP map URL (expected http:// or https://)", + "tailcatConflict": "Tailcat cannot be used together with jump server, proxy, or ProxyCommand.", "sshProxyConflict": "Proxy cannot be used together with jump server or ProxyCommand.", "sshProxySharedTip": "Editing this proxy changes what all associated servers use.", "sshProxyInUse": "{count, plural, =1{1 server uses it. It will switch to direct connection.} other{{count} servers use it. They will switch to direct connection.}}", diff --git a/lib/view/page/server/edit/actions.dart b/lib/view/page/server/edit/actions.dart index 31d5b3bf52..cd696c7d7a 100644 --- a/lib/view/page/server/edit/actions.dart +++ b/lib/view/page/server/edit/actions.dart @@ -338,7 +338,10 @@ extension _Actions on _ServerEditPageState { /// Whether saving leaves an SSH user for a PVE password login: the SSH /// credential is written exactly when there is a host (see `_onSave`). - bool get _hasPveLoginUser => _ipController.text.trim().isNotEmpty; + bool get _hasPveLoginUser => + _ipController.text.trim().isNotEmpty || + (_routeMode.value == _SshRouteMode.tailcat && + _tailcatAddressCtrl.text.trim().isNotEmpty); /// Whether [cfg]'s pin still names the certificate it was confirmed for /// once the server is saved as [next]: the API's host resolves on the far @@ -361,6 +364,7 @@ extension _Actions on _ServerEditPageState { ssh?.resolvedJumpIds.join(','), ssh?.proxyId?.trim(), ssh?.proxyCommand?.trim(), + ssh?.tailcatAddress?.trim(), s.monitorOn?.addr.trim(), ].join('\u0000'); } @@ -497,6 +501,8 @@ extension _Actions on _ServerEditPageState { return l10n.jumpServerAndProxyCommandCannotBeUsedTogether; case SpiValidationError.sshProxyConflict: return l10n.sshProxyConflict; + case SpiValidationError.tailcatConflict: + return l10n.tailcatConflict; case SpiValidationError.noConnectionMethod: return l10n.noConnectionMethod; } @@ -607,13 +613,26 @@ extension _Actions on _ServerEditPageState { Toast.show('${libL10n.invalid}: ${l10n.sshProxy}'); return null; } - if (_ipController.text.isEmpty) { - Toast.show('${libL10n.empty} ${libL10n.host}'); - return null; - } - if (!_hostReg.hasMatch(_ipController.text)) { - Toast.show(l10n.invalidHostFormat); - return null; + if (_routeMode.value == _SshRouteMode.tailcat) { + final tailcatAddr = _tailcatAddressCtrl.text.trim(); + if (!TailcatAddress.isPlausible(tailcatAddr)) { + Toast.show(l10n.tailcatAddressInvalid); + return null; + } + final derpUrl = _tailcatDerpMapCtrl.text.trim(); + if (!TailcatAddress.isValidDerpMapUrl(derpUrl)) { + Toast.show(l10n.tailcatDerpMapUrlInvalid); + return null; + } + } else { + if (_ipController.text.isEmpty) { + Toast.show('${libL10n.empty} ${libL10n.host}'); + return null; + } + if (!_hostReg.hasMatch(_ipController.text)) { + Toast.show(l10n.invalidHostFormat); + return null; + } } // Key auth switched on with no key picked and no password to fall back // on: refused before asking whether no authentication is meant. @@ -714,6 +733,7 @@ extension _Actions on _ServerEditPageState { _SshRouteMode.jump => _jumpServers.value.isNotEmpty, _SshRouteMode.proxy => _proxyId.value != null, _SshRouteMode.command => _proxyCommandCtrl.text.trim().isNotEmpty, + _SshRouteMode.tailcat => _tailcatAddressCtrl.text.trim().isNotEmpty, }; WakeOnLanCfg? _wolToSave() { @@ -783,11 +803,17 @@ extension _Actions on _ServerEditPageState { ); // Same rule as the agent above: kept when switched off, and absent only - // when there is no host to keep. - final ssh = _ipController.text.trim().isEmpty + // when there is no host (or Tailcat peer) to keep. + final tailcatAddrText = _tailcatAddressCtrl.text.trim(); + final isTailcat = + _routeMode.value == _SshRouteMode.tailcat && tailcatAddrText.isNotEmpty; + final hasSshTarget = _ipController.text.trim().isNotEmpty || isTailcat; + final ssh = !hasSshTarget ? null : SshCredential( - ip: _ipController.text, + ip: _ipController.text.trim().isNotEmpty + ? _ipController.text + : SshCredential.tailcatPlaceholderHost, port: int.tryParse(_portController.text) ?? 22, // Defaulted here and only here, whatever the switch says: a // parked configuration is still one somebody will turn back on. @@ -837,6 +863,10 @@ extension _Actions on _ServerEditPageState { proxyCommand: _routeMode.value == _SshRouteMode.command ? proxyCommandText.selfNotEmptyOrNull : null, + tailcatAddress: isTailcat ? tailcatAddrText : null, + tailcatDerpMapUrl: isTailcat + ? _tailcatDerpMapCtrl.text.trim().selfNotEmptyOrNull + : null, fileTransport: _fileTransport.value, allowLegacyAlgorithms: _allowLegacyAlgorithms.value, moshEnabled: _isMoshBlockedByRoute() ? false : _moshEnabled.value, @@ -963,6 +993,8 @@ extension _Actions on _ServerEditPageState { _SshRouteMode.proxy when _proxyId.value != null => 'ssh_proxy', _SshRouteMode.command when _proxyCommandCtrl.text.trim().isNotEmpty => 'proxy', + _SshRouteMode.tailcat when _tailcatAddressCtrl.text.trim().isNotEmpty => + 'tailcat', _ => 'direct', }; @@ -1100,7 +1132,10 @@ extension _Utils on _ServerEditPageState { final ssh = spi.ssh; if (ssh != null) { - _ipController.text = ssh.ip; + _ipController.text = + ssh.hasTailcat && ssh.ip == SshCredential.tailcatPlaceholderHost + ? '' + : ssh.ip; _portController.text = ssh.port.toString(); _usernameController.text = ssh.user; _passwordController.text = ssh.pwd ?? ''; @@ -1131,12 +1166,16 @@ extension _Utils on _ServerEditPageState { _proxyId.value = savedProxyId != null && savedProxyId.isNotEmpty ? savedProxyId : null; _proxyCommandCtrl.text = ssh.proxyCommand ?? ''; + _tailcatAddressCtrl.text = ssh.tailcatAddress ?? ''; + _tailcatDerpMapCtrl.text = ssh.tailcatDerpMapUrl ?? ''; if (_jumpServers.value.isNotEmpty) { _routeMode.value = _SshRouteMode.jump; } else if (_proxyId.value != null) { _routeMode.value = _SshRouteMode.proxy; } else if (_proxyCommandCtrl.text.trim().isNotEmpty) { _routeMode.value = _SshRouteMode.command; + } else if (_tailcatAddressCtrl.text.trim().isNotEmpty) { + _routeMode.value = _SshRouteMode.tailcat; } else { _routeMode.value = _SshRouteMode.direct; } @@ -1214,6 +1253,7 @@ extension _Utils on _ServerEditPageState { _storedSecrets.addAll( [ _passwordController, + _tailcatAddressCtrl, _pvePwdCtrl, _pveTokenSecretCtrl, _monitorPwdCtrl, diff --git a/lib/view/page/server/edit/edit.dart b/lib/view/page/server/edit/edit.dart index ee2f9ba8e8..5f8c9647ad 100644 --- a/lib/view/page/server/edit/edit.dart +++ b/lib/view/page/server/edit/edit.dart @@ -17,6 +17,7 @@ import 'package:server_box/core/ssh/agent.dart'; import 'package:server_box/core/ssh/control_master.dart'; import 'package:server_box/core/ssh/jump_chain.dart'; import 'package:server_box/core/ssh/mosh.dart'; +import 'package:server_box/core/ssh/tailcat_ffi.dart'; import 'package:server_box/core/ssh_discovery/sources.dart'; import 'package:server_box/core/ssh_discovery/ssh_config.dart'; import 'package:server_box/core/utils/app_auth.dart'; @@ -68,7 +69,7 @@ enum ServerEditSection { pve, } -enum _SshRouteMode { direct, jump, proxy, command } +enum _SshRouteMode { direct, jump, proxy, command, tailcat } /// What a new server's form starts with, from outside the app. Nothing /// secret: see `AddServerLink`. @@ -113,6 +114,8 @@ class _ServerEditPageState extends ConsumerState final _ipController = TextEditingController(); final _altUrlController = TextEditingController(); final _proxyCommandCtrl = TextEditingController(); + final _tailcatAddressCtrl = TextEditingController(); + final _tailcatDerpMapCtrl = TextEditingController(); final _controlPathCtrl = TextEditingController(); final _portController = TextEditingController(); final _usernameController = TextEditingController(); @@ -306,6 +309,8 @@ class _ServerEditPageState extends ConsumerState _ipController.dispose(); _altUrlController.dispose(); _proxyCommandCtrl.dispose(); + _tailcatAddressCtrl.dispose(); + _tailcatDerpMapCtrl.dispose(); _controlPathCtrl.dispose(); _portController.dispose(); _usernameController.dispose(); diff --git a/lib/view/page/server/edit/widget.dart b/lib/view/page/server/edit/widget.dart index 1938b7a7ea..f45ff86c20 100644 --- a/lib/view/page/server/edit/widget.dart +++ b/lib/view/page/server/edit/widget.dart @@ -51,7 +51,12 @@ extension _Widgets on _ServerEditPageState { return switch (method) { _Method.monitorHttp => _monitorAddrCtrl.text.selfNotEmptyOrNull ?? '', _Method.ssh => [ - if (_ipController.text.trim().isNotEmpty) + if (_routeMode.value == _SshRouteMode.tailcat && + _tailcatAddressCtrl.text.trim().isNotEmpty) + '${_usernameController.text.selfNotEmptyOrNull ?? 'root'}' + '@${SshCredential.tailcatPlaceholderHost}' + ':${_portController.text.selfNotEmptyOrNull ?? '22'}' + else if (_ipController.text.trim().isNotEmpty) '${_usernameController.text.selfNotEmptyOrNull ?? 'root'}' '@${_ipController.text.trim()}' ':${_portController.text.selfNotEmptyOrNull ?? '22'}', @@ -983,6 +988,7 @@ extension _Widgets on _ServerEditPageState { _jumpServers, _proxyId, _proxyCommandCtrl, + _tailcatAddressCtrl, ]), builder: (_, _) { if (!_useSsh.value) return UIs.placeholder; @@ -991,6 +997,7 @@ extension _Widgets on _ServerEditPageState { _SshRouteMode.jump => _jumpServers.value.isNotEmpty, _SshRouteMode.proxy => _proxyId.value != null, _SshRouteMode.command => _proxyCommandCtrl.text.trim().isNotEmpty, + _SshRouteMode.tailcat => _tailcatAddressCtrl.text.trim().isNotEmpty, }; final enabled = _moshEnabled.value && !blockedByProxy; final prediction = _moshPrediction.value; @@ -1089,7 +1096,12 @@ extension _Widgets on _ServerEditPageState { // A password login is the SSH user's; with no SSH host there is none, and // saving refuses it (`_pveConfigToSave`). return ListenableBuilder( - listenable: Listenable.merge([_pveUseToken, _ipController]), + listenable: Listenable.merge([ + _pveUseToken, + _ipController, + _routeMode, + _tailcatAddressCtrl, + ]), builder: (_, _) => _buildPveAuthModeTile(_pveUseToken.value), ); } @@ -1220,40 +1232,43 @@ extension _Widgets on _ServerEditPageState { /// for. What survives of the exclusivity is the order, which only has to be /// asked when there are two things to order. Widget _buildSshConnFields() { - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - Input( - controller: _ipController, - type: TextInputType.url, - onSubmitted: (_) => _focusScope.requestFocus(_portFocus), - node: _ipFocus, - label: libL10n.host, - icon: BoxIcons.bx_server, - hint: 'example.com', - suggestion: false, - ), - Input( - controller: _portController, - type: TextInputType.number, - node: _portFocus, - onSubmitted: (_) => _focusScope.requestFocus(_usernameFocus), - label: libL10n.port, - icon: Bootstrap.number_123, - hint: '22', - suggestion: false, - ), - Input( - controller: _usernameController, - type: TextInputType.text, - node: _usernameFocus, - label: libL10n.user, - icon: Icons.account_box, - hint: 'root', - suggestion: false, - ), - ], - ); + return _routeMode.listenVal((mode) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (mode != _SshRouteMode.tailcat) + Input( + controller: _ipController, + type: TextInputType.url, + onSubmitted: (_) => _focusScope.requestFocus(_portFocus), + node: _ipFocus, + label: libL10n.host, + icon: BoxIcons.bx_server, + hint: 'example.com', + suggestion: false, + ), + Input( + controller: _portController, + type: TextInputType.number, + node: _portFocus, + onSubmitted: (_) => _focusScope.requestFocus(_usernameFocus), + label: libL10n.port, + icon: Bootstrap.number_123, + hint: '22', + suggestion: false, + ), + Input( + controller: _usernameController, + type: TextInputType.text, + node: _usernameFocus, + label: libL10n.user, + icon: Icons.account_box, + hint: 'root', + suggestion: false, + ), + ], + ); + }); } /// The agent's own fields. @@ -1714,6 +1729,7 @@ extension _Widgets on _ServerEditPageState { _jumpServers, _proxyId, _proxyCommandCtrl, + _tailcatAddressCtrl, ]), builder: (context, _) { final mode = _routeMode.value; @@ -1779,6 +1795,7 @@ extension _Widgets on _ServerEditPageState { _SshRouteMode.jump => _buildJumpChoices(servers), _SshRouteMode.proxy => _buildProxyChoices(context, proxies), _SshRouteMode.command => _buildProxyCommand(), + _SshRouteMode.tailcat => _buildTailcatFields(), }, ], ], @@ -1810,9 +1827,37 @@ extension _Widgets on _ServerEditPageState { : '${proxy.name} · ${proxy.type.label}'; case _SshRouteMode.command: return l10n.sshRouteCommand; + case _SshRouteMode.tailcat: + return l10n.sshRouteTailcat; } } + Widget _buildTailcatFields() { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Input( + controller: _tailcatAddressCtrl, + type: TextInputType.visiblePassword, + obscureText: true, + onReveal: _revealStored(_tailcatAddressCtrl), + label: l10n.tailcatAddress, + icon: MingCute.link_line, + hint: 'tc...', + suggestion: false, + ), + Input( + controller: _tailcatDerpMapCtrl, + type: TextInputType.url, + label: l10n.tailcatDerpMapUrl, + icon: Icons.public, + hint: 'https://tailcat.dev/derpmap.json', + suggestion: false, + ), + ], + ); + } + Widget _buildSshRouteSegments(BuildContext context, _SshRouteMode current) { final scheme = Theme.of(context).colorScheme; final items = [ @@ -1820,6 +1865,7 @@ extension _Widgets on _ServerEditPageState { (_SshRouteMode.jump, l10n.sshRouteJump), (_SshRouteMode.proxy, l10n.sshProxy), (_SshRouteMode.command, l10n.sshRouteCommand), + (_SshRouteMode.tailcat, l10n.sshRouteTailcat), ]; return Container( padding: const EdgeInsets.all(4), diff --git a/lib/view/widget/ssh_discovery/actions.dart b/lib/view/widget/ssh_discovery/actions.dart index 79f949fd23..4d5b384782 100644 --- a/lib/view/widget/ssh_discovery/actions.dart +++ b/lib/view/widget/ssh_discovery/actions.dart @@ -165,7 +165,11 @@ extension _Actions on _SshDiscoveryViewState { for (final MapEntry(:key, value: h) in selected.entries) { final ssh = h.server.ssh; if (h.via.isNotEmpty || ssh == null) continue; - if (ssh.proxyCommand != null || ssh.resolvedJumpIds.isNotEmpty) continue; + if (ssh.proxyCommand != null || + ssh.resolvedJumpIds.isNotEmpty || + ssh.hasTailcat) { + continue; + } direct[key] = ssh; } final known = loadKnownHostFingerprints(); diff --git a/test/helpers/server_ddl.dart b/test/helpers/server_ddl.dart index abcf2aa578..f3d27b99ab 100644 --- a/test/helpers/server_ddl.dart +++ b/test/helpers/server_ddl.dart @@ -97,14 +97,25 @@ const bmcServerColumns = '"bmc_cert_sha256" TEXT NULL, ' '"bmc_cred_id" TEXT NULL REFERENCES bmc_credential (id) ON DELETE SET NULL, '; -/// The column m046 added: last, where `ADD COLUMN` puts it too. +/// The two columns m047 added: last, where `ADD COLUMN` puts them too. +const sshTailcatColumns = + ', "ssh_tailcat_address" TEXT NULL, "ssh_tailcat_derp_map_url" TEXT NULL'; + +/// `server` as it was before v48, asserted to have been found. +String serverDdlBeforeSshTailcat(String fresh) { + expect(fresh, contains(sshTailcatColumns)); + return fresh.replaceFirst(sshTailcatColumns, ''); +} + +/// The column m046 added: last at v47, where `ADD COLUMN` puts it too. const sshProxyIdColumn = ', "ssh_proxy_id" TEXT NULL REFERENCES ssh_proxy (id) ON DELETE SET NULL'; /// `server` as it was before v47, asserted to have been found. String serverDdlBeforeSshProxy(String fresh) { - expect(fresh, contains(sshProxyIdColumn)); - return fresh.replaceFirst(sshProxyIdColumn, ''); + final before = serverDdlBeforeSshTailcat(fresh); + expect(before, contains(sshProxyIdColumn)); + return before.replaceFirst(sshProxyIdColumn, ''); } /// The four columns m045 added: last at v46, where `ADD COLUMN` puts them too. diff --git a/test/migration/m028_local_server_test.dart b/test/migration/m028_local_server_test.dart index a9a9cd4d6a..43c98cf8a1 100644 --- a/test/migration/m028_local_server_test.dart +++ b/test/migration/m028_local_server_test.dart @@ -18,6 +18,7 @@ import 'package:server_box/data/store/migrations/m041_ssh_control_path.dart'; import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; import 'package:sqlite3/sqlite3.dart'; @@ -214,6 +215,7 @@ void main() { await const MonitorFallbackAddrMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); final store = ServerStore(); store.put( diff --git a/test/migration/m030_pve_virt_test.dart b/test/migration/m030_pve_virt_test.dart index 77f707244c..2c2d66c47a 100644 --- a/test/migration/m030_pve_virt_test.dart +++ b/test/migration/m030_pve_virt_test.dart @@ -33,6 +33,7 @@ import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/pve.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/setting.dart'; @@ -150,6 +151,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_xinfo('server'), freshServer); expect(_xinfo('server_pve'), freshPve); diff --git a/test/migration/m035_monitor_cert_sha256_test.dart b/test/migration/m035_monitor_cert_sha256_test.dart index a534f4b288..f5e78a3805 100644 --- a/test/migration/m035_monitor_cert_sha256_test.dart +++ b/test/migration/m035_monitor_cert_sha256_test.dart @@ -27,6 +27,7 @@ import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -107,6 +108,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_xinfo('server'), fresh); }); diff --git a/test/migration/m039_ssh_identity_agent_test.dart b/test/migration/m039_ssh_identity_agent_test.dart index 167e938efb..7d36da99e8 100644 --- a/test/migration/m039_ssh_identity_agent_test.dart +++ b/test/migration/m039_ssh_identity_agent_test.dart @@ -12,6 +12,7 @@ import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -70,6 +71,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_serverColumns(), fresh); }); diff --git a/test/migration/m040_ssh_forward_agent_test.dart b/test/migration/m040_ssh_forward_agent_test.dart index 62f60f7a90..abe4b393b3 100644 --- a/test/migration/m040_ssh_forward_agent_test.dart +++ b/test/migration/m040_ssh_forward_agent_test.dart @@ -11,6 +11,7 @@ import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -68,6 +69,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_serverColumns(), fresh); }); diff --git a/test/migration/m041_ssh_control_path_test.dart b/test/migration/m041_ssh_control_path_test.dart index b9134f1816..a380c7d480 100644 --- a/test/migration/m041_ssh_control_path_test.dart +++ b/test/migration/m041_ssh_control_path_test.dart @@ -10,6 +10,7 @@ import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -66,6 +67,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_serverColumns(), fresh); }); diff --git a/test/migration/m042_monitor_fallback_addr_test.dart b/test/migration/m042_monitor_fallback_addr_test.dart index 176320645d..6957584215 100644 --- a/test/migration/m042_monitor_fallback_addr_test.dart +++ b/test/migration/m042_monitor_fallback_addr_test.dart @@ -9,6 +9,7 @@ import 'package:server_box/data/store/migrations/m042_monitor_fallback_addr.dart import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -64,6 +65,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_serverColumns(), fresh); }); diff --git a/test/migration/m043_bmc_target_test.dart b/test/migration/m043_bmc_target_test.dart index b189ca9698..723cef9038 100644 --- a/test/migration/m043_bmc_target_test.dart +++ b/test/migration/m043_bmc_target_test.dart @@ -7,6 +7,7 @@ import 'package:server_box/data/store/migrations/all.dart'; import 'package:server_box/data/store/migrations/m043_bmc_target.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -63,6 +64,7 @@ void main() { await const BmcTargetMigration().apply(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_xinfo('server'), freshServer); expect(_xinfo('bmc_target'), freshTarget); diff --git a/test/migration/m045_ssh_mosh_test.dart b/test/migration/m045_ssh_mosh_test.dart index 0b8c5fbcc7..74ddda5bfc 100644 --- a/test/migration/m045_ssh_mosh_test.dart +++ b/test/migration/m045_ssh_mosh_test.dart @@ -7,6 +7,7 @@ import 'package:server_box/data/model/server/ssh_credential.dart'; import 'package:server_box/data/store/migrations/all.dart'; import 'package:server_box/data/store/migrations/m045_ssh_mosh.dart'; import 'package:server_box/data/store/migrations/m046_ssh_proxy.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; import 'package:server_box/data/store/schema.dart'; import 'package:server_box/data/store/server.dart'; import 'package:server_box/data/store/tables.dart'; @@ -56,6 +57,7 @@ void main() { await createV45Server(); await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); expect(_serverColumns(), fresh); }); @@ -76,6 +78,7 @@ void main() { await const SshMoshMigration().apply(); await const SshProxyMigration().apply(); + await const SshTailcatMigration().apply(); final ssh = ServerStore().fetchOneRaw('s1')!.ssh!; expect(ssh.moshEnabled, isFalse); diff --git a/test/migration/m047_ssh_tailcat_test.dart b/test/migration/m047_ssh_tailcat_test.dart new file mode 100644 index 0000000000..6c65886db1 --- /dev/null +++ b/test/migration/m047_ssh_tailcat_test.dart @@ -0,0 +1,107 @@ +import 'dart:convert'; + +import 'package:fl_lib/fl_lib.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/data/model/server/server_private_info.dart'; +import 'package:server_box/data/model/server/ssh_credential.dart'; +import 'package:server_box/data/store/migrations/all.dart'; +import 'package:server_box/data/store/migrations/m047_ssh_tailcat.dart'; +import 'package:server_box/data/store/schema.dart'; +import 'package:server_box/data/store/server.dart'; +import 'package:server_box/data/store/tables.dart'; + +Map _serverColumns() => { + for (final row in SqliteDb.instance.select('PRAGMA table_info(server);')) + row['name'] as String: ( + row['type'] as String, + (row['notnull'] as int) == 1, + row['dflt_value'], + ), +}; + +Future _v47() async { + await createTables(SqliteDb.instance); + final db = SqliteDb.instance; + db.execute('ALTER TABLE server DROP COLUMN ssh_tailcat_address;'); + db.execute('ALTER TABLE server DROP COLUMN ssh_tailcat_derp_map_url;'); +} + +void main() { + setUp(() => SqliteDb.openInMemory()); + + tearDown(() async { + await closeTables(); + await SqliteDb.close(); + }); + + test('is registered once, from 47, as olderBuildsRead', () { + expect(const SshTailcatMigration().from, 47); + expect(const SshTailcatMigration().olderBuildsRead, isTrue); + expect(kSchemaMigrations.whereType(), hasLength(1)); + expect(kSchemaMigrations.last.from, SchemaVersion.current - 1); + }); + + test('adds the same columns a fresh database has', () async { + await createTables(SqliteDb.instance); + final fresh = _serverColumns(); + + await closeTables(); + await SqliteDb.close(); + SqliteDb.openInMemory(); + await _v47(); + + await const SshTailcatMigration().apply(); + // Idempotent re-run. + await const SshTailcatMigration().apply(); + + expect(_serverColumns(), fresh); + }); + + test('a server written before v48 defaults Tailcat fields to null', () async { + await _v47(); + SqliteDb.instance.execute( + 'INSERT INTO server (id, name, ssh_ip, ssh_port, ssh_user) ' + "VALUES ('s1', 'legacy', '10.0.0.1', 22, 'root');", + ); + + await const SshTailcatMigration().apply(); + + final ssh = ServerStore().fetchOneRaw('s1')!.ssh!; + expect(ssh.hasTailcat, isFalse); + expect(ssh.tailcatAddress, isNull); + expect(ssh.tailcatDerpMapUrl, isNull); + }); + + test('Tailcat fields survive SQLite and JSON round trips', () async { + await createTables(SqliteDb.instance); + final store = ServerStore(); + const addr = 'tcAQIDBAUGBwgJCgsMDQ4PEA'; + const derp = 'https://derp.example.com/derpmap.json'; + const spi = Spi( + name: 'tailcat-host', + id: 's-tc', + ssh: SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + port: 2222, + user: 'ops', + tailcatAddress: addr, + tailcatDerpMapUrl: derp, + ), + ); + store.put(spi); + + final loaded = store.fetchOneRaw('s-tc')!; + expect(loaded.ssh!.hasTailcat, isTrue); + expect(loaded.ssh!.tailcatAddress, addr); + expect(loaded.ssh!.tailcatDerpMapUrl, derp); + expect(loaded.ssh!.port, 2222); + expect(loaded.ssh, equals(spi.ssh)); + expect(loaded.displayAddr, 'ops@tailcat:2222'); + expect(loaded.displayAddr, isNot(contains(addr))); + + final fromJson = Spi.fromJson( + json.decode(loaded.toJsonString()) as Map, + ); + expect(fromJson.ssh, equals(spi.ssh)); + }); +} diff --git a/test/unit/ssh/tailcat_socket_test.dart b/test/unit/ssh/tailcat_socket_test.dart new file mode 100644 index 0000000000..f8a2c421bd --- /dev/null +++ b/test/unit/ssh/tailcat_socket_test.dart @@ -0,0 +1,475 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/core/ssh/client.dart'; +import 'package:server_box/core/ssh/host_key_probe.dart'; +import 'package:server_box/core/ssh/tailcat_ffi.dart'; +import 'package:server_box/core/ssh/tailcat_socket.dart'; +import 'package:server_box/data/model/app/error.dart'; +import 'package:server_box/data/model/server/server_private_info.dart'; +import 'package:server_box/data/model/server/ssh_credential.dart'; + +void main() { + group('TailcatAddress validation', () { + test('accepts plausible tc-prefixed base64url addresses', () { + expect(TailcatAddress.isPlausible('tcAQIDBAUGBwgJCgsMDQ4PEA'), isTrue); + expect( + TailcatAddress.isPlausible(' tcAQIDBAUGBwgJCgsMDQ4PEA '), + isTrue, + ); + }); + + test('rejects empty, wrong-prefix, too-short, or non-base64url inputs', () { + expect(TailcatAddress.isPlausible(''), isFalse); + expect(TailcatAddress.isPlausible('tcshort'), isFalse); + expect(TailcatAddress.isPlausible('10.0.0.1'), isFalse); + expect(TailcatAddress.isPlausible('tc!!!not-base64-url!!!'), isFalse); + expect(TailcatAddress.isPlausible('tcAQIDBAUGBwgJCgsMDQ4PEA=='), isFalse); + }); + + test('validates optional DERP map URLs', () { + expect(TailcatAddress.isValidDerpMapUrl(''), isTrue); + expect( + TailcatAddress.isValidDerpMapUrl('https://tailcat.dev/derpmap.json'), + isTrue, + ); + expect( + TailcatAddress.isValidDerpMapUrl('http://127.0.0.1:8080/derp.json'), + isTrue, + ); + expect(TailcatAddress.isValidDerpMapUrl('ftp://example.com/a'), isFalse); + expect(TailcatAddress.isValidDerpMapUrl('not a url'), isFalse); + }); + }); + + group('SshCredential & Spi Tailcat rules', () { + const validAddr = 'tcAQIDBAUGBwgJCgsMDQ4PEA'; + + test('Tailcat conflicts with jump, proxy, and ProxyCommand', () { + const withJump = Spi( + id: 's1', + name: 'tc-jump', + ssh: SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + tailcatAddress: validAddr, + jumpIds: ['j1'], + ), + ); + expect(withJump.validate(), SpiValidationError.tailcatConflict); + + const withProxy = Spi( + id: 's2', + name: 'tc-proxy', + ssh: SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + tailcatAddress: validAddr, + proxyId: 'p1', + ), + ); + expect(withProxy.validate(), SpiValidationError.tailcatConflict); + + const withCmd = Spi( + id: 's3', + name: 'tc-cmd', + ssh: SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + tailcatAddress: validAddr, + proxyCommand: 'nc %h %p', + ), + ); + expect(withCmd.validate(), SpiValidationError.tailcatConflict); + + const clean = Spi( + id: 's4', + name: 'tc-ok', + ssh: SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + port: 2222, + user: 'alice', + tailcatAddress: validAddr, + ), + ); + expect(clean.validate(), isNull); + expect(clean.displayAddr, 'alice@tailcat:2222'); + expect(clean.displayAddr, isNot(contains(validAddr))); + expect(clean.ssh!.canUseMosh, isFalse); + }); + + test('changing tailcatAddress or derpMapUrl forces reconnect', () { + const a = SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + tailcatAddress: validAddr, + ); + final b = a.copyWith(tailcatAddress: () => 'tcBBBBBBBBBBBBBBBBBBBBBB'); + final c = a.copyWith( + tailcatDerpMapUrl: () => 'https://relay.example.com/map.json', + ); + expect(a.isSameAs(b), isFalse); + expect(a.isSameAs(c), isFalse); + expect(a == b, isFalse); + expect(a.hashCode == b.hashCode, isFalse); + }); + }); + + group('TailcatSocket error handling & redaction', () { + const fakeSecret = 'tcAQIDBAUGBwgJCgsMDQ4PEA'; + + test('rejects bad format, bad port, bad DERP URL without leaking address', () async { + await expectLater( + TailcatSocket.connect(address: 'not-a-tc-addr', port: 22), + throwsA( + isA() + .having((e) => e.type, 'type', SSHErrType.connect) + .having((e) => e.message, 'message', isNot(contains('not-a-tc-addr'))), + ), + ); + + await expectLater( + TailcatSocket.connect(address: fakeSecret, port: 0), + throwsA( + isA() + .having((e) => e.message, 'message', isNot(contains(fakeSecret))), + ), + ); + + await expectLater( + TailcatSocket.connect( + address: fakeSecret, + port: 22, + derpMapUrl: 'ftp://invalid.example.com', + ), + throwsA( + isA() + .having((e) => e.message, 'message', isNot(contains(fakeSecret))), + ), + ); + }); + + test('surfaces clean error when libtailcat cannot be loaded', () async { + await expectLater( + TailcatSocket.connect( + address: fakeSecret, + port: 22, + libraryPath: '/nonexistent/path/libtailcat_missing.dylib', + ), + throwsA( + isA() + .having((e) => e.type, 'type', SSHErrType.connect) + .having((e) => e.message, 'message', contains('Failed to load libtailcat')) + .having((e) => e.message, 'message', isNot(contains(fakeSecret))), + ), + ); + }); + }); + + // Real end-to-end integration tests against compiled libtailcat + local DERP + // fixture. Activated when SERVERBOX_TAILCAT_LIB and TAILCAT_TEST_REGION are set. + final libPath = Platform.environment[TailcatLibrary.envLibPath]; + final regionJson = Platform.environment['TAILCAT_TEST_REGION']; + final hasLiveFixture = + libPath != null && + libPath.isNotEmpty && + regionJson != null && + regionJson.isNotEmpty; + + group( + 'TailcatSocket live libtailcat integration', + () { + late TailcatLibrary lib; + late Map region; + late HttpServer derpMapServer; + late String derpMapUrl; + + setUp(() async { + lib = TailcatLibrary.open(libraryPath: libPath); + expect(lib.abiVersion(), TailcatLibrary.supportedAbiVersion); + region = json.decode(regionJson!) as Map; + final regionId = '${region['RegionID'] ?? 1}'; + final derpMapBody = json.encode({ + 'Regions': {regionId: region}, + }); + derpMapServer = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + derpMapServer.listen((req) { + req.response + ..statusCode = HttpStatus.ok + ..headers.contentType = ContentType.json + ..write(derpMapBody); + unawaited(req.response.close()); + }); + derpMapUrl = 'http://127.0.0.1:${derpMapServer.port}/derpmap.json'; + }); + + tearDown(() async { + await derpMapServer.close(force: true); + }); + + test('streams bytes bidirectionally and redacts secret address', () async { + final serverHandle = lib.serverNew({'region': region}); + final listenerHandle = await _listenTcpInIsolate( + libPath!, + serverHandle, + 2222, + ); + try { + final info = lib.info(serverHandle); + final address = info['address'] as String; + expect(TailcatAddress.isPlausible(address), isTrue); + + final parsed = lib.parseAddress(address); + expect(parsed['public_key'], isA()); + expect(parsed.containsKey('preshared_key'), isFalse); + + // Accept one connection and echo everything back in a worker isolate. + final serverEchoDone = _echoOneInIsolate(libPath, listenerHandle); + + final socket = await TailcatSocket.connect( + address: address, + port: 2222, + derpMapUrl: derpMapUrl, + timeout: const Duration(seconds: 15), + libraryPath: libPath, + ); + expect(socket.toString(), 'TailcatSocket(port: 2222)'); + expect(socket.toString(), isNot(contains(address))); + + final received = BytesBuilder(); + final doneReading = Completer(); + socket.stream.listen( + received.add, + onDone: () { + if (!doneReading.isCompleted) doneReading.complete(); + }, + onError: (Object e) { + if (!doneReading.isCompleted) doneReading.completeError(e); + }, + ); + + final payload = utf8.encode('SSH-2.0-ServerBoxTailcatTest\r\n'); + socket.sink.add(payload); + await socket.flush(); + await socket.sink.close(); + + await doneReading.future.timeout(const Duration(seconds: 15)); + await serverEchoDone.timeout(const Duration(seconds: 15)); + expect(received.toBytes(), equals(payload)); + + await socket.close(); + await socket.done.timeout(const Duration(seconds: 5)); + } finally { + await _closeHandlesInIsolate(libPath, listenerHandle, serverHandle); + } + }); + + test('probeHostKey dials through TailcatSocket and verifies SSH host key', () async { + // Optional end-to-end check when a local OpenSSH/Go SSH fixture target + // port is provided by the harness via TAILCAT_TEST_SSH_PORT. + final sshPortStr = Platform.environment['TAILCAT_TEST_SSH_PORT']; + if (sshPortStr == null || sshPortStr.isEmpty) return; + final sshPort = int.parse(sshPortStr); + + final serverHandle = lib.serverNew({'region': region}); + final listenerHandle = await _listenTcpInIsolate( + libPath!, + serverHandle, + 2223, + ); + try { + final address = lib.info(serverHandle)['address'] as String; + + // Proxy one accepted Tailcat connection to local 127.0.0.1:sshPort. + final bridgeFuture = _bridgeOneTailcatConnToTcp( + libPath: libPath, + listenerHandle: listenerHandle, + targetPort: sshPort, + ); + + final cred = SshCredential( + ip: SshCredential.tailcatPlaceholderHost, + port: 2223, + user: 'test', + tailcatAddress: address, + tailcatDerpMapUrl: derpMapUrl, + ); + final hostKey = await probeHostKey( + cred, + timeout: const Duration(seconds: 15), + ); + expect(hostKey, isNotNull); + expect(hostKey!.fingerprint, startsWith('SHA256:')); + await bridgeFuture.timeout(const Duration(seconds: 15)); + + // Now run a full genClient() SSH handshake + HostKeyVerifier over Tailcat. + final bridgeFuture2 = _bridgeOneTailcatConnToTcp( + libPath: libPath, + listenerHandle: listenerHandle, + targetPort: sshPort, + ); + final accepted = {}; + final spi = Spi( + id: 'srv-tc-e2e', + name: 'tailcat-e2e', + ssh: cred, + ); + final client = await genClient( + spi, + timeout: const Duration(seconds: 15), + knownHostFingerprints: {}, + hostCertAuthorities: const [], + onHostKeyPrompt: (info) async => true, + onHostKeyAccepted: (key, fp) => accepted[key] = fp, + ); + try { + await client.authenticated.timeout(const Duration(seconds: 15)); + expect(accepted.values, contains(hostKey.fingerprint)); + } finally { + client.close(); + await client.done.timeout( + const Duration(seconds: 5), + onTimeout: () {}, + ); + } + await bridgeFuture2.timeout(const Duration(seconds: 15)); + } finally { + await _closeHandlesInIsolate(libPath, listenerHandle, serverHandle); + } + }); + }, + skip: !hasLiveFixture + ? 'Set SERVERBOX_TAILCAT_LIB and TAILCAT_TEST_REGION to run live libtailcat E2E tests' + : false, + ); +} + +Future _listenTcpInIsolate(String libPath, int serverHandle, int port) { + return Isolate.run(() { + final isoLib = TailcatLibrary.open(libraryPath: libPath); + return isoLib.serverListenTcp(serverHandle, port); + }); +} + +Future _echoOneInIsolate(String libPath, int listenerHandle) { + return Isolate.run(() { + final isoLib = TailcatLibrary.open(libraryPath: libPath); + final tok = isoLib.tokenNew(timeout: const Duration(seconds: 15)); + final buf = isoLib.allocateBuffer(4096); + var conn = 0; + try { + conn = isoLib.listenerAccept(listenerHandle, token: tok); + while (true) { + final r = isoLib.connRead( + connection: conn, + nativeBuffer: buf, + capacity: 4096, + token: tok, + ); + if (r.bytes.isNotEmpty) { + isoLib.connWriteAll(connection: conn, data: r.bytes, token: tok); + } + if (r.status == TailcatStatus.eof) { + isoLib.connCloseWrite(conn, token: tok); + return; + } + if (r.status != TailcatStatus.ok) { + throw StateError('server read status ${r.status}: ${r.error}'); + } + } + } finally { + isoLib.freeBuffer(buf); + if (conn != 0) isoLib.closeHandle(conn); + isoLib.closeHandle(tok); + } + }); +} + +Future _closeHandlesInIsolate( + String libPath, + int listenerHandle, + int serverHandle, +) { + return Isolate.run(() { + final isoLib = TailcatLibrary.open(libraryPath: libPath); + isoLib.closeHandle(listenerHandle); + isoLib.closeHandle(serverHandle); + }); +} + +Future _acceptOneInIsolate(String libPath, int listenerHandle) { + return Isolate.run(() { + final isoLib = TailcatLibrary.open(libraryPath: libPath); + final tok = isoLib.tokenNew(timeout: const Duration(seconds: 15)); + try { + return isoLib.listenerAccept(listenerHandle, token: tok); + } finally { + isoLib.closeHandle(tok); + } + }); +} + +Future _closeOneHandleInIsolate(String libPath, int handle) { + return Isolate.run(() { + final isoLib = TailcatLibrary.open(libraryPath: libPath); + isoLib.closeHandle(handle); + }); +} + +Future _bridgeOneTailcatConnToTcp({ + required String libPath, + required int listenerHandle, + required int targetPort, +}) async { + final connHandle = await _acceptOneInIsolate(libPath, listenerHandle); + final tcp = await Socket.connect(InternetAddress.loopbackIPv4, targetPort); + final readerPort = ReceivePort(); + await Isolate.spawn(_pumpTailcatToPort, (connHandle, libPath, readerPort.sendPort)); + final sub = readerPort.listen((msg) { + if (msg is TransferableTypedData) { + tcp.add(msg.materialize().asUint8List()); + } else { + unawaited(tcp.close()); + } + }); + final tcpDone = Completer(); + tcp.listen( + (data) { + final lib = TailcatLibrary.open(libraryPath: libPath); + try { + lib.connWriteAll(connection: connHandle, data: Uint8List.fromList(data)); + } catch (_) {} + }, + onDone: () { + if (!tcpDone.isCompleted) tcpDone.complete(); + }, + onError: (_) { + if (!tcpDone.isCompleted) tcpDone.complete(); + }, + ); + await tcpDone.future; + await sub.cancel(); + readerPort.close(); + tcp.destroy(); + await _closeOneHandleInIsolate(libPath, connHandle); +} + +void _pumpTailcatToPort((int, String, SendPort) args) { + final (conn, libPath, out) = args; + final lib = TailcatLibrary.open(libraryPath: libPath); + final buf = lib.allocateBuffer(16384); + try { + while (true) { + final r = lib.connRead(connection: conn, nativeBuffer: buf, capacity: 16384); + if (r.bytes.isNotEmpty) { + out.send(TransferableTypedData.fromList([r.bytes])); + } + if (r.status != TailcatStatus.ok) { + out.send(null); + return; + } + } + } finally { + lib.freeBuffer(buf); + } +} diff --git a/test/widget/server_edit_tailcat_test.dart b/test/widget/server_edit_tailcat_test.dart new file mode 100644 index 0000000000..0bf18a5edf --- /dev/null +++ b/test/widget/server_edit_tailcat_test.dart @@ -0,0 +1,199 @@ +import 'package:fl_lib/fl_lib.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:server_box/core/extension/context/locale.dart' as app_locale; +import 'package:server_box/data/model/server/server_private_info.dart'; +import 'package:server_box/data/model/server/ssh_credential.dart'; +import 'package:server_box/data/provider/private_key.dart'; +import 'package:server_box/data/provider/server/all.dart'; +import 'package:server_box/data/store/private_key.dart'; +import 'package:server_box/data/store/pve.dart'; +import 'package:server_box/data/store/secret.dart'; +import 'package:server_box/data/store/server.dart'; +import 'package:server_box/data/store/setting.dart'; +import 'package:server_box/data/store/ssh_proxy.dart'; +import 'package:server_box/data/store/stores.dart'; +import 'package:server_box/generated/l10n/l10n.dart'; +import 'package:server_box/view/page/server/edit/edit.dart'; + +import '../helpers/test_db.dart'; + +void main() { + setUp(() async { + await openTestDb(); + getIt.registerSingleton(SettingStore('setting_test')); + getIt.registerSingleton(ServerStore()); + getIt.registerSingleton(PveStore()); + getIt.registerSingleton(PrivateKeyStore()); + getIt.registerSingleton(SshProxyStore()); + getIt.registerSingleton(SudoPasswordStore()); + await Stores.setting.init(); + FlutterSecureStorage.setMockInitialValues({}); + }); + + tearDown(() async { + await getIt.reset(); + await closeTestDb(); + }); + + Finder verticalScrollable() => find + .byWidgetPredicate( + (w) => w is Scrollable && w.axisDirection == AxisDirection.down, + ) + .first; + + Future openEditor(WidgetTester tester, {Spi? server}) async { + if (server != null) { + Stores.server.put(server); + } + await tester.pumpWidget( + ProviderScope( + overrides: [ + serversProvider.overrideWith( + () => _StoreServers(server == null ? const [] : [server]), + ), + privateKeyProvider.overrideWithValue(const PrivateKeyState()), + ], + child: MaterialApp( + builder: ResponsivePoints.builder, + locale: const Locale('en'), + localizationsDelegates: const [ + ...app_locale.appLocalizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) { + app_locale.l10n = AppLocalizations.of(context)!; + context.setLibL10n(); + return Scaffold( + body: Builder( + builder: (context) => TextButton( + key: const ValueKey('open'), + onPressed: () => ServerEditPage.route.go( + context, + args: server == null ? null : ServerEditArgs(server), + ), + child: const Text('Open editor'), + ), + ), + ); + }, + ), + ), + ), + ); + await tester.tap(find.byKey(const ValueKey('open'))); + await tester.pumpAndSettle(); + } + + testWidgets( + 'creates and saves a Tailcat SSH server without requiring a host IP', + (tester) async { + const addr = 'tcAQIDBAUGBwgJCgsMDQ4PEA'; + const derp = 'https://derp.example.com/derpmap.json'; + + await openEditor(tester); + + // Fill Name, Port, User, and Password (leaving Host empty). + await tester.enterText( + find.widgetWithText(Input, libL10n.name), + 'my-tailcat-box', + ); + await tester.enterText(find.widgetWithText(Input, libL10n.port), '2222'); + await tester.enterText(find.widgetWithText(Input, libL10n.user), 'ops'); + await tester.enterText( + find.widgetWithText(Input, libL10n.pwd), + 'pass123', + ); + + // Expand SSH Advanced and select the Tailcat route. + final sshAdv = find.text(app_locale.l10n.sshAdvanced); + await tester.scrollUntilVisible( + sshAdv, + 300, + scrollable: verticalScrollable(), + ); + await tester.tap(sshAdv); + await tester.pumpAndSettle(); + + final tcSeg = find.text(app_locale.l10n.sshRouteTailcat).first; + await tester.scrollUntilVisible( + tcSeg, + 200, + scrollable: verticalScrollable(), + ); + await tester.tap(tcSeg); + await tester.pumpAndSettle(); + + // Tailcat address input is obscured by default (secret capability token). + final addrInput = find.widgetWithText(Input, app_locale.l10n.tailcatAddress); + expect(addrInput, findsOneWidget); + expect(tester.widget(addrInput).obscureText, isTrue); + + await tester.enterText(addrInput, addr); + await tester.enterText( + find.widgetWithText(Input, app_locale.l10n.tailcatDerpMapUrl), + derp, + ); + await tester.pump(const Duration(milliseconds: 100)); + + // Save without ever filling in a Host/IP. + await tester.tap(find.widgetWithText(FilledButton, libL10n.save)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('open')), findsOneWidget); + + final saved = Stores.server.fetch().single; + expect(saved.name, 'my-tailcat-box'); + expect(saved.ssh, isNotNull); + expect(saved.ssh!.ip, SshCredential.tailcatPlaceholderHost); + expect(saved.ssh!.port, 2222); + expect(saved.ssh!.user, 'ops'); + expect(saved.ssh!.tailcatAddress, addr); + expect(saved.ssh!.tailcatDerpMapUrl, derp); + expect(saved.ssh!.proxyId, isNull); + expect(saved.ssh!.proxyCommand, isNull); + expect(saved.ssh!.resolvedJumpIds, isEmpty); + expect(saved.displayAddr, 'ops@tailcat:2222'); + expect(saved.displayAddr, isNot(contains(addr))); + }, + ); +} + +final class _StoreServers extends ServersNotifier { + _StoreServers(this.initial); + + final List initial; + + @override + ServersState build() => ServersState( + servers: {for (final s in initial) s.id: s}, + serverOrder: [for (final s in initial) s.id], + ); + + @override + Future reload({bool refreshConnections = true}) async { + Stores.server.dropCache(); + final all = Stores.server.fetch(); + state = ServersState( + servers: {for (final s in all) s.id: s}, + serverOrder: [for (final s in all) s.id], + ); + } + + @override + Future addServer(Spi spi) async { + Stores.server.put(spi); + state = state.copyWith( + servers: {...state.servers, spi.id: spi}, + serverOrder: [...state.serverOrder, spi.id], + ); + } + + @override + Future updateServer(Spi old, Spi newSpi) async { + Stores.server.update(old, newSpi); + state = state.copyWith(servers: {...state.servers, newSpi.id: newSpi}); + } +} diff --git a/tools/tailcat-lib/README.md b/tools/tailcat-lib/README.md new file mode 100644 index 0000000000..822396cfe6 --- /dev/null +++ b/tools/tailcat-lib/README.md @@ -0,0 +1,31 @@ +# `libtailcat` native library packaging + +ServerBox's native Tailcat SSH transport (`lib/core/ssh/tailcat_ffi.dart` + `lib/core/ssh/tailcat_socket.dart`) speaks directly to upstream `github.com/tailscale/tailcat`'s C ABI v1 (`cmd/libtailcat`, `tailcat.h`). + +No Go code is forked in this repository and no CocoaPods dependency is introduced. + +## Build from upstream `tailscale/tailcat` + +Pin or clone upstream `github.com/tailscale/tailcat` (`v0.8.0+`, commit `9245129f` or later) and run: + +```sh +# macOS / Linux / Windows (host shared library) +TAILCAT_SRC=/path/to/tailcat sh tools/tailcat-lib/build.sh host build/tailcat + +# Android (arm64-v8a / armeabi-v7a / x86_64) +TAILCAT_SRC=/path/to/tailcat ANDROID_NDK_HOME=/path/to/ndk \ + sh tools/tailcat-lib/build.sh android build/tailcat + +# iOS + macOS XCFramework (requires full Xcode with iOS SDK) +TAILCAT_SRC=/path/to/tailcat sh tools/tailcat-lib/build.sh ios build/tailcat +``` + +## Runtime lookup order + +`TailcatLibrary.open()` searches in this order: + +1. Explicit `libraryPath` argument (tests) or `SERVERBOX_TAILCAT_LIB` environment variable. +2. Process image (`DynamicLibrary.process()`) on iOS/macOS when `CTailcat.xcframework` is statically linked (`-force_load` / `tc_abi_version` retained). +3. Platform shared library (`libtailcat.dylib`, `libtailcat.so`, `libtailcat.dll`, or `CTailcat.framework/CTailcat`). + +If `libtailcat` is not bundled in a build, all existing SSH connection types (Direct, Jump, Proxy, ProxyCommand) continue to work untouched, and attempting a Tailcat connection returns an `SSHErr` stating the library is unavailable. diff --git a/tools/tailcat-lib/build.sh b/tools/tailcat-lib/build.sh new file mode 100755 index 0000000000..191f8dfecb --- /dev/null +++ b/tools/tailcat-lib/build.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env sh +# Build upstream github.com/tailscale/tailcat's C ABI v1 library (cmd/libtailcat) +# for macOS, Linux, Windows, Android, or iOS without modifying Go sources. +# +# Usage: +# TAILCAT_SRC=/path/to/tailcat sh tools/tailcat-lib/build.sh [out-dir] +# +# Targets: +# host Current host platform shared library (default) +# macos macOS shared library (.dylib) for current arch +# linux Linux shared library (.so) for current arch +# windows Windows DLL (.dll) via MinGW-w64 gcc +# android Android shared library (arm64-v8a; set ANDROID_NDK_HOME) +# ios iOS/macOS CTailcat.xcframework via upstream swift/Makefile (Xcode + iOS SDK) +set -eu + +TARGET="${1:-host}" +OUT_DIR="${2:-build/tailcat}" +TAILCAT_SRC="${TAILCAT_SRC:-}" +GO="${GO:-go}" + +if [ -z "$TAILCAT_SRC" ] || [ ! -f "$TAILCAT_SRC/cmd/libtailcat/main.go" ]; then + echo "error: set TAILCAT_SRC to a checkout of github.com/tailscale/tailcat (v0.8.0+)" >&2 + exit 1 +fi + +TAGS="$(cat "$TAILCAT_SRC/build-tags.txt")" +mkdir -p "$OUT_DIR" +OUT_ABS="$(cd "$OUT_DIR" && pwd)" + +if [ "$TARGET" = "host" ]; then + case "$(uname -s)" in + Darwin) TARGET="macos" ;; + Linux) TARGET="linux" ;; + MINGW*|MSYS*|CYGWIN*) TARGET="windows" ;; + *) echo "error: unsupported host OS $(uname -s)" >&2; exit 1 ;; + esac +fi + +cd "$TAILCAT_SRC" +case "$TARGET" in + macos) + CGO_ENABLED=1 "$GO" build -buildmode=c-shared -tags "$TAGS" -ldflags "-s -w" \ + -o "$OUT_ABS/libtailcat.dylib" ./cmd/libtailcat + echo "Built $OUT_ABS/libtailcat.dylib" + ;; + linux) + CGO_ENABLED=1 "$GO" build -buildmode=c-shared -tags "$TAGS" -ldflags "-s -w" \ + -o "$OUT_ABS/libtailcat.so" ./cmd/libtailcat + echo "Built $OUT_ABS/libtailcat.so" + ;; + windows) + CGO_ENABLED=1 "$GO" build -buildmode=c-shared -tags "$TAGS" -ldflags "-s -w" \ + -o "$OUT_ABS/libtailcat.dll" ./cmd/libtailcat + echo "Built $OUT_ABS/libtailcat.dll" + ;; + android) + if [ -z "${ANDROID_NDK_HOME:-}" ]; then + echo "error: ANDROID_NDK_HOME must point to an Android NDK installation" >&2 + exit 1 + fi + ABI="${ANDROID_ABI:-arm64-v8a}" + API="${ANDROID_API:-24}" + HOST_TAG="$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m)" + case "$HOST_TAG" in + darwin-arm64|darwin-x86_64) HOST_TAG="darwin-x86_64" ;; + linux-x86_64) HOST_TAG="linux-x86_64" ;; + esac + TOOLCHAIN="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/$HOST_TAG/bin" + case "$ABI" in + arm64-v8a) + GOARCH=arm64 + CC="$TOOLCHAIN/aarch64-linux-android${API}-clang" + ;; + armeabi-v7a) + GOARCH=arm + CC="$TOOLCHAIN/armv7a-linux-androideabi${API}-clang" + ;; + x86_64) + GOARCH=amd64 + CC="$TOOLCHAIN/x86_64-linux-android${API}-clang" + ;; + *) + echo "error: unsupported ANDROID_ABI $ABI" >&2 + exit 1 + ;; + esac + mkdir -p "$OUT_ABS/jniLibs/$ABI" + CGO_ENABLED=1 GOOS=android GOARCH="$GOARCH" CC="$CC" \ + "$GO" build -buildmode=c-shared -tags "$TAGS" -ldflags "-s -w" \ + -o "$OUT_ABS/jniLibs/$ABI/libtailcat.so" ./cmd/libtailcat + echo "Built $OUT_ABS/jniLibs/$ABI/libtailcat.so" + ;; + ios) + make -C "$TAILCAT_SRC/swift" xcframework + rm -rf "$OUT_ABS/CTailcat.xcframework" + cp -R "$TAILCAT_SRC/swift/CTailcat.xcframework" "$OUT_ABS/CTailcat.xcframework" + echo "Built $OUT_ABS/CTailcat.xcframework" + ;; + *) + echo "error: unknown target '$TARGET' (expected host|macos|linux|windows|android|ios)" >&2 + exit 1 + ;; +esac