From ad6d35d2c6b08e72b3ab5b8e27d2f5b2a9429159 Mon Sep 17 00:00:00 2001 From: NetKit contributors Date: Sun, 1 Nov 2026 18:29:54 +0100 Subject: [PATCH] =?UTF-8?q?NetKit=201.0.1:=20SSH=20profily=20v2,=20po?= =?UTF-8?q?=C5=99ad=C3=AD=20a=20v=C3=BDb=C4=9Br=20kl=C3=AD=C4=8De;=20zdroj?= =?UTF-8?q?ov=C3=BD=20k=C3=B3d=20iOS?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ios.yml | 204 ++ CHANGELOG.md | 8 + androidApp/build.gradle.kts | 2 +- .../cz/netkit/app/test/M1Instrumentation.kt | 10 +- .../netkit/app/test/SshKeyEditorEvidence.kt | 163 + .../netkit/app/test/SshProfilesR1Evidence.kt | 229 ++ .../netkit/app/test/SshProfilesV2Evidence.kt | 155 + .../app/ssh/SshProfileImportController.kt | 2 +- .../cz/netkit/app/ssh/SshProfileImportUi.kt | 47 +- .../kotlin/cz/netkit/app/ssh/SshScreen.kt | 112 +- .../kotlin/cz/netkit/app/ssh/SshViewModel.kt | 63 +- .../cz/netkit/app/ui/about/AboutScreen.kt | 16 +- .../kotlin/cz/netkit/app/update/UpdateCard.kt | 8 +- .../src/main/res/values-en/ssh_design.xml | 1 - .../src/main/res/values-en/ssh_import.xml | 26 +- androidApp/src/main/res/values/ssh_design.xml | 1 - androidApp/src/main/res/values/ssh_import.xml | 26 +- .../app/ssh/SshLegacyExportFixtureTest.kt | 23 + .../cz/netkit/app/ssh/SshProfileExportTest.kt | 44 + .../app/ssh/SshProfileImportControllerTest.kt | 17 + docs/architektura.md | 6 +- docs/bezpecnost.md | 61 + docs/funkce/ssh.md | 64 + docs/ios.md | 333 +- docs/plan.md | 1 + docs/testovani.md | 36 + docs/zavislosti.md | 116 + gradle/verification-metadata.xml | 195 + iosApp/NetKit.xcodeproj/project.pbxproj | 669 ++++ .../xcshareddata/swiftpm/Package.resolved | 68 + .../xcshareddata/xcschemes/NetKit.xcscheme | 13 + iosApp/NetKit/IcmpPing.swift | 105 + iosApp/NetKit/Info.plist | 7 + iosApp/NetKit/KeychainSecrets.swift | 114 + iosApp/NetKit/LanView.swift | 310 ++ iosApp/NetKit/Localizable.xcstrings | 2806 ++++++++++++++ iosApp/NetKit/NetKitApp.swift | 174 + iosApp/NetKit/OpenSourceLicenses.txt | 3261 +++++++++++++++++ iosApp/NetKit/PortScan.swift | 77 + iosApp/NetKit/PrivacyInfo.xcprivacy | 48 + iosApp/NetKit/SpeedView.swift | 501 +++ iosApp/NetKit/SshHostKeyValidator.swift | 105 + iosApp/NetKit/SshKeyboard.swift | 81 + iosApp/NetKit/SshMetadataStore.swift | 132 + iosApp/NetKit/SshTerminalRows.swift | 67 + iosApp/NetKit/SshTransport.swift | 275 ++ iosApp/NetKit/SshView.swift | 543 +++ iosApp/NetKit/SshViewModel.swift | 447 +++ iosApp/NetKit/WifiView.swift | 29 + iosApp/NetKit/WolPersistence.swift | 77 + iosApp/NetKit/WolPlatform.swift | 257 ++ iosApp/NetKit/WolView.swift | 105 + iosApp/NetKit/cs.lproj/InfoPlist.strings | 2 + iosApp/NetKit/en.lproj/InfoPlist.strings | 2 + iosApp/NetKitTests/KeychainSecretsTests.swift | 163 + iosApp/NetKitTests/LanTests.swift | 408 +++ iosApp/NetKitTests/LocalSshServer.swift | 160 + iosApp/NetKitTests/NetKitTests.swift | 26 + iosApp/NetKitTests/SpeedTests.swift | 374 ++ iosApp/NetKitTests/SshIntegrationTests.swift | 321 ++ .../NetKitTests/SshMetadataStoreTests.swift | 603 +++ iosApp/NetKitTests/SshTerminalTests.swift | 47 + iosApp/NetKitUITests/NetKitUITests.swift | 408 +++ shared/build.gradle.kts | 16 + .../kotlin/cz/netkit/shared/lan/LanPolicy.kt | 22 +- .../kotlin/cz/netkit/shared/ssh/SshModels.kt | 2 +- .../netkit/shared/ssh/SshProfileExchange.kt | 51 + .../cz/netkit/shared/ssh/SshProfileImport.kt | 63 +- .../cz/netkit/shared/update/ProjectLinks.kt | 25 +- .../cz/netkit/shared/ssh/SshLegacyFixture.kt | 4 + .../cz/netkit/shared/ssh/SshPolicyTest.kt | 4 +- .../shared/ssh/SshProfileExchangeTest.kt | 135 + .../netkit/shared/ssh/SshProfileImportTest.kt | 2 +- .../netkit/shared/update/ProjectLinksTest.kt | 21 +- .../cz/netkit/shared/ios/IosAboutDomain.kt | 12 + .../cz/netkit/shared/ios/IosNetworkDomain.kt | 46 + .../shared/ios/IosSecretStoreAdapter.kt | 47 + .../cz/netkit/shared/ios/IosSpeedDomain.kt | 18 + .../cz/netkit/shared/ios/IosSshDomain.kt | 172 + .../cz/netkit/shared/ios/IosTerminal.kt | 50 + .../cz/netkit/shared/ios/IosWolBridge.kt | 114 + .../cz/netkit/shared/ios/IosWolCodec.kt | 20 + .../cz/netkit/shared/IosAboutDomainTest.kt | 23 + .../kotlin/cz/netkit/shared/IosBridgeTest.kt | 173 + .../cz/netkit/shared/IosDomainSmokeTest.kt | 20 + .../cz/netkit/shared/IosSshBridgeTest.kt | 294 ++ tools/public_export.manifest | 56 + tools/public_export.reviewed.tsv | 122 +- web/netkit/README.md | 1 + 89 files changed, 16128 insertions(+), 139 deletions(-) create mode 100644 .github/workflows/ios.yml create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt create mode 100644 iosApp/NetKit.xcodeproj/project.pbxproj create mode 100644 iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved create mode 100644 iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme create mode 100644 iosApp/NetKit/IcmpPing.swift create mode 100644 iosApp/NetKit/Info.plist create mode 100644 iosApp/NetKit/KeychainSecrets.swift create mode 100644 iosApp/NetKit/LanView.swift create mode 100644 iosApp/NetKit/Localizable.xcstrings create mode 100644 iosApp/NetKit/NetKitApp.swift create mode 100644 iosApp/NetKit/OpenSourceLicenses.txt create mode 100644 iosApp/NetKit/PortScan.swift create mode 100644 iosApp/NetKit/PrivacyInfo.xcprivacy create mode 100644 iosApp/NetKit/SpeedView.swift create mode 100644 iosApp/NetKit/SshHostKeyValidator.swift create mode 100644 iosApp/NetKit/SshKeyboard.swift create mode 100644 iosApp/NetKit/SshMetadataStore.swift create mode 100644 iosApp/NetKit/SshTerminalRows.swift create mode 100644 iosApp/NetKit/SshTransport.swift create mode 100644 iosApp/NetKit/SshView.swift create mode 100644 iosApp/NetKit/SshViewModel.swift create mode 100644 iosApp/NetKit/WifiView.swift create mode 100644 iosApp/NetKit/WolPersistence.swift create mode 100644 iosApp/NetKit/WolPlatform.swift create mode 100644 iosApp/NetKit/WolView.swift create mode 100644 iosApp/NetKit/cs.lproj/InfoPlist.strings create mode 100644 iosApp/NetKit/en.lproj/InfoPlist.strings create mode 100644 iosApp/NetKitTests/KeychainSecretsTests.swift create mode 100644 iosApp/NetKitTests/LanTests.swift create mode 100644 iosApp/NetKitTests/LocalSshServer.swift create mode 100644 iosApp/NetKitTests/NetKitTests.swift create mode 100644 iosApp/NetKitTests/SpeedTests.swift create mode 100644 iosApp/NetKitTests/SshIntegrationTests.swift create mode 100644 iosApp/NetKitTests/SshMetadataStoreTests.swift create mode 100644 iosApp/NetKitTests/SshTerminalTests.swift create mode 100644 iosApp/NetKitUITests/NetKitUITests.swift create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt create mode 100644 shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt create mode 100644 shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt create mode 100644 shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt create mode 100644 shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt create mode 100644 shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml new file mode 100644 index 0000000..a97a812 --- /dev/null +++ b/.github/workflows/ios.yml @@ -0,0 +1,204 @@ +name: iOS + +# Public repositories run this automatically (standard runners are free there). +# The private development repository runs it only manually (macOS minutes count 10x +# against its quota): Actions > iOS > Run workflow after changes to iosApp/, iosMain +# or shared code that iosMain calls. +on: + push: + branches: [main, "codex/**"] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ios-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + linux: + if: github.event_name == 'workflow_dispatch' || github.event.repository.private == false + name: Linux Android regression + runs-on: ubuntu-24.04 + timeout-minutes: 40 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: temurin + java-version: "21" + - name: Forbidden imports in shared commonMain + run: | + if grep -rE "^import (java|javax|android)\." shared/src/commonMain; then + echo "::error::shared/src/commonMain must not import java, javax or android" + exit 1 + fi + - name: Strict tests, lint and debug build without Apple targets + run: >- + ./gradlew --no-daemon --dependency-verification strict + testDebugUnitTest :shared:allTests lintDebug assembleDebug + + simulator: + if: github.event_name == 'workflow_dispatch' || github.event.repository.private == false + name: ARM iOS simulator + runs-on: macos-15 + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 + with: + distribution: temurin + java-version: "21" + - name: Verify Apple toolchain and select available iPhone deterministically + run: | + test "$(uname -m)" = arm64 + sudo xcode-select -s /Applications/Xcode_16.4.app + test "$(xcodebuild -version)" = $'Xcode 16.4\nBuild version 16F6' + xcodebuild -version + mkdir -p artifacts/ios + xcrun simctl list devices available --json > artifacts/ios/simulators.json + python3 - <<'PY' + import json + import os + import re + + with open("artifacts/ios/simulators.json", encoding="utf-8") as source: + inventory = json.load(source) + candidates = [] + for runtime, devices in inventory["devices"].items(): + match = re.fullmatch(r"com\.apple\.CoreSimulator\.SimRuntime\.iOS-(\d+)-(\d+)(?:-(\d+))?", runtime) + if not match or tuple(int(part or 0) for part in match.groups()) != (18, 5, 0): + continue + version = tuple(int(part or 0) for part in match.groups()) + for device in devices: + if device.get("isAvailable") and device["name"].startswith("iPhone"): + candidates.append((version, device["name"], device["udid"])) + if not candidates: + raise SystemExit("No available iOS 18.5 iPhone simulator in the selected Xcode") + # Pinned iOS 18.5 for Xcode 16.4; stable name/UUID tie-break. + newest = max(item[0] for item in candidates) + _, name, identifier = min(item for item in candidates if item[0] == newest) + print(f"Selected {name}, iOS {newest}, {identifier}") + with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as output: + output.write(f"IOS_SIMULATOR_ID={identifier}\n") + PY + - name: Link static shared framework and run Kotlin Native tests + run: | + ./gradlew --no-daemon --dependency-verification strict -Pnetkit.ios=true \ + :shared:linkDebugFrameworkIosSimulatorArm64 :shared:iosSimulatorArm64Test + framework=shared/build/bin/iosSimulatorArm64/debugFramework/NetKitShared.framework + test -s "$framework/NetKitShared" + test -s "$framework/Headers/NetKitShared.h" + test -s "$framework/Modules/module.modulemap" + cp "$framework/Headers/NetKitShared.h" artifacts/ios/NetKitShared.h + { + ls -lR "$framework" + file "$framework/NetKitShared" + lipo -archs "$framework/NetKitShared" | grep -w arm64 + } | tee artifacts/ios/framework.log + - name: Resolve only committed Swift package versions + run: | + lockfile=iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved + test -s "$lockfile" + xcodebuild -resolvePackageDependencies -project iosApp/NetKit.xcodeproj -scheme NetKit \ + -onlyUsePackageVersionsFromResolvedFile -disableAutomaticPackageResolution \ + 2>&1 | tee artifacts/ios/package-resolution.log + git diff --exit-code -- "$lockfile" + - name: Build simulator app with local ad-hoc signing + run: | + xcodebuild -project iosApp/NetKit.xcodeproj -scheme NetKit \ + -configuration Debug -sdk iphonesimulator \ + -destination "platform=iOS Simulator,id=$IOS_SIMULATOR_ID" \ + -derivedDataPath build/ios-derived \ + -resultBundlePath artifacts/ios/build.xcresult \ + -onlyUsePackageVersionsFromResolvedFile -disableAutomaticPackageResolution \ + CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=YES \ + build 2>&1 | tee artifacts/ios/build.log + - name: Build unsigned Release simulator app and reject UI export hook + run: | + ./gradlew --no-daemon --dependency-verification strict -Pnetkit.ios=true \ + :shared:linkReleaseFrameworkIosSimulatorArm64 + xcodebuild -project iosApp/NetKit.xcodeproj -scheme NetKit \ + -configuration Release -sdk iphonesimulator \ + -destination "platform=iOS Simulator,id=$IOS_SIMULATOR_ID" \ + -derivedDataPath build/ios-release-derived \ + -resultBundlePath artifacts/ios/release-build.xcresult \ + -onlyUsePackageVersionsFromResolvedFile -disableAutomaticPackageResolution \ + CODE_SIGNING_ALLOWED=NO build 2>&1 | tee artifacts/ios/release-build.log + python3 - <<'PY' + from pathlib import Path + + binary = Path("build/ios-release-derived/Build/Products/Release-iphonesimulator/NetKit.app/NetKit") + contents = binary.read_bytes() + if not contents: + raise SystemExit("Release app executable is empty") + if b"netkit-ui-capture-ssh-export" in contents: + raise SystemExit("Release app contains the DEBUG UI export hook") + print("PASS: Release app excludes the DEBUG UI export hook") + PY + git diff --exit-code -- iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved + - name: Swift local transport integration and localized launch tests + run: | + xcodebuild -project iosApp/NetKit.xcodeproj -scheme NetKit \ + -configuration Debug -sdk iphonesimulator \ + -destination "platform=iOS Simulator,id=$IOS_SIMULATOR_ID" \ + -destination-timeout 120 -parallel-testing-enabled NO \ + -derivedDataPath build/ios-derived \ + -resultBundlePath artifacts/ios/tests.xcresult \ + -onlyUsePackageVersionsFromResolvedFile -disableAutomaticPackageResolution \ + CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=YES \ + test 2>&1 | tee artifacts/ios/tests.log + git diff --exit-code -- iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved + - name: Inspect local simulator signatures and entitlements + if: always() + run: | + products=build/ios-derived/Build/Products/Debug-iphonesimulator + mkdir -p artifacts/ios + : > artifacts/ios/defined-symbols.log + { + if [ -d "$products" ]; then + while IFS= read -r -d '' bundle; do + printf '\nBundle: %s\n' "$bundle" + if ! codesign --display --verbose=4 --entitlements - "$bundle" 2>&1; then + printf 'Signature inspection failed for this bundle.\n' + fi + printf '\nBundle: %s\n' "$bundle" >> artifacts/ios/defined-symbols.log + if executable=$(plutil -extract CFBundleExecutable raw -o - "$bundle/Info.plist" 2>> artifacts/ios/defined-symbols.log); then + case "$executable" in + '' | */*) printf 'Invalid bundle executable name; symbol inspection skipped.\n' >> artifacts/ios/defined-symbols.log ;; + *) + if ! nm -gU "$bundle/$executable" >> artifacts/ios/defined-symbols.log 2>&1; then + printf 'Defined-symbol inspection failed for this executable.\n' >> artifacts/ios/defined-symbols.log + fi + ;; + esac + else + printf 'Bundle executable name unavailable; symbol inspection skipped.\n' >> artifacts/ios/defined-symbols.log + fi + done < <(find "$products" -type d \( -name '*.app' -o -name '*.xctest' \) -print0) + else + printf 'No simulator build products available for signature inspection.\n' + printf 'No simulator build products available for symbol inspection.\n' >> artifacts/ios/defined-symbols.log + fi + } | tee artifacts/ios/signatures.log + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: ios-simulator-results + path: | + artifacts/ios/ + shared/build/reports/tests/iosSimulatorArm64Test/ + shared/build/test-results/iosSimulatorArm64Test/ + if-no-files-found: error + retention-days: 7 diff --git a/CHANGELOG.md b/CHANGELOG.md index 5481037..78d23cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.0.1 — SSH profily a iOS ve zdrojích (2026-11-01) + +- Export SSH profilů v novém formátu v2 (typ ověření, startovací příkaz, keepalive, pořadí; bez hesel a klíčů) a import v1, v2 i starších exportů z telefonu. +- Pořadí SSH profilů šipkami, náhled změn před importem a varování u startovacího příkazu. +- Profil s ověřením klíčem bez přiřazeného klíče se nepřipojí a nabídne výběr nebo vytvoření klíče. +- Export funguje i po ukončení aplikace systémem během výběru souboru; varování lze zavřít. +- Zdrojový kód iOS verze (SwiftUI nad sdíleným jádrem) je součástí repozitáře; iOS se zatím nevydává. + ## 1.0.0 — první veřejné vydání (2026-10-31) - První veřejná verze: LAN skener, Wi-Fi analýza, SSH terminál, Wake-on-LAN, rychlostní testy a kontrola aktualizací. diff --git a/androidApp/build.gradle.kts b/androidApp/build.gradle.kts index 542f974..8bd3f2c 100644 --- a/androidApp/build.gradle.kts +++ b/androidApp/build.gradle.kts @@ -7,7 +7,7 @@ plugins { alias(libs.plugins.kotlin.compose) } /** Release version; versionCode = major*10000 + minor*100 + patch (docs/distribuce.md §2). */ -val netkitVersion = "1.0.0" +val netkitVersion = "1.0.1" val netkitVersionCode = netkitVersion.split('.').map(String::toInt).let { (major, minor, patch) -> require(minor in 0..99 && patch in 0..99) { "minor and patch must be 0..99" } major * 10000 + minor * 100 + patch diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt index 917ef09..8ce8a0f 100644 --- a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt @@ -89,22 +89,26 @@ class M1Instrumentation : Instrumentation() { phase=arguments.getString("phase").orEmpty() try { check(runId.matches(Regex("[a-f0-9]{32}"))) { "Invalid runId" } - check(phase in listOf("ui","lan","ssh","wifi","wifi-denied","ssh-ui","ssh-rotated","lan-confirm","ssh-lifecycle","ssh-legacy","lan-discovery","lan-icmp-rtt","wifi-freshness","ssh-reconnect","json-limits")) { "Invalid phase" } + check(phase in listOf("ui","lan","ssh","wifi","wifi-denied","ssh-ui","ssh-rotated","lan-confirm","ssh-lifecycle","ssh-legacy","lan-discovery","lan-icmp-rtt","wifi-freshness","ssh-reconnect","json-limits","ssh-key-editor","ssh-profiles-v2","ssh-profiles-r1","ssh-profiles-p3")) { "Invalid phase" } app=targetContext.applicationContext as M1TestApplication marker("PHASE:$phase:START") runBlocking { withTimeout(if (phase == "ssh-lifecycle") 380_000L else 115_000L) { - when(phase) { "json-limits" -> jsonLimitsPhase(); "ssh-reconnect" -> sshUiPhase(reconnect = true); "wifi-freshness" -> wifiFreshnessPhase(); "ui" -> uiPhase(); "lan" -> lanPhase(); "lan-icmp-rtt" -> lanIcmpRttPhase(); "lan-confirm" -> lanConfirmPhase(); "lan-discovery" -> lanDiscoveryPhase(); "ssh" -> sshPhase(); "ssh-ui" -> sshUiPhase(); "ssh-lifecycle" -> sshUiPhase(lifecycle = true); "ssh-rotated" -> sshRotatedPhase(); "ssh-legacy" -> sshLegacyPhase(); "wifi" -> wifiPhase(false); "wifi-denied" -> wifiPhase(true) } + when(phase) { "ssh-profiles-p3" -> sshProfilesP3Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-profiles-r1" -> sshProfilesR1Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-profiles-v2" -> sshProfilesV2Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-key-editor" -> sshKeyEditorEvidence(this@M1Instrumentation, app, arguments.getString("stage") ?: "2", arguments.getString("order") != "import-first", ::screenshot, ::marker); "json-limits" -> jsonLimitsPhase(); "ssh-reconnect" -> sshUiPhase(reconnect = true); "wifi-freshness" -> wifiFreshnessPhase(); "ui" -> uiPhase(); "lan" -> lanPhase(); "lan-icmp-rtt" -> lanIcmpRttPhase(); "lan-confirm" -> lanConfirmPhase(); "lan-discovery" -> lanDiscoveryPhase(); "ssh" -> sshPhase(); "ssh-ui" -> sshUiPhase(); "ssh-lifecycle" -> sshUiPhase(lifecycle = true); "ssh-rotated" -> sshRotatedPhase(); "ssh-legacy" -> sshLegacyPhase(); "wifi" -> wifiPhase(false); "wifi-denied" -> wifiPhase(true) } } } } catch (failure: Throwable) { // Exception class/step only: provider/library messages may include credentials or key data. + if (phase == "ssh-key-editor" || phase == "ssh-profiles-v2" || phase == "ssh-profiles-r1" || phase == "ssh-profiles-p3") { + marker("SSH_TEST_STACK:" + failure.stackTrace.take(12).joinToString(";")) + try { screenshot("ssh-test-failure.png") } catch (_: Exception) { } + } failureType=failure.javaClass.simpleName outcome="FAIL" } finally { if (::app.isInitialized) { try { app.closeStore() } catch (_: Throwable) { outcome="FAIL" } - try { app.cleanupUiSecrets() } catch (_: Throwable) { outcome="FAIL" } + try { if (phase != "ssh-key-editor" || arguments.getString("stage") != "1" || outcome != "PASS") app.cleanupUiSecrets() } catch (_: Throwable) { outcome="FAIL" } } } // Cleanup is part of the verdict and must finish before Instrumentation can stop the process. diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt new file mode 100644 index 0000000..e6b303e --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt @@ -0,0 +1,163 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.ssh.SshViewModel +import cz.netkit.shared.ssh.SshAuthentication +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import java.io.File + +/** Same test is run against the unmodified 157543b production code and the updated branch. */ +suspend fun sshKeyEditorEvidence( + test: Instrumentation, app: M1TestApplication, stage: String, keyFirst: Boolean, + screenshot: (String) -> Unit, marker: (String) -> Unit, +) { + val activity = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + withTimeout(8000) { model.state.first { it.loaded } } + val ui = SshEvidenceUi(test) + try { + ui.clickTag("tab_ssh") + suspend fun generateKey() { + marker("KEY_EDITOR:OPEN_KEYS") + ui.clickTag("ssh_keys") + marker("KEY_EDITOR:KEY_NAME") + val input = ui.await { it.isEditable } + check(input.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "Fixture Ed25519") + })) + ui.await { it.isEditable && it.text?.toString() == "Fixture Ed25519" } + marker("KEY_EDITOR:GENERATE_CLICK") + ui.clickText(app.getString(R.string.ssh_generate)) + marker("KEY_EDITOR:GENERATE_WAIT") + withTimeout(15000) { model.state.first { !it.busy && it.data.keys.size == 1 } } + marker("KEY_EDITOR:GENERATED:${model.state.value.data.keys.size}") + ui.click(ui.await { it.contentDescription?.toString() == app.getString(R.string.ssh_back) }) + ui.clickTag("ssh_confirm") // Discard the already-used key-name field, not the saved key. + } + suspend fun importProfile() { + val file = File(app.filesDir, "profile-v1.json").apply { + writeText("""{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"Fixture","host":"192.0.2.10","port":22,"username":"tester"}],"skipped":[]}""") + } + marker("KEY_EDITOR:IMPORT_PREVIEW") + withTimeout(8000) { model.state.first { !it.profileImportBlockedByDialog && !it.busy } } + test.runOnMainSync { model.previewProfileImport(Uri.fromFile(file)) } + withTimeout(8000) { model.state.first { it.pendingProfileImport != null } } + if (model.state.value.data.keys.isNotEmpty()) ui.clickText(app.getString(R.string.ssh_import_password), scroll = true) + ui.clickTag("ssh_import_confirm") + withTimeout(8000) { model.state.first { !it.profileImportBusy && it.data.profiles.size == 1 } } + check(model.state.value.data.profiles.single().authentication == SshAuthentication.PASSWORD) + check(model.state.value.data.profiles.single().keyRef == null) + marker("KEY_EDITOR:IMPORTED_PASSWORD_WITHOUT_KEY") + } + if (stage == "all") { + if (keyFirst) { generateKey(); importProfile() } else { importProfile(); generateKey() } + } else if ((stage == "1") == keyFirst) generateKey() else importProfile() + if (stage == "1") { marker("KEY_EDITOR:STAGE1:PASS"); return } + check(model.state.value.data.keys.size == 1) + check(model.state.value.data.profiles.single().keyRef == null) + ui.clickTag("tab_ssh") + // Original UI uses a profile menu; updated UI has a direct management button. + val direct = ui.all().find { it.viewIdResourceName == "ssh_edit_${model.state.value.data.profiles.single().id}" } + if (direct != null) ui.click(direct) else { + ui.clickText("Fixture") + ui.clickText(app.getString(R.string.ssh_edit)) + } + ui.clickText(app.getString(R.string.ssh_key), scroll = true) + delay(500) + screenshot("ssh-key-editor-${if (keyFirst) "key-first" else "import-first"}.png") + val dump = ui.all().joinToString("\n") { node -> + val rect = Rect(); node.getBoundsInScreen(rect) + "${node.className}|${node.text}|${node.contentDescription}|selected=${node.isSelected}|checked=${node.isChecked}|enabled=${node.isEnabled}|visible=${node.isVisibleToUser}|$rect" + } + File(app.filesDir, "m1-evidence/key-editor-tree.txt").writeText(dump) + marker("KEY_EDITOR:BEFORE_SELECTION:keys=${model.state.value.data.keys.size};loaded=${model.state.value.loaded};busy=${model.state.value.busy}") + ui.clickText("Fixture Ed25519", scroll = true) + ui.clickText(app.getString(R.string.ssh_save), scroll = true) + withTimeout(8000) { model.state.first { + !it.busy && it.data.profiles.single().authentication == SshAuthentication.KEY && + it.data.profiles.single().keyRef == it.data.keys.single().id + } } + marker("KEY_EDITOR:SELECT_AND_SAVE:PASS") + } catch (error: Throwable) { + screenshot("ssh-key-editor-failure.png") + marker("KEY_EDITOR:FAILURE_STATE:keys=${model.state.value.data.keys.size};busy=${model.state.value.busy};error=${model.state.value.error}") + throw error + } finally { test.runOnMainSync { activity.finish() } } +} + +internal class SshEvidenceUi(private val test: Instrumentation) { + fun all(): List { + // Same cache discipline as M1Instrumentation.freshRoot: refresh() alone retains stale Compose children on API 34+. + if (android.os.Build.VERSION.SDK_INT >= 34) test.uiAutomation.clearCache() + val root = test.uiAutomation.rootInActiveWindow ?: return emptyList() + root.refresh() + return buildList { + fun visit(n: AccessibilityNodeInfo) { n.refresh(); add(n); for (i in 0 until n.childCount) n.getChild(i)?.let(::visit) } + visit(root) + } + } + suspend fun await(predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo = withTimeout(8000) { + while (true) { all().firstOrNull(predicate)?.let { return@withTimeout it }; delay(100) } + error("unreachable") + } + suspend fun click(node: AccessibilityNodeInfo) { + try { test.uiAutomation.waitForIdle(200, 2000) } catch (_: java.util.concurrent.TimeoutException) { } + val fresh = all().firstOrNull { + if (!node.viewIdResourceName.isNullOrEmpty()) it.viewIdResourceName == node.viewIdResourceName + else if (!node.text.isNullOrEmpty()) it.text == node.text + else it.contentDescription == node.contentDescription && !node.contentDescription.isNullOrEmpty() + } ?: node + val action = generateSequence(fresh) { it.parent }.firstOrNull { it.isClickable && it.isEnabled } + if (action?.performAction(AccessibilityNodeInfo.ACTION_CLICK) == true) { delay(250); return } + val bounds = Rect(); fresh.getBoundsInScreen(bounds) + val now = android.os.SystemClock.uptimeMillis() + for (action in listOf(android.view.MotionEvent.ACTION_DOWN, android.view.MotionEvent.ACTION_UP)) { + val event = android.view.MotionEvent.obtain(now, android.os.SystemClock.uptimeMillis(), action, + bounds.exactCenterX(), bounds.exactCenterY(), 0) + event.source = android.view.InputDevice.SOURCE_TOUCHSCREEN + try { check(test.uiAutomation.injectInputEvent(event, true)) } finally { event.recycle() } + } + delay(250) + } + suspend fun clickTag(tag: String) { + val node = await { it.viewIdResourceName == tag } + if (!node.isSelected) click(node) + } + private fun visibleText(text: String): AccessibilityNodeInfo? { + val nodes = all() + val navigationTop = nodes.firstOrNull { it.viewIdResourceName == "tab_ssh" }?.let { + Rect().apply { it.getBoundsInScreen(this) }.top + } ?: test.targetContext.resources.displayMetrics.heightPixels + return nodes.firstOrNull { node -> + val bounds = Rect(); node.getBoundsInScreen(bounds) + node.text?.toString() == text && node.isVisibleToUser && bounds.width() > 0 && + bounds.height() > 0 && bounds.top >= 0 && bounds.bottom <= navigationTop + } + } + suspend fun findText(text: String, scroll: Boolean = false): AccessibilityNodeInfo { + if (scroll) repeat(10) { + visibleText(text)?.let { return it } + all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + delay(250) + } + val node = withTimeout(8000) { + var found = visibleText(text) + while (found == null) { delay(100); found = visibleText(text) } + found + } + return node + } + suspend fun clickText(text: String, scroll: Boolean = false) = click(findText(text, scroll)) +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt new file mode 100644 index 0000000..f2a3d00 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt @@ -0,0 +1,229 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.content.Intent +import android.net.Uri +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.ssh.* +import cz.netkit.shared.ssh.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import java.io.File + +/** R1 regressions exercise production screens and ViewModel with an isolated real store. */ +suspend fun sshProfilesR1Evidence(test: Instrumentation, app: M1TestApplication, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val profile = SshProfile("fixture", "Fixture", "192.0.2.10", username = "tester") + val key = SshKeyInfo("metadata-only", "Other key", "public-fixture") + val activity = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + val ui = SshEvidenceUi(test) + val store = SshViewModel::class.java.getDeclaredField("store").apply { isAccessible = true }.get(model) as SshStore + suspend fun data(value: SshData) { + withContext(Dispatchers.IO) { store.update { value } } + withTimeout(8000) { model.state.first { it.data == value && it.loaded && !it.busy } } + } + suspend fun prepare(): Boolean { + val completed = CompletableDeferred() + test.runOnMainSync { model.prepareExport { completed.complete(true) } } + withTimeout(8000) { model.state.first { !it.busy } } + return completed.isCompleted + } + try { + withTimeout(8000) { model.state.first { it.loaded } } + ui.clickTag("tab_ssh") + // Invalid exports must never call the callback which opens CreateDocument. + val duplicate = SshData(profiles = listOf(profile, profile.copy(id = "second"))) + data(duplicate) + check(!prepare()) + check(model.state.value.exportFailure == SshProfileExportError.DuplicateNames(listOf("Fixture"))) + ui.findText(app.getString(R.string.ssh_export_duplicates, "Fixture")) + // Also invoke the real menu: it stays in NetKit and displays the specific error. + ui.clickTag("ssh_more"); ui.clickTag("ssh_export") + ui.findText(app.getString(R.string.ssh_export_duplicates, "Fixture")) + check(ui.all().none { it.packageName?.toString() == "com.google.android.documentsui" }) + screenshot("ssh-r1-export-duplicates.png") + data(SshData(profiles = (1..70).map { profile.copy(id = "p$it", name = "p$it", startupCommand = "ž".repeat(4096)) })) + check(!prepare()) + check(model.state.value.exportFailure == SshProfileExportError.TooLarge) + ui.findText(app.getString(R.string.ssh_export_size)) + ui.clickTag("ssh_more"); ui.clickTag("ssh_export") + ui.findText(app.getString(R.string.ssh_export_size)) + check(ui.all().none { it.packageName?.toString() == "com.google.android.documentsui" }) + screenshot("ssh-r1-export-size.png") + data(SshData(profiles = listOf(profile))) + check(prepare()) + data(duplicate) // Changing data while SAF is open must not invalidate the prepared snapshot. + val output = File(app.filesDir, "m1-evidence/ssh-r1-export.json") + test.runOnMainSync { model.export(Uri.fromFile(output)) } + withTimeout(8000) { model.state.first { it.exported && !it.busy } } + check(decodeSshProfileImport(output.readBytes()).profiles.single().alias == "Fixture") + marker("SSH_R1:P2_1_EXPORT_PREFLIGHT_AND_SNAPSHOT:PASS") + + data(SshData(keys = listOf(key))) + val v1 = File(app.filesDir, "r1-v1.json").apply { + writeText("""{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"Imported","host":"192.0.2.10","port":22,"username":"tester"}],"skipped":[]}""") + } + test.runOnMainSync { model.previewProfileImport(Uri.fromFile(v1)) } + withTimeout(8000) { model.state.first { it.pendingProfileImport != null } } + fun auth() = ui.all().firstOrNull { it.viewIdResourceName == "ssh_import_auth_Imported" }?.text?.toString() + withTimeout(8000) { while (auth() != app.getString(R.string.ssh_key)) delay(50) } + ui.clickText(app.getString(R.string.ssh_import_password), scroll = true) + withTimeout(8000) { while (auth() != app.getString(R.string.ssh_password)) delay(50) } + ui.clickText(key.name, scroll = true) + withTimeout(8000) { while (auth() != app.getString(R.string.ssh_key)) delay(50) } + ui.clickTag("ssh_import_confirm") + withTimeout(8000) { model.state.first { !it.profileImportBusy && it.data.profiles.size == 1 } } + check(model.state.value.data.profiles.single().let { it.authentication == SshAuthentication.KEY && it.keyRef == key.id }) + marker("SSH_R1:P2_2_PREVIEW_FOLLOWS_SELECTION:PASS") + + data(SshData(profiles = listOf(profile), keys = listOf(key))) + val keyProfile = profile.copy(authentication = SshAuthentication.KEY) + val v2 = File(app.filesDir, "r1-v2.json").apply { writeBytes(encodeSshProfileExport(SshData(profiles = listOf(keyProfile)))) } + test.runOnMainSync { model.previewProfileImport(Uri.fromFile(v2)) } + withTimeout(8000) { model.state.first { it.pendingProfileImport != null } } + ui.findText(app.getString(R.string.ssh_select_profile_key), scroll = true) + screenshot("ssh-r1-import-key-warning.png") + test.runOnMainSync { model.cancelProfileImport() } + marker("SSH_R1:P3_4_UPDATE_KEY_WARNING:PASS") + + data(SshData(profiles = listOf(keyProfile), keys = listOf(key))) + // Accessible management labels carry the profile identity; monogram is captured for visual verification. + fun hasDescription(node: android.view.accessibility.AccessibilityNodeInfo, description: String): Boolean = + node.contentDescription?.toString() == description || (0 until node.childCount).any { + node.getChild(it)?.let { child -> hasDescription(child, description) } == true + } + // Compose exposes the description below the tagged clickable wrapper in the unmerged tree. + check(hasDescription(ui.await { it.viewIdResourceName == "ssh_edit_fixture" }, app.getString(R.string.ssh_edit_profile, "Fixture"))) + check(hasDescription(ui.await { it.viewIdResourceName == "ssh_delete_fixture" }, app.getString(R.string.ssh_delete_profile_action, "Fixture"))) + screenshot("ssh-r1-profile-actions.png") + marker("SSH_R1:P3_7_NAMED_ACTIONS:PASS") + test.runOnMainSync { model.connect(keyProfile) } + ui.clickTag("ssh_missing_key_edit") + ui.findText(app.getString(R.string.ssh_create_key), scroll = true) + check(model.state.value.data.keys.isNotEmpty()) + ui.clickTag("ssh_editor_create_key") + ui.findText(app.getString(R.string.ssh_generate), scroll = true) + marker("SSH_R1:P3_6_CREATE_WITH_OTHER_KEY:PASS") + + // No network is reached: metadata-only key fails before DNS at encrypted-secret lookup. + val confirmed = profile.copy(authentication = SshAuthentication.KEY, keyRef = key.id, startupCommand = "show version") + data(SshData(profiles = listOf(confirmed), keys = listOf(key))) + test.runOnMainSync { model.connect(confirmed) } + val ended = withTimeout(8000) { model.state.first { it.sessions.any { s -> s.ended } } }.sessions.single() + // This is the exact snapshot held by the reconnect dialog before a concurrent edit. + val dialogProfile = model.reconnectProfile(ended.id)!! + data(SshData(profiles = listOf(confirmed.copy(host = "198.51.100.1", startupCommand = "show status", keyRef = null)), keys = listOf(key))) + test.runOnMainSync { model.reconnect(ended.id, dialogProfile) } + withTimeout(8000) { model.state.first { it.sessions.single().ended && it.sessions.single() !== ended } } + val sessionProfiles = SshViewModel::class.java.getDeclaredField("sessionProfiles").apply { isAccessible = true }.get(model) as Map<*, *> + check(sessionProfiles[ended.id] == dialogProfile) + check(model.state.value.keySelectionRequired == null) + val previousSession = model.state.value.sessions.single() + val connections = SshViewModel::class.java.getDeclaredField("connections").apply { isAccessible = true } + val before = (connections.get(model) as Map<*, *>).toMap() + data(SshData(keys = listOf(key))) + test.runOnMainSync { model.reconnect(ended.id, dialogProfile) } + check(model.state.value.profileUnavailable && model.state.value.keySelectionRequired == null) + check(model.state.value.sessions.single() === previousSession) + check((connections.get(model) as Map<*, *>).toMap() == before) + check(ui.all().none { it.viewIdResourceName == "ssh_missing_key_edit" }) + check(model.state.value.data.profiles.isEmpty()) + marker("SSH_R1:P3_5_CONFIRMED_SNAPSHOT_AND_DELETION:PASS") + test.runOnMainSync { model.closeAllSessions() } + } catch (error: Throwable) { + screenshot("ssh-r1-failure.png") + File(app.filesDir, "m1-evidence/ssh-r1-tree.txt").writeText(ui.all().joinToString("\n") { + "${it.viewIdResourceName}|${it.text}|${it.contentDescription}|enabled=${it.isEnabled}" + }) + throw error + } finally { test.runOnMainSync { activity.finish() } } +} + +/** P3: the SAF result returns without the in-memory snapshot, plus dismissible warnings. */ +suspend fun sshProfilesP3Evidence(test: Instrumentation, app: M1TestApplication, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val profile = SshProfile("fixture", "Fixture", "192.0.2.10", username = "tester") + val activity = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + val ui = SshEvidenceUi(test) + val store = SshViewModel::class.java.getDeclaredField("store").apply { isAccessible = true }.get(model) as SshStore + suspend fun data(value: SshData) { + withContext(Dispatchers.IO) { store.update { value } } + withTimeout(8000) { model.state.first { it.data == value && it.loaded && !it.busy } } + } + suspend fun dismissWarning() { + ui.clickText(app.getString(R.string.ssh_ok), scroll = true) + withTimeout(8000) { model.state.first { it.exportFailure == null && !it.profileUnavailable } } + withTimeout(8000) { while (ui.all().any { it.text?.toString() == app.getString(R.string.ssh_ok) }) delay(50) } + } + try { + withTimeout(8000) { model.state.first { it.loaded } } + ui.clickTag("tab_ssh") + data(SshData(profiles = listOf(profile))) + val ready = CompletableDeferred() + test.runOnMainSync { model.prepareExport { ready.complete(Unit) } } + withTimeout(8000) { ready.await() } + // Simulate the exact lost field after process death; keep the real persisted store and SAF result URI. + SshViewModel::class.java.getDeclaredField("preparedExport").apply { isAccessible = true }.set(model, null) + data(SshData(profiles = listOf(profile.copy(name = "Current")))) + val output = File(app.filesDir, "m1-evidence/ssh-p3-export.json").apply { check(parentFile!!.isDirectory || parentFile!!.mkdirs()); writeBytes(byteArrayOf()) } + test.runOnMainSync { model.export(Uri.fromFile(output)) } + withTimeout(8000) { model.state.first { it.exported && !it.busy } } + check(!model.state.value.error && model.state.value.exportFailure == null) + check(decodeSshProfileImport(output.readBytes()).profiles.single().alias == "Current") + marker("SSH_P3:LOST_SNAPSHOT_EXPORT:PASS") + + val invalid = listOf( + SshData(profiles = listOf(profile, profile.copy(id = "second"))) to app.getString(R.string.ssh_export_duplicates, "Fixture"), + SshData(profiles = (1..70).map { profile.copy(id = "p$it", name = "p$it", startupCommand = "ž".repeat(4096)) }) to app.getString(R.string.ssh_export_size)) + for ((value, message) in invalid) { + data(value) + val before = output.readBytes() + test.runOnMainSync { model.export(Uri.fromFile(output)) } + withTimeout(8000) { model.state.first { !it.busy && it.exportFailure != null } } + check(!model.state.value.error && !model.state.value.exported) + check(before.contentEquals(output.readBytes())) // No truncation on failed fallback validation. + ui.findText(message) + dismissWarning() + } + marker("SSH_P3:FALLBACK_ERRORS_AND_DISMISS:PASS") + // Deleted/missing reconnect also has an actionable, dismissible error. + data(SshData()) + test.runOnMainSync { model.reconnect("missing-session", profile) } + ui.findText(app.getString(R.string.ssh_profile_unavailable)) + dismissWarning() + marker("SSH_P3:PROFILE_WARNING_DISMISS:PASS") + + for (auth in listOf(SshAuthentication.KEY, SshAuthentication.INTERACTIVE)) { + data(SshData(profiles = listOf(profile.copy(secretRef = "fixture-reference")))) + val input = File(app.filesDir, "p3-auth.json").apply { + writeBytes(encodeSshProfileExport(SshData(profiles = listOf(profile.copy(authentication = auth))))) + } + test.runOnMainSync { model.previewProfileImport(Uri.fromFile(input)) } + withTimeout(8000) { model.state.first { it.pendingProfileImport != null } } + ui.findText(app.getString(R.string.ssh_import_secret_moves), scroll = true) + screenshot("ssh-p3-password-warning-${auth.name}.png") + test.runOnMainSync { model.cancelProfileImport() } + withTimeout(8000) { model.state.first { it.pendingProfileImport == null && !it.profileImportBusy } } + } + // Check both translations independent of the emulator language. + for ((language, expected) in listOf("cs" to "Uložené heslo se odpojí a smaže.", + "en" to "The saved password will be detached and deleted.")) { + val config = android.content.res.Configuration(app.resources.configuration).apply { setLocale(java.util.Locale.forLanguageTag(language)) } + check(app.createConfigurationContext(config).getString(R.string.ssh_import_secret_moves) == expected) + } + marker("SSH_P3:AUTH_NEUTRAL_WARNING_CS_EN:PASS") + } catch (error: Throwable) { + screenshot("ssh-p3-failure.png") + throw error + } finally { test.runOnMainSync { activity.finish() } } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt new file mode 100644 index 0000000..2892074 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt @@ -0,0 +1,155 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.content.Intent +import android.net.Uri +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.ssh.* +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.shared.ssh.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import java.io.File + +@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) +suspend fun sshProfilesV2Evidence(test: Instrumentation, app: M1TestApplication, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val profiles = listOf( + SshProfile("a", "Alpha", "192.0.2.1", username = "tester", authentication = SshAuthentication.KEY), + SshProfile("b", "Beta", "192.0.2.2", username = "tester", authentication = SshAuthentication.KEY, keyRef = "absent"), + SshProfile("c", "Gamma", "192.0.2.3", username = "tester", authentication = SshAuthentication.KEY, keyRef = "metadata-only")) + val seedScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { SshStore(app, seedScope).update { SshData(profiles = profiles, keys = listOf(SshKeyInfo("metadata-only", "Other key", "public-fixture"))) } } + finally { seedScope.coroutineContext[Job]!!.cancelAndJoin() } + val ui = SshEvidenceUi(test) + fun start() = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + var activity = start() + lateinit var model: SshViewModel + fun bind() { test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } } + bind() + try { + withTimeout(8000) { model.state.first { it.loaded } } + ui.clickTag("tab_ssh") + check(!ui.await { it.viewIdResourceName == "ssh_up_a" }.isEnabled) + check(!ui.await { it.viewIdResourceName == "ssh_down_c" }.isEnabled) + ui.clickTag("ssh_down_a") + withTimeout(8000) { model.state.first { !it.busy && it.data.profiles.map { p -> p.id } == listOf("b", "a", "c") } } + screenshot("ssh-profile-order.png") + test.runOnMainSync { activity.finish() } + withTimeout(8000) { while (!activity.isDestroyed) delay(50) } + activity = start(); bind() + withTimeout(8000) { model.state.first { it.loaded } } + check(model.state.value.data.profiles.map { it.id } == listOf("b", "a", "c")) + ui.clickTag("tab_ssh") + val output = File(app.filesDir, "m1-evidence/ssh-v2-export.json") + val ready = CompletableDeferred() + test.runOnMainSync { model.prepareExport { ready.complete(Unit) } } + withTimeout(8000) { ready.await() } + test.runOnMainSync { model.export(Uri.fromFile(output)) } + withTimeout(8000) { model.state.first { it.exported && !it.busy } } + check(decodeSshProfileImport(output.readBytes()).profiles.map { it.alias } == listOf("Beta", "Alpha", "Gamma")) + marker("SSH_V2:MOVE_RESTART_EXPORT:PASS") + val saved = CompletableDeferred() + test.runOnMainSync { model.saveProfile(profiles[0], "", false) { saved.complete(Unit) } } + withTimeout(8000) { saved.await() } + check(model.state.value.data.profiles.map { it.id } == listOf("b", "a", "c")) + marker("SSH_V2:EDIT_PRESERVES_ORDER:PASS") + // Both missing and dangling references must stop before any transport is added. + val connectionField = SshViewModel::class.java.getDeclaredField("connections").apply { isAccessible = true } + fun transportCount() = (connectionField.get(model) as Map<*, *>).size + for (profile in profiles.take(2)) { + test.runOnMainSync { model.connect(profile) } + withTimeout(8000) { model.state.first { it.keySelectionRequired?.id == profile.id } } + check(model.state.value.sessions.isEmpty() && transportCount() == 0) + marker("SSH_V2:GUARD_${profile.id}:NO_TRANSPORT") + ui.findText(app.getString(R.string.ssh_select_profile_key), scroll = true) + test.runOnMainSync { model.dismissKeySelection() } + } + test.runOnMainSync { model.connect(profiles[0]) } + ui.clickTag("ssh_missing_key_edit") + ui.findText(app.getString(R.string.ssh_select_profile_key), scroll = true) + marker("SSH_V2:EDITOR_WARNING_VISIBLE") + // There is a different key on the device: the editor still explicitly requests selection. + ui.findText(app.getString(R.string.ssh_save), scroll = true) + check(!ui.await { it.viewIdResourceName == "ssh_profile_save" }.isEnabled) + screenshot("ssh-missing-key-editor.png") + marker("SSH_V2:CONNECT_AND_EDITOR_MISSING_KEY:PASS") + // End a metadata-only KEY attempt before DNS (no encrypted key exists), then remove its key. + test.runOnMainSync { model.dismissKeySelection(); model.connect(profiles[2]) } + val ended = withTimeout(8000) { model.state.first { it.sessions.any { s -> s.ended } } }.sessions.single() + val keyRemoved = CompletableDeferred() + test.runOnMainSync { model.saveProfile(profiles[2].copy(keyRef = null), "", false) { keyRemoved.complete(Unit) } } + withTimeout(8000) { keyRemoved.await() } + test.runOnMainSync { model.deleteKey("metadata-only") } + withTimeout(8000) { model.state.first { !it.busy && it.data.keys.isEmpty() } } + val field = SshViewModel::class.java.getDeclaredField("connections").apply { isAccessible = true } + val before = (field.get(model) as Map<*, *>).toMap() + test.runOnMainSync { model.reconnect(ended.id, model.reconnectProfile(ended.id)!!) } + withTimeout(8000) { model.state.first { it.keySelectionRequired?.id == "c" } } + check((field.get(model) as Map<*, *>).toMap() == before) + check(model.state.value.sessions.single() === ended) + marker("SSH_V2:RECONNECT_NO_TRANSPORT:PASS") + ui.clickTag("ssh_missing_key_edit") + ui.findText(app.getString(R.string.ssh_create_key), scroll = true) + ui.clickTag("ssh_editor_create_key") + ui.await { it.text?.toString() == app.getString(R.string.ssh_generate) } + ui.click(ui.await { it.contentDescription?.toString() == app.getString(R.string.ssh_back) }) + ui.findText(app.getString(R.string.ssh_select_profile_key), scroll = true) + marker("SSH_V2:EMPTY_EDITOR_CREATE_KEY_AND_RETURN:PASS") + test.runOnMainSync { model.dismissKeySelection(); model.closeAllSessions() } + // Reset only the Activity UI; persisted profiles remain and all sessions are closed. + test.runOnMainSync { activity.finish() } + withTimeout(8000) { while (!activity.isDestroyed) delay(50) } + activity = start(); bind() + withTimeout(8000) { model.state.first { it.loaded } } + ui.clickTag("tab_ssh") + val changed = profiles[0].copy(host = "198.51.100.1", port = 2222, username = "other", + authentication = SshAuthentication.INTERACTIVE, startupCommand = "show version", keepaliveSeconds = 60) + val input = File(app.filesDir, "incoming-v2.json").apply { writeBytes(encodeSshProfileExport(SshData(profiles = listOf(changed)))) } + test.runOnMainSync { model.previewProfileImport(Uri.fromFile(input)) } + withTimeout(8000) { model.state.first { it.pendingProfileImport != null } } + for ((label, old, new) in listOf( + Triple(R.string.ssh_host, "192.0.2.1", "198.51.100.1"), Triple(R.string.ssh_port, "22", "2222"), + Triple(R.string.ssh_username, "tester", "other"), + Triple(R.string.ssh_authentication_label, app.getString(R.string.ssh_key), app.getString(R.string.ssh_interactive)), + Triple(R.string.ssh_startup_command, app.getString(R.string.ssh_none), "show version"), + Triple(R.string.ssh_keepalive, "30", "60"))) { + val text = app.getString(R.string.ssh_import_change, app.getString(label), old, new) + ui.await { it.text?.toString()?.contains(text) == true } + } + ui.await { it.text?.toString()?.contains(app.getString(R.string.ssh_import_startup_warning)) == true } + screenshot("ssh-import-v2-changes.png") + marker("SSH_V2:ALL_CHANGED_FIELDS_AND_STARTUP_WARNING:PASS") + test.runOnMainSync { model.cancelProfileImport() } + // The same production row rendered with busy=true must disable both arrows. + test.runOnMainSync { + activity.setContent { NetKitTheme { + Column(Modifier.safeDrawingPadding().padding(Spacing.normal).semantics { testTagsAsResourceId = true }) { + ProfileRow(profiles[1], false, false, true, false, false, {}, {}, {}, { error("Busy move") }) + } + } } + } + check(!ui.await { it.viewIdResourceName == "ssh_up_b" }.isEnabled) + check(!ui.await { it.viewIdResourceName == "ssh_down_b" }.isEnabled) + marker("SSH_V2:BUSY_ARROWS_DISABLED:PASS") + } catch (error: Throwable) { + screenshot("ssh-v2-failure.png") + File(app.filesDir, "m1-evidence/ssh-v2-failure-tree.txt").writeText(ui.all().joinToString("\n") { + "${it.viewIdResourceName}|${it.text}|enabled=${it.isEnabled}|visible=${it.isVisibleToUser}" + }) + throw error + } finally { test.runOnMainSync { activity.finish() } } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt index f2629ba..e3e001c 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt @@ -22,7 +22,7 @@ data class SshProfileImportState( internal fun SshUiState.blocksProfileImport(): Boolean = !loaded || storeFailed || busy || profileImportBlockedByDialog || - hostChallenge != null || authChallenge != null || sessions.any { !it.ended } + hostChallenge != null || authChallenge != null || keySelectionRequired != null || sessions.any { !it.ended } /** Main-thread API shared by the ViewModel and JVM tests; store mutations use its operations mutex. */ internal class SshProfileImportController( diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt index a385b8a..c7989a1 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt @@ -31,6 +31,8 @@ import cz.netkit.app.ui.Tag import cz.netkit.app.ui.Tone import cz.netkit.app.ui.theme.NetKitTheme import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.ssh.needsKeySelection +import cz.netkit.shared.ssh.SshAuthentication import cz.netkit.shared.ssh.SshImportEntry import cz.netkit.shared.ssh.SshImportSkipReason import cz.netkit.shared.ssh.SshProfileImportFailure @@ -41,8 +43,8 @@ private fun endpoint(username: String, host: String, port: Int): String { } /** - * Preview of a `netkit-ssh-profiles` file from the PC. Nothing is stored before confirmation; - * the chosen phone key applies only to new profiles, existing ones keep their authentication. + * Preview of v1, v2 or legacy export. Nothing is stored before confirmation. + * A chosen key applies only to new v1 profiles or new v2/legacy KEY profiles. */ @Composable internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiState, onConfirm: (String?) -> Unit, onCancel: () -> Unit) { @@ -61,7 +63,7 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS } if (plan.newProfiles.isNotEmpty()) { item { Eyebrow(stringResource(R.string.ssh_import_new), Modifier.padding(top = Spacing.small)) } - items(plan.newProfiles, key = { "n" + it.incoming.alias }) { ImportRow(it, Tone.OK) } + items(plan.newProfiles, key = { "n" + it.incoming.alias }) { ImportRow(it, Tone.OK, keyRef, state) } item { Column(verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { Eyebrow(stringResource(R.string.ssh_import_key), Modifier.padding(top = Spacing.small)) @@ -74,7 +76,7 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS } if (plan.updatedProfiles.isNotEmpty()) { item { Eyebrow(stringResource(R.string.ssh_import_updated), Modifier.padding(top = Spacing.small)) } - items(plan.updatedProfiles, key = { "u" + it.incoming.alias }) { ImportRow(it, Tone.WARN) } + items(plan.updatedProfiles, key = { "u" + it.incoming.alias }) { ImportRow(it, Tone.WARN, keyRef, state) } } if (plan.skipped.isNotEmpty()) { item { Eyebrow(stringResource(R.string.ssh_import_skipped), Modifier.padding(top = Spacing.small)) } @@ -98,20 +100,49 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS } @Composable -private fun ImportRow(entry: SshImportEntry, tone: Tone) { +private fun ImportRow(entry: SshImportEntry, tone: Tone, keyRef: String?, state: SshUiState) { val colors = NetKitTheme.colors Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { Text(entry.incoming.alias, Modifier.weight(1f), style = NetKitType.panelTitle, color = colors.text, maxLines = 1, overflow = TextOverflow.Ellipsis) entry.incoming.group?.let { Tag(it, tone) } } - val after = endpoint(entry.after.username, entry.after.host, entry.after.port) - val text = entry.before?.let { endpoint(it.username, it.host, it.port) + " → " + after } ?: after - Text(text, style = NetKitType.addressFor(NetKitType.label), color = colors.muted) + val after = entry.after + val before = entry.before + if (before == null) { + Text(endpoint(after.username, after.host, after.port), style = NetKitType.addressFor(NetKitType.label), color = colors.muted) + val authentication = entry.incoming.authentication ?: if (keyRef != null) SshAuthentication.KEY else SshAuthentication.PASSWORD + Text(stringResource(authenticationResource(authentication)), Modifier.testTag("ssh_import_auth_${entry.incoming.alias}"), style = NetKitType.label, color = colors.muted) + if (after.startupCommand.isNotEmpty()) StatusBanner(stringResource(R.string.ssh_import_startup_warning) + "\n" + after.startupCommand, StatusKind.WARNING) + } else { + ImportChange(R.string.ssh_host, before.host, after.host) + ImportChange(R.string.ssh_port, before.port.toString(), after.port.toString()) + ImportChange(R.string.ssh_username, before.username, after.username) + ImportChange(R.string.ssh_authentication_label, stringResource(authenticationResource(before.authentication)), stringResource(authenticationResource(after.authentication))) + ImportChange(R.string.ssh_startup_command, before.startupCommand, after.startupCommand, sensitive = true) + ImportChange(R.string.ssh_keepalive, before.keepaliveSeconds.toString(), after.keepaliveSeconds.toString()) + if (after.needsKeySelection(state.data)) StatusBanner(stringResource(R.string.ssh_select_profile_key), StatusKind.WARNING) + } if (entry.detachedSecretRef != null) StatusBanner(stringResource(R.string.ssh_import_secret_moves), StatusKind.WARNING) } } +@Composable +private fun ImportChange(@StringRes label: Int, before: String, after: String, sensitive: Boolean = false) { + if (before == after) return + val text = stringResource(R.string.ssh_import_change, stringResource(label), + before.ifEmpty { stringResource(R.string.ssh_none) }, after.ifEmpty { stringResource(R.string.ssh_none) }) + if (sensitive) StatusBanner(text + "\n" + stringResource(R.string.ssh_import_startup_warning), StatusKind.WARNING) + else Text(text, style = NetKitType.label, color = NetKitTheme.colors.muted) +} + +@StringRes +private fun authenticationResource(value: SshAuthentication) = when (value) { + SshAuthentication.PASSWORD -> R.string.ssh_password + SshAuthentication.KEY -> R.string.ssh_key + SshAuthentication.INTERACTIVE -> R.string.ssh_interactive +} + @StringRes private fun skipReasonResource(reason: SshImportSkipReason) = when (reason) { SshImportSkipReason.PROXY_JUMP -> R.string.ssh_skip_proxy_jump diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt index 2649bf8..4442ab4 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt @@ -41,6 +41,7 @@ import android.view.WindowManager import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector @@ -115,13 +116,14 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos if (android.os.Build.VERSION.SDK_INT >= 33) activity?.setRecentsScreenshotEnabled(true) } } - val export = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> uri?.let(viewModel::export) } + val export = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> if (uri == null) viewModel.cancelExport() else viewModel.export(uri) } val importProfiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(viewModel::previewProfileImport) } val terminalStateHolder = rememberSaveableStateHolder() + val profileFormStateHolder = rememberSaveableStateHolder() val active = state.sessions.find { it.id == state.selectedSession } val inList = editor == null && !keys && !hostKeys // The import transaction must not race a profile/key edit or a connection confirmation. - val dialogOpen = editor != null || keys || hostKeys || connecting != null || deleting != null + val dialogOpen = editor != null || keys || hostKeys || connecting != null || reconnecting != null || state.keySelectionRequired != null || deleting != null LaunchedEffect(dialogOpen) { viewModel.setProfileImportBlockedByDialog(dialogOpen) } // Device detail "Otevřít SSH": open the new-profile form with the host filled in, once. LaunchedEffect(prefillHost, state.loaded) { @@ -150,7 +152,7 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos onClick = { actionsMenu = false; hostKeys = true }, modifier = Modifier.testTag("ssh_host_keys")) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_export)) }, enabled = state.loaded && !state.busy, leadingIcon = { Icon(NetKitIcons.Download, null, Modifier.size(20.dp)) }, - onClick = { actionsMenu = false; export.launch("netkit-ssh.json") }, modifier = Modifier.testTag("ssh_export")) + onClick = { actionsMenu = false; viewModel.prepareExport { export.launch("netkit-ssh-profiles.json") } }, modifier = Modifier.testTag("ssh_export")) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_import_profiles)) }, enabled = state.loaded && !state.busy && !state.profileImportBusy, leadingIcon = { Icon(NetKitIcons.Download, null, Modifier.size(20.dp)) }, @@ -167,6 +169,14 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos if (state.busy) NetKitProgress() if (state.error) BannerWithAction(stringResource(sshFailureResource(state.failure)), StatusKind.ERROR, stringResource(R.string.ssh_ok), viewModel::clearError) + state.exportFailure?.let { failure -> + BannerWithAction(when (failure) { + is SshProfileExportError.DuplicateNames -> stringResource(R.string.ssh_export_duplicates, failure.names.joinToString(", ")) + SshProfileExportError.TooLarge -> stringResource(R.string.ssh_export_size) + }, StatusKind.WARNING, stringResource(R.string.ssh_ok), viewModel::clearError) + } + if (state.profileUnavailable) BannerWithAction(stringResource(R.string.ssh_profile_unavailable), StatusKind.WARNING, + stringResource(R.string.ssh_ok), viewModel::clearError) if (state.exported) StatusBanner(stringResource(R.string.ssh_exported)) if (state.profileImportBusy) NetKitProgress() state.profileImportFailure?.let { failure -> @@ -174,8 +184,11 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos stringResource(R.string.ssh_ok), viewModel::cancelProfileImport) } when { - editor != null -> ProfileForm(editor!!, state, viewModel, onClose = { editorJson = null }) keys -> KeyManager(state, viewModel, onClose = { keys = false }) + editor != null -> profileFormStateHolder.SaveableStateProvider(editor.id) { + ProfileForm(editor, state, viewModel, onClose = { editorJson = null; profileFormStateHolder.removeState(editor.id) }, + onCreateKey = { keys = true }) + } hostKeys -> HostKeys(state, viewModel, onClose = { hostKeys = false }) else -> { if (state.sessions.isNotEmpty()) Row(verticalAlignment = Alignment.CenterVertically) { @@ -229,10 +242,10 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos key(profile.id) { ProfileRow(profile, live = state.sessions.any { it.connected && !it.ended && viewModel.reconnectProfile(it.id)?.id == profile.id }, - canConnect = canConnect, busy = state.busy, first = index == 0, last = index == profiles.lastIndex, + canConnect = canConnect, busy = state.busy || state.profileImportBusy || state.pendingProfileImport != null, first = index == 0, last = index == profiles.lastIndex, onConnect = { connecting = profile }, onEdit = { editorJson = Json.encodeToString(profile) }, - onDelete = { deleting = profile }) + onDelete = { deleting = profile }, onMove = { viewModel.moveProfile(profile.id, it) }) } } } @@ -271,6 +284,16 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos } } } + state.keySelectionRequired?.let { profile -> + val currentProfile = state.data.profiles.find { it.id == profile.id } + NetKitAlert(onDismiss = viewModel::dismissKeySelection, + text = { Text(stringResource(if (currentProfile == null) R.string.ssh_profile_unavailable else R.string.ssh_select_profile_key), Modifier.testTag("ssh_missing_key"), style = NetKitType.body) }, + confirm = { if (currentProfile != null) PrimaryButton(stringResource(R.string.ssh_edit), small = true, modifier = Modifier.testTag("ssh_missing_key_edit"), onClick = { + editorJson = Json.encodeToString(currentProfile) + viewModel.dismissKeySelection() + }) }, + dismiss = { NeutralButton(stringResource(R.string.ssh_cancel), small = true, onClick = viewModel::dismissKeySelection) }) + } if (recovering) ConfirmDialog(stringResource(R.string.ssh_recover_confirm), onCancel = { recovering = false }) { viewModel.recoverStore(); recovering = false } @@ -287,7 +310,7 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos reconnecting?.let { (id, profile) -> ConfirmDialog( stringResource(R.string.ssh_connect_confirm, profile.endpoint, profile.startupCommand.ifBlank { stringResource(R.string.ssh_none) }), onCancel = { reconnecting = null }, warning = localWarning(profile), - ) { viewModel.reconnect(id); reconnecting = null } } + ) { viewModel.reconnect(id, profile); reconnecting = null } } state.hostChallenge?.let { challenge -> HostDialog(challenge, viewModel) } state.authChallenge?.let { challenge -> key(challenge) { AuthenticationDialog(challenge, viewModel) } } } @@ -486,41 +509,49 @@ private fun profileAddress(profile: SshProfile): String { } /** - * Profile row: 44 dp monogram tile | name and `user@host :port` | tonal "Připojit". Tapping the - * tile or the texts opens edit/delete; the connect button keeps the `ssh_connect_` tag. + * Profile row with the WoL management layout (edit/delete/up/down). + * Connect retains its stable test tag. */ @Composable -private fun ProfileRow(profile: SshProfile, live: Boolean, canConnect: Boolean, busy: Boolean, first: Boolean, last: Boolean, - onConnect: () -> Unit, onEdit: () -> Unit, onDelete: () -> Unit) { +internal fun ProfileRow(profile: SshProfile, live: Boolean, canConnect: Boolean, busy: Boolean, first: Boolean, last: Boolean, + onConnect: () -> Unit, onEdit: () -> Unit, onDelete: () -> Unit, onMove: (Int) -> Unit) { val colors = NetKitTheme.colors val divider = colors.divider - var menu by remember { mutableStateOf(false) } - Row(Modifier.fillMaxWidth() + Column(Modifier.fillMaxWidth() .then(if (first) Modifier else Modifier.drawBehind { drawLine(divider, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) }) - .padding(top = if (first) 0.dp else Spacing.medium, bottom = if (last) 0.dp else Spacing.medium), - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { - Box(Modifier.weight(1f)) { - Row(Modifier.fillMaxWidth().clip(NetKitShape.nested) - .clickable(onClickLabel = stringResource(R.string.ssh_profile_actions, profile.name), role = Role.Button) { menu = true }, - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { - Box(Modifier.size(44.dp).clip(NetKitShape.nested).background(colors.surface2), contentAlignment = Alignment.Center) { - Text(profileMonogram(profile.name), style = NetKitType.panelTitle.copy(fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.02).em), - color = colors.accent, maxLines = 1, softWrap = false) - } - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text(profile.name, style = NetKitType.panelTitle, color = colors.text, maxLines = 2, overflow = TextOverflow.Ellipsis) - Text(profileAddress(profile), style = NetKitType.addressFor(NetKitType.label), color = colors.muted) - if (live) Tag(stringResource(R.string.ssh_chip_live), Tone.OK, dot = true, modifier = Modifier.padding(top = Spacing.tiny)) - } + .padding(top = if (first) 0.dp else Spacing.medium, bottom = if (last) 0.dp else Spacing.medium)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Box(Modifier.size(44.dp).clip(NetKitShape.nested).background(colors.surface2), contentAlignment = Alignment.Center) { + Text(profileMonogram(profile.name), style = NetKitType.panelTitle.copy(fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.02).em), + color = colors.accent, maxLines = 1, softWrap = false) + } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(profile.name, style = NetKitType.panelTitle, color = colors.text, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(profileAddress(profile), style = NetKitType.addressFor(NetKitType.label), color = colors.muted) + if (live) Tag(stringResource(R.string.ssh_chip_live), Tone.OK, dot = true) + } + TonalButton(stringResource(R.string.ssh_connect), onClick = onConnect, enabled = canConnect, small = true, + modifier = Modifier.testTag("ssh_connect_${profile.id}")) + } + HorizontalDivider(Modifier.padding(top = Spacing.small), thickness = 1.dp, color = colors.divider) + val editLabel = stringResource(R.string.ssh_edit_profile, profile.name) + val deleteLabel = stringResource(R.string.ssh_delete_profile_action, profile.name) + Row(verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = onEdit, enabled = !busy, shape = NetKitShape.buttonSmall, + modifier = Modifier.testTag("ssh_edit_${profile.id}").semantics { contentDescription = editLabel }) { Text(stringResource(R.string.ssh_edit)) } + TextButton(onClick = onDelete, enabled = !busy, shape = NetKitShape.buttonSmall, + colors = ButtonDefaults.textButtonColors(contentColor = colors.err), + modifier = Modifier.testTag("ssh_delete_${profile.id}").semantics { contentDescription = deleteLabel }) { Text(stringResource(R.string.ssh_delete)) } + Spacer(Modifier.weight(1f)) + IconButton(onClick = { onMove(-1) }, enabled = !busy && !first, modifier = Modifier.testTag("ssh_up_${profile.id}")) { + Icon(NetKitIcons.ChevronRight, stringResource(R.string.ssh_move_up, profile.name), Modifier.size(20.dp).rotate(-90f), + tint = if (!busy && !first) colors.muted else colors.dim) } - NetKitMenu(expanded = menu, onDismiss = { menu = false }) { - DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_edit)) }, enabled = !busy, onClick = { menu = false; onEdit() }) - DropdownMenuItem(text = { Text(stringResource(R.string.ssh_delete), style = NetKitType.body, color = colors.err) }, - enabled = !busy, onClick = { menu = false; onDelete() }) + IconButton(onClick = { onMove(1) }, enabled = !busy && !last, modifier = Modifier.testTag("ssh_down_${profile.id}")) { + Icon(NetKitIcons.ChevronRight, stringResource(R.string.ssh_move_down, profile.name), Modifier.size(20.dp).rotate(90f), + tint = if (!busy && !last) colors.muted else colors.dim) } } - TonalButton(stringResource(R.string.ssh_connect), onClick = onConnect, enabled = canConnect, small = true, - modifier = Modifier.testTag("ssh_connect_${profile.id}")) } } @@ -558,7 +589,7 @@ private fun Hint(text: String) { } @Composable -private fun ProfileForm(original: SshProfile, state: SshUiState, viewModel: SshViewModel, onClose: () -> Unit) { +private fun ProfileForm(original: SshProfile, state: SshUiState, viewModel: SshViewModel, onClose: () -> Unit, onCreateKey: () -> Unit) { var name by rememberSaveable(original.id) { mutableStateOf(original.name) }; var host by rememberSaveable(original.id) { mutableStateOf(original.host) } var port by rememberSaveable(original.id) { mutableStateOf(original.port.toString()) }; var user by rememberSaveable(original.id) { mutableStateOf(original.username) } var auth by rememberSaveable(original.id) { mutableStateOf(original.authentication) }; var keyRef by rememberSaveable(original.id) { mutableStateOf(original.keyRef) } @@ -588,14 +619,21 @@ private fun ProfileForm(original: SshProfile, state: SshUiState, viewModel: SshV Hint(stringResource(R.string.ssh_password_hint)) } if (auth == SshAuthentication.KEY) { - if (state.data.keys.isEmpty()) Hint(stringResource(R.string.ssh_add_key_first)) + if (draft.needsKeySelection(state.data)) Box(Modifier.testTag("ssh_editor_missing_key")) { + StatusBanner(stringResource(R.string.ssh_select_profile_key), StatusKind.WARNING) + } + if (state.data.keys.isEmpty()) { + Hint(stringResource(R.string.ssh_add_key_first)) + } + if (draft.needsKeySelection(state.data)) NeutralButton(stringResource(R.string.ssh_create_key), enabled = !state.busy, + modifier = Modifier.testTag("ssh_editor_create_key"), onClick = onCreateKey) Column { state.data.keys.forEach { key -> ChoiceRow(keyRef == key.id, key.name, onClick = { keyRef = key.id }) } } } SshField(command, { command = it.take(4096) }, R.string.ssh_startup_command, mono = true) SshField(keepalive, { keepalive = it.take(3) }, R.string.ssh_keepalive, number = true) Hint(stringResource(R.string.ssh_profile_validation)) FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { - PrimaryButton(stringResource(R.string.ssh_save), enabled = draft.valid() && !state.busy && (auth != SshAuthentication.KEY || state.data.keys.any { it.id == keyRef }), + PrimaryButton(stringResource(R.string.ssh_save), modifier = Modifier.testTag("ssh_profile_save"), enabled = draft.valid() && !state.busy && (auth != SshAuthentication.KEY || state.data.keys.any { it.id == keyRef }), onClick = { viewModel.saveProfile(draft, password, savePassword) { password = ""; onClose() } }) NeutralButton(stringResource(R.string.ssh_back), enabled = !state.busy, onClick = { discard = true }) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt index b655026..c092cce 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt @@ -30,6 +30,8 @@ class SshSessionState(val id: String, val name: String, val terminal: TerminalSn data class HostChallenge(val requestId: String, val sessionId: String, val offered: TrustedHostKey, val previous: TrustedHostKey?, val lastRejected: TrustedHostKey? = null) data class AuthChallenge(val requestId: String, val sessionId: String, val trustedIdentity: String, val name: String, val instruction: String, val prompts: List, val echo: List) data class SshUiState(val data: SshData = SshData(), val loaded: Boolean = false, val storeFailed: Boolean = false, + val keySelectionRequired: SshProfile? = null, + val exportFailure: SshProfileExportError? = null, val profileUnavailable: Boolean = false, val busy: Boolean = false, val error: Boolean = false, val failure: SshFailure? = null, val storeRecoverable: Boolean = false, val archivePath: String? = null, val protection: KeyProtection? = null, val sessions: List = emptyList(), val selectedSession: String? = null, @@ -39,6 +41,16 @@ data class SshUiState(val data: SshData = SshData(), val loaded: Boolean = false /** Default network for the "local target without VPN" hint; the connection itself does not use it. */ val activeKind: NetKind? = null, val activeViaVpn: Boolean = false) +/** Restore export after process death; validate before opening/truncating the destination. */ +internal suspend fun completeSshProfileExport( + prepared: ByteArray?, read: suspend () -> SshData, write: suspend (ByteArray) -> Unit, +): SshProfileExportError? { + val bytes = try { prepared ?: encodeSshProfileExport(read()) } + catch (error: SshProfileExportException) { return error.reason } + write(bytes) // Provider/IO failures still use the normal operation error handler. + return null +} + class SshViewModel(application: Application) : AndroidViewModel(application) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val storeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) @@ -65,9 +77,16 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { if (session.connected && sessionNetworks[session.id]?.let(matches) == true) session.copy(networkLost = true) else session }) } } - fun reconnectProfile(id: String): SshProfile? = sessionProfiles[id] + fun reconnectProfile(id: String): SshProfile? = sessionProfiles[id]?.let { previous -> + _state.value.data.profiles.find { it.id == previous.id } ?: previous + } /** Called only after the same connection/startup-command confirmation as a new session. */ - fun reconnect(id: String) { sessionProfiles[id]?.let { startConnection(it, id) } } + fun reconnect(id: String, confirmedProfile: SshProfile) { + if (sessionProfiles[id]?.id != confirmedProfile.id || _state.value.data.profiles.none { it.id == confirmedProfile.id }) { + _state.update { it.copy(profileUnavailable = true, keySelectionRequired = null) }; return + } + startConnection(confirmedProfile, id) + } private val hostReplies = PromptReplyGate() private val authReplies = PromptReplyGate?>() private val backgroundPolicy = SshBackgroundPolicy(android.os.SystemClock::elapsedRealtime) @@ -147,7 +166,8 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } fun confirmProfileImport(keyRef: String?) = profileImporter.confirm(keyRef) fun cancelProfileImport() = profileImporter.cancel() - fun clearError() { _state.update { it.copy(error = false, failure = null, exported = false) } } + fun dismissKeySelection() { _state.update { it.copy(keySelectionRequired = null) } } + fun clearError() { _state.update { it.copy(error = false, failure = null, exported = false, exportFailure = null, profileUnavailable = false) } } fun saveProfile(profile: SshProfile, password: String, remember: Boolean, onSaved: () -> Unit) = operation { require(profile.valid()); val previous = store.read().profiles.find { it.id == profile.id } var newRef: String? = null @@ -158,11 +178,17 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } else previous?.secretRef } else null try { - store.update { data -> data.copy(profiles = data.profiles.filterNot { it.id == profile.id } + profile.copy(secretRef = ref)) } + store.update { data -> data.copy(profiles = if (data.profiles.any { it.id == profile.id }) + data.profiles.map { if (it.id == profile.id) profile.copy(secretRef = ref) else it } + else data.profiles + profile.copy(secretRef = ref)) } } catch (e: Exception) { newRef?.let { secrets.delete(it) }; throw e } if (previous?.secretRef != ref) previous?.secretRef?.let { secrets.delete(it) } withContext(Dispatchers.Main) { onSaved() } } + fun moveProfile(id: String, delta: Int) { + if (_state.value.busy || profileImporter.active) return + operation { store.update { moveSshProfile(it, id, delta) } } + } fun deleteProfile(id: String) = operation { val profile = store.read().profiles.find { it.id == id } ?: return@operation store.update { it.copy(profiles = it.profiles.filterNot { p -> p.id == id }) } @@ -199,12 +225,26 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { store.update { data -> require(data.profiles.none { it.keyRef == id }); data.copy(keys = data.keys.filterNot { it.id == id }) } secrets.delete(id) } + private var preparedExport: ByteArray? = null + /** Validate and freeze bytes BEFORE the document picker can create a destination. */ + fun prepareExport(onReady: () -> Unit) = operation { + preparedExport = null + _state.update { it.copy(exportFailure = null) } + try { preparedExport = encodeSshProfileExport(store.read()) } + catch (error: SshProfileExportException) { + _state.update { it.copy(exportFailure = error.reason) }; return@operation + } + withContext(Dispatchers.Main) { onReady() } + } + fun cancelExport() { preparedExport = null } fun export(uri: Uri) = operation { - val data = store.read() - // Export profiles only. No saved credentials, references, host trust, or private/public keys. - val exported = exportSshProfiles(data) - getApplication().contentResolver.openOutputStream(uri, "wt")?.use { SshDataSerializer.writeTo(exported, it) } ?: error("Export failed") - _state.update { it.copy(exported = true) } + val prepared = preparedExport + preparedExport = null + _state.update { it.copy(exportFailure = null) } + val failure = completeSshProfileExport(prepared, store::read) { bytes -> + getApplication().contentResolver.openOutputStream(uri, "wt")?.use { it.write(bytes) } ?: error("Export failed") + } + _state.update { it.copy(exportFailure = failure, exported = failure == null) } } fun connect(profile: SshProfile) { startConnection(profile, null) } private fun startConnection(profile: SshProfile, replacement: String?) { @@ -213,6 +253,11 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { replacement != null && _state.value.sessions.none { it.id == replacement }) { _state.update { it.copy(error = true) }; return } + if (profile.needsKeySelection(_state.value.data)) { + _state.update { it.copy(keySelectionRequired = profile) } + return // No session, buffer, attempt, transport or DNS is created. + } + _state.update { it.copy(keySelectionRequired = null, profileUnavailable = false) } // A replacement reuses its existing tab; keep its previous output until onConnected. if (replacement == null) while (_state.value.sessions.size >= 4) { val ended = _state.value.sessions.firstOrNull { it.ended } ?: break diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt index 17d403c..abd2a6c 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt @@ -56,10 +56,12 @@ import cz.netkit.app.ui.theme.NetKitTheme import cz.netkit.app.ui.theme.NetKitType import cz.netkit.app.update.UpdateUiState import cz.netkit.app.update.UpdateViewModel +import cz.netkit.app.update.localizedUpdateUrl import cz.netkit.app.update.openLink import cz.netkit.shared.update.UpdateCheckFailure import cz.netkit.shared.update.UpdateSource import cz.netkit.shared.update.UpdateStatus +import cz.netkit.shared.update.localizedWebUrl import cz.netkit.shared.update.privacyPolicyUrl /** @@ -122,6 +124,7 @@ internal fun SubscreenHeader(title: String, backTag: String, onBack: () -> Unit) @Composable private fun UpdatesCard(state: UpdateUiState, onToggle: (Boolean) -> Unit, onCheck: () -> Unit, onOpen: (String) -> Unit) { val colors = NetKitTheme.colors + val language = LocalConfiguration.current.locales[0].language SectionCard(stringResource(R.string.about_updates_title)) { Row( Modifier.fillMaxWidth().heightIn(min = 48.dp) @@ -143,7 +146,8 @@ private fun UpdatesCard(state: UpdateUiState, onToggle: (Boolean) -> Unit, onChe val info = state.info FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { if (info != null && state.available && (state.status == UpdateStatus.AVAILABLE || state.status == UpdateStatus.DISMISSED)) { - PrimaryButton(stringResource(R.string.update_download), { onOpen(info.openUrl) }, Modifier.testTag("about_update_open"), + PrimaryButton(stringResource(R.string.update_download), { onOpen(localizedUpdateUrl(info.openUrl, language)) }, + Modifier.testTag("about_update_open"), icon = NetKitIcons.Download, small = true) } NeutralButton(stringResource(if (state.checking) R.string.about_checking else R.string.about_check_now), onCheck, @@ -193,15 +197,15 @@ private fun updatesNote(state: UpdateUiState): String? { @Composable private fun ProjectCard(onOpen: (String) -> Unit, onOpenLicenses: () -> Unit) { val language = LocalConfiguration.current.locales[0].language - val privacy = remember(language) { - privacyPolicyUrl(BuildConfig.UPDATE_BASE_URL.takeIf { BuildConfig.UPDATE_CONFIGURED }, BuildConfig.SOURCE_URL, language) - } + val webBase = BuildConfig.UPDATE_BASE_URL.takeIf { BuildConfig.UPDATE_CONFIGURED } + val privacy = remember(language) { privacyPolicyUrl(webBase, BuildConfig.SOURCE_URL, language) } + val webPage = remember(language) { localizedWebUrl(BuildConfig.UPDATE_BASE_URL, webBase, language) } SectionCard(stringResource(R.string.about_project_title)) { Column { var divider = false if (BuildConfig.UPDATE_CONFIGURED) { - ListRow(stringResource(R.string.about_web), BuildConfig.UPDATE_BASE_URL.removePrefix("https://"), NetKitIcons.Globe, - onClick = { onOpen(BuildConfig.UPDATE_BASE_URL) }, modifier = Modifier.testTag("about_web")) + ListRow(stringResource(R.string.about_web), webPage.removePrefix("https://"), NetKitIcons.Globe, + onClick = { onOpen(webPage) }, modifier = Modifier.testTag("about_web")) divider = true } ListRow(stringResource(R.string.about_source), BuildConfig.SOURCE_URL.removePrefix("https://"), NetKitIcons.Terminal, diff --git a/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt b/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt index 2577f69..4ded5f1 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt @@ -28,6 +28,8 @@ import cz.netkit.app.ui.Spacing import cz.netkit.app.ui.theme.NetKitTheme import cz.netkit.app.ui.theme.NetKitType import cz.netkit.shared.update.UpdateInfo +import cz.netkit.shared.update.localizedWebUrl +import cz.netkit.app.BuildConfig import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException @@ -56,7 +58,7 @@ internal fun UpdateCard(info: UpdateInfo, onDismiss: () -> Unit, modifier: Modif } info.notesFor(language)?.let { Text(it, style = NetKitType.body, color = colors.text) } Text(stringResource(R.string.update_install_hint), style = NetKitType.label, color = colors.muted) - PrimaryButton(stringResource(R.string.update_download), { openLink(context, info.openUrl) }, + PrimaryButton(stringResource(R.string.update_download), { openLink(context, localizedUpdateUrl(info.openUrl, language)) }, Modifier.testTag("update_open"), icon = NetKitIcons.Download) } } @@ -81,3 +83,7 @@ internal fun openLink(context: Context, url: String) { Toast.makeText(context, R.string.about_open_failed, Toast.LENGTH_SHORT).show() } } + +/** Update page in the UI language: the web page of `latest.json` goes to `/en/netkit` outside Czech. */ +internal fun localizedUpdateUrl(url: String, language: String): String = + localizedWebUrl(url, BuildConfig.UPDATE_BASE_URL.takeIf { BuildConfig.UPDATE_CONFIGURED }, language) diff --git a/androidApp/src/main/res/values-en/ssh_design.xml b/androidApp/src/main/res/values-en/ssh_design.xml index 41dc862..4be02c2 100644 --- a/androidApp/src/main/res/values-en/ssh_design.xml +++ b/androidApp/src/main/res/values-en/ssh_design.xml @@ -1,7 +1,6 @@ More SSH actions - Actions for profile %1$s live %1$s · %2$d×%3$d Server diff --git a/androidApp/src/main/res/values-en/ssh_import.xml b/androidApp/src/main/res/values-en/ssh_import.xml index 2e6b492..2a01369 100644 --- a/androidApp/src/main/res/values-en/ssh_import.xml +++ b/androidApp/src/main/res/values-en/ssh_import.xml @@ -1,16 +1,16 @@ - Import profiles from PC - Import profiles from PC + Import profiles + Import profiles New: %1$d · changed: %2$d · unchanged: %3$d · skipped: %4$d Source: %1$s New profiles - Host, port or user will change + Profiles to update Skipped aliases Key for new profiles - This phone has no key yet. Create one under Keys, distribute its public part with the PC script and import again, or continue with a password. - No key, password sign-in - The file contains no passwords or keys. Existing profiles keep their authentication method, key and startup command. + This phone has no key yet. Key-authenticated profiles can be imported; select a key in the profile editor before connecting. + No key assignment (v1: password; v2: authentication from file) + The selected key applies only to new v1 profiles or new key-authenticated profiles. V2 and legacy exports also transfer authentication, startup command and keepalive. Existing profiles retain their local keys. Import Cancel Share public key @@ -34,5 +34,17 @@ The import would exceed 200 profiles. Profiles changed in the meantime. Open the file again. The file is not in the NetKit profile format. - The saved password will be detached and deleted; you will enter it again when connecting. + The saved password will be detached and deleted. + Select a key in the profile editor. + Move profile %1$s up + Move profile %1$s down + Authentication + %1$s: %2$s → %3$s + The startup command runs after you confirm the connection. Check its contents. + Create key + Cannot export profiles: multiple profiles share these names (%1$s). Rename them before exporting. + Cannot export profiles: the file exceeds 256 KiB. Shorten startup commands or reduce the number of profiles. + The profile was deleted. Cannot reconnect. + Edit profile %1$s + Delete profile %1$s diff --git a/androidApp/src/main/res/values/ssh_design.xml b/androidApp/src/main/res/values/ssh_design.xml index 8212fe1..49f5223 100644 --- a/androidApp/src/main/res/values/ssh_design.xml +++ b/androidApp/src/main/res/values/ssh_design.xml @@ -1,7 +1,6 @@ Další akce SSH - Akce profilu %1$s živá %1$s · %2$d×%3$d Server diff --git a/androidApp/src/main/res/values/ssh_import.xml b/androidApp/src/main/res/values/ssh_import.xml index 1fc7dc5..6d5cf0d 100644 --- a/androidApp/src/main/res/values/ssh_import.xml +++ b/androidApp/src/main/res/values/ssh_import.xml @@ -1,16 +1,16 @@ - Importovat profily z PC - Import profilů z PC + Importovat profily + Import profilů Nové: %1$d · změněné: %2$d · beze změny: %3$d · přeskočené: %4$d Zdroj: %1$s Nové profily - Změní se host, port nebo uživatel + Aktualizované profily Přeskočené aliasy Klíč pro nové profily - Telefon zatím nemá vlastní klíč. Vytvořte ho v sekci Klíče, rozdejte jeho veřejnou část skriptem na PC a import opakujte, nebo pokračujte s heslem. - Bez klíče, přihlášení heslem - Hesla ani klíče soubor neobsahuje. Existující profily si ponechají způsob přihlášení, klíč i startovací příkaz. + Telefon zatím nemá vlastní klíč. Profily s ověřováním klíčem lze importovat; před připojením vyberte klíč v úpravě profilu. + Bez přiřazení klíče (v1: heslo; v2: ověřování ze souboru) + Vybraný klíč dostanou jen nové profily v1 nebo nové profily s ověřováním klíčem. V2 a starý export přenesou i ověřování, startovací příkaz a keepalive. Místní klíče existujících profilů zůstávají. Importovat Zrušit Sdílet veřejný klíč @@ -34,5 +34,17 @@ Po importu by bylo víc než 200 profilů. Profily se mezitím změnily. Otevřete soubor znovu. Soubor nemá formát profilů NetKit. - Uložené heslo se odpojí a smaže; při připojení ho zadáte znovu. + Uložené heslo se odpojí a smaže. + Vyberte klíč v úpravě profilu. + Posunout profil %1$s nahoru + Posunout profil %1$s dolů + Ověřování + %1$s: %2$s → %3$s + Startovací příkaz se spustí po potvrzení připojení. Zkontrolujte jeho obsah. + Vytvořit klíč + Profily nelze exportovat: stejný název používá více profilů (%1$s). Před exportem je přejmenujte. + Profily nelze exportovat: soubor překračuje limit 256 KiB. Zkraťte startovací příkazy nebo snižte počet profilů. + Profil byl smazán. Připojení nelze obnovit. + Upravit profil %1$s + Smazat profil %1$s diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt new file mode 100644 index 0000000..f60ebba --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt @@ -0,0 +1,23 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.* +import java.io.ByteArrayOutputStream +import kotlinx.coroutines.test.runTest +import kotlin.test.* + +class SshLegacyExportFixtureTest { + @Test fun originalSerializerExportDecodesWithPortableSettings() = runTest { + val data = SshData(profiles = SshAuthentication.entries.mapIndexed { index, auth -> + SshProfile("old-$index", "fixture-$index", "192.0.2.${index + 1}", 2222 + index, "tester", + auth, "secret-$index", "key-$index", "show version", 60 + index) + }) + val output = ByteArrayOutputStream() + SshDataSerializer.writeTo(exportSshProfiles(data), output) + val incoming = decodeSshProfileImport(output.toByteArray()) + var id = 0 + val restored = applySshImportPlan(SshData(), planSshProfileImport(SshData(), incoming, null) { "new-${id++}" }) + assertEquals(data.profiles.mapIndexed { index, p -> p.copy(id = "new-$index", secretRef = null, keyRef = null) }, restored.profiles) + assertEquals(data.profiles.map { it.copy(secretRef = null, keyRef = null) }, + SshDataSerializer.readFrom(output.toByteArray().inputStream()).profiles) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt new file mode 100644 index 0000000..a3a6cfb --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt @@ -0,0 +1,44 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.* +import kotlinx.coroutines.test.runTest +import java.io.IOException +import kotlin.test.* + +class SshProfileExportTest { + private val profile = SshProfile("fixture", "Fixture", "192.0.2.10", username = "tester") + + @Test fun preparedSnapshotDoesNotReadChangedStore() = runTest { + val bytes = encodeSshProfileExport(SshData(profiles = listOf(profile))) + var written: ByteArray? = null + assertNull(completeSshProfileExport(bytes, { error("Snapshot must not read storage") }) { written = it }) + assertContentEquals(bytes, written) + } + + @Test fun lostSnapshotReadsAndEncodesCurrentStore() = runTest { + val current = SshData(profiles = listOf(profile.copy(name = "Current"))) + var reads = 0 + var written: ByteArray? = null + assertNull(completeSshProfileExport(null, { reads++; current }) { written = it }) + assertEquals(1, reads) + assertEquals("Current", decodeSshProfileImport(assertNotNull(written)).profiles.single().alias) + } + + @Test fun duplicateNamesAfterStateLossNeverOpenDestination() = runTest { + val data = SshData(profiles = listOf(profile, profile.copy(id = "second"))) + assertEquals(SshProfileExportError.DuplicateNames(listOf("Fixture")), + completeSshProfileExport(null, { data }) { error("Must not open/truncate destination") }) + } + + @Test fun oversizeAfterStateLossNeverOpensDestination() = runTest { + val data = SshData(profiles = (1..70).map { profile.copy(id = "p$it", name = "p$it", startupCommand = "ž".repeat(4096)) }) + assertEquals(SshProfileExportError.TooLarge, + completeSshProfileExport(null, { data }) { error("Must not open/truncate destination") }) + } + + @Test fun providerFailureStillPropagatesToOperationHandler() = runTest { + assertFailsWith { + completeSshProfileExport(null, { SshData(profiles = listOf(profile)) }) { throw IOException() } + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt index 2ed8cd3..e689afe 100644 --- a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt @@ -265,6 +265,7 @@ class SshProfileImportControllerTest { assertFalse(ready.blocksProfileImport()) for (state in listOf(ready.copy(loaded = false), ready.copy(storeFailed = true), ready.copy(busy = true), ready.copy(profileImportBlockedByDialog = true), + ready.copy(keySelectionRequired = SshProfile("fixture", "Fixture", "192.0.2.10", username = "tester", authentication = SshAuthentication.KEY)), ready.copy(authChallenge = AuthChallenge("request", "session", "identity", "", "", emptyList(), emptyList())), ready.copy(hostChallenge = HostChallenge("request", "session", TrustedHostKey("endpoint", "algorithm", "public", "SHA256:x"), null)))) { assertTrue(state.blocksProfileImport()) @@ -303,4 +304,20 @@ class SshProfileImportControllerTest { assertContentEquals(before, file.readBytes()) } finally { storeScope.coroutineContext[Job]!!.cancelAndJoin(); directory.deleteRecursively() } } + @Test fun authenticationChangeDeletesDetachedPasswordAfterCommit() = runTest { + for (auth in listOf(SshAuthentication.KEY, SshAuthentication.INTERACTIVE)) { + val original = SshProfile("saved", "Fixture", "192.0.2.10", username = "tester", secretRef = "saved-secret") + val fixture = Fixture(this, SshData(profiles = listOf(original))) + val input = encodeSshProfileExport(SshData(profiles = listOf(original.copy(authentication = auth)))) + fixture.controller.preview { input }; advanceUntilIdle() + assertEquals(listOf("saved-secret"), fixture.controller.state.value.pendingProfileImport!!.plan.detachedSecretRefs) + assertTrue(fixture.deleted.isEmpty()) + fixture.beforeDelete = { assertNull(fixture.data.profiles.single().secretRef) } + fixture.controller.confirm(null); advanceUntilIdle() + assertEquals(listOf("saved-secret"), fixture.deleted) + assertEquals(auth, fixture.data.profiles.single().authentication) + assertEquals(1, fixture.writes) + } + } + } diff --git a/docs/architektura.md b/docs/architektura.md index 1de83a4..ef9ebeb 100644 --- a/docs/architektura.md +++ b/docs/architektura.md @@ -7,13 +7,15 @@ známé nedostatky a vazby na SHA APK eviduje report 08 (interní záznam). ## 1. Moduly -- `:shared`: Kotlin Multiplatform s cíli `androidTarget()` a `jvm()`. Společné modely, +- `:shared`: Kotlin Multiplatform s cíli `androidTarget()` a `jvm()`. Od iOS P0 se na macOS + nebo s `-Pnetkit.ios=true` přidávají `iosArm64()` a `iosSimulatorArm64()`. Společné modely, čistá logika a WoL controller jsou v `src/commonMain`; testy v `src/commonTest`. - `:androidApp`: Compose UI, Android ViewModely, síťové implementace, úložiště, JVM testy v `src/test` a emulátorová instrumentace v `src/androidTest`. Balíčky jsou `cz.netkit.shared.` a `cz.netkit.app.`, ID aplikace -`cz.netkit.app`. iOS target není deklarovaný; viz [ios.md](ios.md). Platformní +`cz.netkit.app`. iOS kostra používá SwiftUI a statický framework `NetKitShared`; stav ověření +je v [ios.md](ios.md#8-implementace-swiftui--p0-2026-10-31). Platformní implementace jsou nyní v `androidApp`, samostatný `shared/src/androidMain` se nepoužívá. ## 2. Rozdělení odpovědností diff --git a/docs/bezpecnost.md b/docs/bezpecnost.md index 880c664..8b62f44 100644 --- a/docs/bezpecnost.md +++ b/docs/bezpecnost.md @@ -549,3 +549,64 @@ logika `shared/.../update/UpdateInfo.kt` a `UpdateFetch.kt` (`nextRedirect`, `ch náhled schránky, **nebrání vložení ani čtení oprávněnou aplikací**. Veřejný SSH klíč, fingerprint a LAN výsledky se tímto příznakem neoznačují; nejde o kopie přihlašovacích tajemství. Ověření implementace a neprovedené kontroly: report 30 (interní záznam). + +## iOS síťové nástroje (P1, 2026-10-31) + +Android pravidla výše se nemění. iOS používá SwiftUI a platformní síťová API: + +- `NSLocalNetworkUsageDescription`: uživatelem spuštěné TCP/DNS/ICMP sondy, Bonjour a WoL. + `NSBonjourServices` uvádí konkrétní `_ssh._tcp`; aplikace neprohlíží všechny typy služeb. +- `NSLocationWhenInUseUsageDescription`: vysvětlení pro aktuální Wi-Fi. Access Wi-Fi Information + entitlement není přidaný; bez něj se zobrazí nedostupnost údajů a nevyžaduje se nepoužitelná poloha. +- Restricted multicast entitlement není přidaný ani vyžádaný. WoL broadcast je odmítnut před + odesláním; povolen je pouze unicast ve zjištěné podsíti vybraného Wi-Fi rozhraní, bez mobilního + fallbacku. Změna pozorované síťové cesty ruší operace. Změnu AP bez změny rozhraní nelze + bez potřebných oprávnění spolehlivě identifikovat. +- TCP: jediný zadaný cíl, maximálně 64 portů, čtyři současná spojení, konečné timeouty. + ICMP je datagramový, bez raw socketů. Síťové nástroje vyžadují potvrzení vlastní/povolené sítě; + nic se nespouští automaticky. Zrušení operace a opuštění obrazovky ukončuje její transporty. +- DNS i názvy Bonjour jsou nedůvěryhodné: sdílené parsery a sanitizace, kontrola dotazu/odpovědi, + omezená velikost odpovědi. Odmítnutá či zkrácená DNS zpráva se nezobrazuje jako úspěšná odpověď. +- Speedtest používá HTTPS/WSS, odmítá přesměrování a omezuje velikost odpovědí i fronty. + Každý start potvrzuje datovou zátěž; NDT7 navíc uchování a veřejné zveřejnění výsledku včetně IP + u M-Lab. Přístupové tokeny ani úplná přístupová URL se neukládají a nelogují. Žádná analytika + aplikace, reklamy nebo sledování. Dobrovolné měření M-Lab přesto představuje externí sběr dat, + který je uveden v privacy manifestu a upozornění uživatele. +- Testovací provoz v CI směřuje pouze na loopback nebo do lokálních mocků. Local Network dialog, + skutečné oprávnění k Wi-Fi a chování fyzické sítě nejsou simulátorem ověřeny. + +Zdroje ověřené 2026-10-31: [Apple TN3179](https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy), +[Wi-Fi fetchCurrent](https://developer.apple.com/documentation/networkextension/nehotspotnetwork/fetchcurrent(completionhandler:)), +[M-Lab NDT](https://www.measurementlab.net/tests/ndt/index.html). + + +## iOS SSH (P2, 2026-10-31) + +- `KeychainSecrets` ukládá hesla a raw Ed25519 privátní klíče jako generic-password položky, + oddělené service/account, se synchronizací vypnutou a + `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`. Identifikátory a limit 256 KiB kontroluje + také iOS adaptér společného `SecretStore`. Jen not-found znamená chybějící tajemství; + zamčené nebo nedostupné úložiště nezpůsobí plaintext fallback. Pracovní kopie jsou dočasně + v paměti Swift/Kotlin/knihovny; negarantujeme vymazání všech jejich kopií. +- Profily, veřejné klíče a důvěra jsou v app-private `ssh.json`, nikoli tajemství. Soubor je + atomický, s complete file protection a v adresáři vyloučeném ze záloh. Vadný/novější obsah + ani IO chyba se nepřepíší prázdnou databází. Import používá sdílené limity a compare-before-apply. +- Host key se ověřuje před předáním uživatelské autentizace. SHA256 otisk se počítá z raw SSH blobu; + důvěra porovnává algoritmus, veřejný klíč a přesný normalizovaný endpoint. Unknown confirmation + používá jednorázovou bránu s náhodným ID a atomický compare-and-insert. Changed je vždy odmítnut; + potvrzovací callback jej nemůže povolit. Reset důvěry vyžaduje zvláštní potvrzení a zavření relace. +- Oficiální NIOSSH v připnuté verzi nabízí jen bezpečnou podmnožinu společné politiky. RSA/SHA-1, + DSA ani staré šifry se nepřidávají pro kompatibilitu. SSH nevypíná VPN a používá systémovou trasu. + Časové limity a rušení uzavírají transport; fronta zápisů a přenos na UI mají pevné limity. +- Schránka terminálu používá `UIPasteboard` s `localOnly`, expirací 60 s a podmíněným vyčištěním, + jen pokud se obsah od kopie nezměnil. Omezuje sdílení mezi zařízeními a životnost, nezaručuje + ochranu před vložením nebo čtením oprávněnou aplikací. Vkládání řídicích znaků je potvrzené a + sanitizované sdílenou funkcí; paste není alternativní cesta k Enter/ESC sekvencím. +- Žádná SSH tajemství, privátní klíče, autentizační prompty, příkazy ani terminálový výstup se + nelogují. Testy používají pouze za běhu generované klíče/hesla a loopback SSH server. Nové + entitlementy ani oprávnění se kvůli SSH nepřidávají. + +Zdroje: [Keychain accessibility](https://developer.apple.com/documentation/security/ksecattraccessiblewhenunlockedthisdeviceonly), +[schránka localOnly](https://developer.apple.com/documentation/uikit/uipasteboard/optionskey/localonly), +[NIOSSH 0.15.1](https://github.com/apple/swift-nio-ssh/tree/0.15.1). +Stav testů a omezení jsou v [ios.md §10](ios.md#10-ssh-klient-a-terminál-p2-2026-10-31). diff --git a/docs/funkce/ssh.md b/docs/funkce/ssh.md index ad710f7..c471e58 100644 --- a/docs/funkce/ssh.md +++ b/docs/funkce/ssh.md @@ -214,6 +214,9 @@ Oficiální zdroje pro tuto opravu ověřené 2026-10-26: ## 8. Import profilů z PC +Tento oddíl popisuje formát v1 z PC skriptu. Importní dialog nyní přijímá +také v2 a starý export telefonu; jejich přenos nastavení a omezení popisuje §9. + PC skript `tools/netkit_ssh_export.py` (jen standardní knihovna Pythonu 3.12) převede aliasy z `~/.ssh/config` na importní soubor `netkit-ssh-profiles` v1 (formát je závazně popsaný v interní pracovní záznam) a volitelně rozdá veřejný klíč telefonu. @@ -272,3 +275,64 @@ Při změně hostu, portu nebo uživatele existujícího profilu import odpojí Testy: `tools/test_netkit_ssh_export.py` (syntetické configy, podvržený `ssh -G` runner, žádné skutečné připojení). Fyzický průchod importu na telefonu ověřuje správce. + +## 9. Výměnný formát v2, starý export a pořadí profilů + +Android exportuje `netkit-ssh-profiles.json`: `format: "netkit-ssh-profiles"`, +`schema: 2`, `source: "netkit-android"`, pole `profiles` a prázdné `skipped`. +Každý profil obsahuje `alias`, `host`, `port`, `username`, `authentication` +(`PASSWORD`, `KEY`, `INTERACTIVE`), `startupCommand` a `keepaliveSeconds`. +Pořadí pole je pořadí v aplikaci. Import navíc přijímá volitelné `group` jako +metadata náhledu; skupiny se v aplikaci neukládají. + +Export neobsahuje lokální ID, `secretRef`, `keyRef`, klíče ani důvěru serverů. +Obsahuje však cíle, uživatelská jména a startovací příkazy: před přenosem ověřte, +že příkaz sám neobsahuje citlivé údaje. Limity importu jsou 256 KiB, 200 profilů +(a nejvýše 200 přeskočených řádků), omezená hloubka JSON a allowlist polí. +Před otevřením systémového dialogu pro vytvoření souboru se připraví a ověří +neměnný export. Duplicitní jména (včetně jejich výčtu) nebo překročení 256 KiB +mají konkrétní CS/EN hlášku a dialog se neotevře; nevznikne prázdný soubor. +Stejná jména při uložení profilů zůstávají povolená. Změny profilů během +otevřeného dialogu neovlivní již připravený export. Pokud Android během SAF +ukončí proces a snapshot se ztratí, po návratu se export znovu vytvoří z +aktuálního úložiště. Duplicity/velikost se znovu ověří před otevřením cíle +pro zápis a zobrazí stejnou konkrétní chybu. Soubor, který už vytvořil SAF, +může při této chybě zůstat prázdný; aplikace ho neotevře ani nepřepíše. +Varování exportu a smazaného profilu lze zavřít tlačítkem OK. + +Import přijímá také v1 z PC skriptu (§8) a původní export telefonu: objekt bez +`format`, `schema: 1`, pole profilů s `name` místo aliasu a starými ID. +Staré ID se nepřebírá. `hostKeys`, `keys`, `rejectedHostKeys` musí být prázdné +seznamy a reference `secretRef`/`keyRef` null (nebo chybět); jinak se celý soubor +odmítne. **Nejde o import zálohy úložiště nebo důvěry serverů.** + +Párování používá přesnou shodu aliasu a jména. V1 mění pouze host, port a +uživatele. V2 a starý export navíc aktualizují ověřování, startovací příkaz a +keepalive; náhled ukazuje každý změněný údaj jako „před → po“. Změna příkazu +má varování, protože se příkaz spustí po potvrzení připojení. Změna cíle +(host/port/uživatel) odpojí uložené heslo jako v §8. Existující `keyRef` se +podle rozhodnutí správce 2026-11-01 zachovává i při změně cíle. Při změně +samotného typu ověřování se ale nepoužívaná reference odpojí: odchod z KEY +odstraní `keyRef`, odchod z PASSWORD odstraní `secretRef` a po úspěšném zápisu +smaže uložené heslo. Náhled při aktualizaci na KEY bez existujícího klíče +výslovně požaduje jeho výběr. U nového profilu v1 ukazuje ověřování podle +aktuální volby klíče v importním dialogu. + +Nové profily se přidají na konec v pořadí souboru; existující profily si +ponechají pozici. Vybraný lokální klíč dostanou nové v1 profily a nové +v2/legacy profily typu `KEY`. Ostatním typům v2 se ověřování výběrem klíče +nemění. Bez výběru zůstane nový v2/legacy `KEY` bez přiřazeného klíče. +Připojení i reconnect v tom případě nevytvoří transport a nabídnou přechod +do editoru. Totéž platí pro odkaz na již neexistující klíč. Editor výslovně +vyžádá výběr; vždy při chybějícím přiřazení nabídne „Vytvořit klíč“, i s jinými klíči v seznamu. Návrat z Klíčů +zachovává netajná rozepsaná pole, nikoli heslo. Reconnect použije přesný profil potvrzený v dialogu, včetně +cíle a startovacího příkazu. Smazaný profil odmítne chybou bez nabídky editoru, +aby editace neobnovila již smazaný profil. + +Řádek správy profilu nabízí úpravu, smazání a šipky nahoru/dolů ve stylu WoL. +Na kraji seznamu a během operace jsou příslušné šipky zakázané; mají CS/EN +popisky pro TalkBack. Pořadí se ukládá v seznamu profilů, přežije restart, +promítne se do exportu a nemění se běžnou editací profilu. + +Implementační a testovací důkazy jsou v reportu 32 (interní záznam); +fyzické přijetí zůstává v checklistu správce. diff --git a/docs/ios.md b/docs/ios.md index 497d4cd..1ebde82 100644 --- a/docs/ios.md +++ b/docs/ios.md @@ -1,7 +1,16 @@ # NetKit — iOS analýza -**Stav 2026-10-27:** analýza pro budoucí rozhodnutí. **Nic se nestaví. Rozhodnutí D12: iOS se -zatím nedělá** (viz §6). Údaje označené „ověřit“ je nutné potvrdit v oficiální dokumentaci Applu +**Stav 2026-11-01:** P0 ověřena v ARM simulátoru — SwiftUI nad `:shared`, link, build, Kotlin/Native, +XCTest bridge a CS/EN UI testy prošly v [CI 41219799892](https://github.com/Losminek/netkit-ios/actions/runs/41219799892). +P1 prošla v [CI 41236666699](https://github.com/Losminek/netkit-ios/actions/runs/41236666699). +P2b prošla v [CI 41286184503](https://github.com/Losminek/netkit-ios/actions/runs/41286184503): +45 XCTest a 6 UI testů. P3 prošla v [CI 41287557230](https://github.com/Losminek/netkit-ios/actions/runs/41287557230). +Opravy revize R1 (interní záznam) prošly v [CI 41292675688](https://github.com/Losminek/netkit-ios/actions/runs/41292675688) (XCTest 68, UI 8); 2026-11-01 přeneseno do vývojového repa a od verze 1.0.1 součástí veřejného exportu. +Parita SSH profilů v2 (§13) prošla v [CI 41323807968](https://github.com/Losminek/netkit-ios/actions/runs/41323807968) +na `f3b5fad`: XCTest 83/0, UI 18/18 CS/EN a Linux PASS. +Aktuální implementaci a omezení popisují §8–13. +Níže původní analýza z 2026-10-27 (D12) a v §7 ověření +buildu bez Macu. Údaje označené „ověřit“ je nutné potvrdit v oficiální dokumentaci Applu v době, kdy se o iOS bude rozhodovat. Údaje v §6 byly ověřeny 2026-10-27; **[P]** = prokázáno zdrojem, **[O]** = odhad. @@ -119,3 +128,323 @@ iOS se znovu otevře, až platí **všechno** z toho: Má firma kolegů Apple Business Manager (jen pro Custom Apps)? Je správce ochoten zveřejnit údaje obchodníka? Compose Multiplatform (stable od 1.8.0, květen 2025 **[P]** [JetBrains](https://blog.jetbrains.com/kotlin/2025/05/compose-multiplatform-1-8-0-released-compose-multiplatform-for-ios-is-stable-and-production-ready/)) nebo SwiftUI nad `:shared`: stále odloženo (§4). + +## 7. Build bez Macu (ověřeno 2026-10-31) + +| Cesta | Verdikt | Zdroj | +|---|---|---| +| xtool (Linux, SwiftPM → iOS app) | **nepoužít**: staví jen SwiftPM projekty, Kotlin `:shared` nepřeloží; potřebuje rozbalený Xcode, jehož licence povoluje SDK jen na Apple hardware; bez simulátoru, nasazuje na fyzické zařízení | **[P]** [xtool](https://github.com/xtool-org/xtool), [Xcode and Apple SDKs Agreement](https://www.apple.com/legal/sla/docs/xcode.pdf) | +| Kotlin/Native na Linuxu | `.klib` pro Apple targety jen bez cinterop; framework/XCFramework jen na macOS; Gradle link na Linuxu tiše přeskočí | **[P]** [native-target-support](https://kotlinlang.org/docs/native-target-support.html) | +| GitHub Actions macOS | standardní runnery ve **veřejném** repu zdarma; v soukromém repu z kreditu (Pro 18 USD/měs, macOS 0,062 USD/min) | **[P]** [GitHub Actions billing](https://docs.github.com/en/billing/concepts/product-billing/github-actions) | + +Zvoleno (D28): vývoj ve veřejném `Losminek/netkit-ios`, build a testy v simulátoru na macOS runneru. + +## 8. Implementace SwiftUI — P0 (2026-10-31) + +Platná volba je **SwiftUI, iOS 17+**, nad Kotlin Multiplatform `:shared`. Historické odložení UI +a podmínka Apple účtu v §4–6 již neplatí pro vývoj a simulátorové testy. Účet, podpis pro zařízení +a distribuce nejsou součástí této fáze. Android aplikace ani její platformní implementace se nemění. + +### Co je připraveno + +- `shared/build.gradle.kts` deklaruje `iosArm64` a `iosSimulatorArm64` jen na macOS nebo při + `-Pnetkit.ios=true`. Obě varianty poskytují statický framework `NetKitShared` a úlohu + `:shared:assembleNetKitSharedDebugXCFramework`. Linux bez přepínače nadále deklaruje Android a JVM. +- `iosApp/NetKit.xcodeproj`, sdílené schéma `NetKit`: jedna SwiftUI obrazovka zobrazuje verzi a + výsledek existujícího `WolDomainKt.parseIpv4`. Jde o lokální výpočet nad dokumentační adresou, + bez síťového provozu. `commonMain` se kvůli této kostře nemění. +- CS/EN texty jsou v `Localizable.xcstrings`. `PrivacyInfo.xcprivacy` deklaruje žádné sledování, + sběr dat ani použití required-reason API v kostře. Síťová oprávnění, Bonjour služby a popis polohy + se doplní spolu s konkrétní funkcí; P0 je nevyžaduje ani nežádá. +- Kotlin `iosTest` ověřuje parser a výpočet broadcastu bez soketu. XCTest volá skutečný sdílený parser; + UI testy spouštějí aplikaci v češtině a angličtině a kontrolují výsledek i verzi. + +### Sestavení a ověření + +Workflow [ios.yml](../.github/workflows/ios.yml) má samostatný Linux job pro Android/JVM regresi +a macOS job pro ARM simulátor. V privátním `netkit-dev` se spouští jen ručně (`workflow_dispatch`), +protože macOS minuty se počítají 10×; spustit po změně `iosApp/`, `iosMain` nebo sdíleného API, +které `iosMain` volá. Verze toolchainu a jejich zdroje jsou v +[závislostech](zavislosti.md#6-ios-kostra-a-ci-p0-2026-10-31). +macOS job kontroluje existenci binárky, hlavičky a module map frameworku; pouhý úspěšný Gradle +příkaz nestačí. Následují `xcodebuild build` a `xcodebuild test`; od opravy P2 3/3 používají +lokální ad-hoc podpis simulátoru (`CODE_SIGN_IDENTITY=-`) kvůli Keychain testům. +Tato [pseudoidentita nevyžaduje certifikát](https://developer.apple.com/library/archive/documentation/Security/Conceptual/CodeSigningGuide/RequirementLang/RequirementLang.html), +Apple účet, vývojový tým ani provisioning profil. Nejde o podpis pro distribuci či zařízení. +Logy a `.xcresult` se ukládají jako artefakt `ios-simulator-results` i při neúspěchu. + +**Vývoj:** iOS je od verze 1.0.1 součástí veřejného exportu. Pro samostatné iOS kolo se +`Losminek/netkit-ios` dočasně odarchivuje, synchronizuje se sdílené jádro a pracuje se na větvi +`codex/*`. Po nezávislé revizi a zeleném `ios.yml` se změny vracejí přes PR do vývojového repa; +po uzavření kola se veřejné iOS repo znovu archivuje. Push a CI zajišťuje pověřený reviewer. +Android se z tohoto repa nevydává ani netaguje. + +Na macOS lze pro simulátor spustit: + +```sh +./gradlew --no-daemon --dependency-verification strict -Pnetkit.ios=true \ + :shared:linkDebugFrameworkIosSimulatorArm64 :shared:iosSimulatorArm64Test +xcodebuild -project iosApp/NetKit.xcodeproj -scheme NetKit \ + -configuration Debug -sdk iphonesimulator \ + -destination 'platform=iOS Simulator,name=iPhone 16,OS=18.5' \ + CODE_SIGN_IDENTITY=- CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=YES build test +``` + +Xcode projekt odkazuje přímo na framework odpovídající platformě a konfiguraci. Plný XCFramework +(device + simulator) sestaví `:shared:assembleNetKitSharedDebugXCFramework` na macOS; +CI P0 ověřuje pouze debug simulator slice. Release framework ani device slice zatím ověřeny nejsou. +Linuxové spuštění s přepínačem není důkazem Apple linkování. Před další fází musí projít oba CI joby. + +### Dosud neimplementováno a neověřeno + +Síťové funkce P1 popisuje §9. Implementaci SSH, Keychainu a terminálu P2 popisuje §10. +iOS nemá Wi-Fi scan okolí ani graf kanálů; ty nejsou plánovány. +P0 bridge, linkování a lokalizované UI testy potvrdil běh CI uvedený v úvodu. To neověřuje +síťové transporty P1 ani chování na zařízení. + +Později na fyzickém zařízení, nikoli v této fázi: + +- Local Network dialog: povolení umožní cílenou LAN operaci, odmítnutí zobrazí srozumitelný stav. +- Wi-Fi info: bez entitlementu/polohy prázdný stav; s oprávněním údaje pouze o aktuální síti. +- WoL: unicast na povolený cíl včetně opakování po vypršení ARP cache uspaného cíle. + Úspěch UDP send znamená předání systému, nikoli důkaz odeslání rámce či probuzení. + Broadcast až s oprávněným multicast entitlementem. +- ICMP: datagramový ping v povolené síti, timeout a zrušení bez raw socketů. +- Entitlementy: ověřit dostupnost před zařízením/distribucí, nepožadovat je kvůli CI simulátoru. + +## 9. Síťové nástroje — P1 (ověřeno v simulátoru) + +P1 používá Swift transporty nad existující doménou `:shared`. Adaptéry v `iosMain` zpřístupňují +validaci portů, DNS zprávy, ICMP matcher, sanitizované mDNS názvy, rychlostní výpočty a skutečný +`WolController`. `commonMain`, Android aplikace a její platformní implementace se v P1 nemění. + +### Transporty a rozsah + +| Nástroj | Implementace | Omezení | +|---|---|---| +| TCP porty | `NWConnection`, sdílený parser portů; jeden zadaný host, nejvýše 64 portů a čtyři současná spojení | Každý port má timeout; odlišuje odpověď, odmítnutí, timeout a chybu. Nejde o automatický sken rozsahu. | +| DNS | UDP `NWConnection` na zadaný resolver, sdílené kódování a parsování zpráv | Kontroluje ID, otázku, třídu a typ, QR/RCODE a truncation; P1 UI dotazuje A, bez TCP fallbacku a DNSSEC validace. | +| Ping | IPv4 `SOCK_DGRAM` / ICMP, checksum a náhodný payload; shared matcher kontroluje sekvenci a celý payload | Jeden dotaz s RTT a timeoutem, bez raw socketu. Dostupnost skutečného ICMP čeká na zařízení. Traceroute není implementován. | +| mDNS | `NWBrowser` pro předem deklarovaný typ `_ssh._tcp`, sdílená sanitizace a model `LanDeviceName` | Omezené prohlížení služby po explicitním startu, nikoli seznam všech zařízení nebo všech Bonjour typů. | +| Aktuální Wi-Fi | `NEHotspotNetwork.fetchCurrent`, explicitní načtení SSID/BSSID | Bez Access Wi-Fi Information entitlementu vrací prázdný stav; entitlement se nepřidává ani nežádá. Nejde o sken okolí. | +| WoL | `WolController`, Swift implementace transportu přes UDP `NWConnection` a platformního úložiště | Unicast pouze v podsíti vybraného Wi-Fi rozhraní. Broadcast režim vytváří shared controller, transport jej bez restricted entitlementu odmítá. | +| LibreSpeed | URLSession HTTPS, šest paralelních download a tři upload úlohy, sdílený trace a výpočet po náběhu | URLSession může HTTP/2 či HTTP/3 multiplexovat; počet úloh není záruka počtu TCP spojení ani shody s Android metodikou. | +| NDT7 | HTTPS locate, validace shared parserem, URLSession WSS s ověřeným subprotokolem | Download vyhodnocuje klientský trace po náběhu, upload používá serverové AppInfo za celý test; metody se liší a UI to uvádí. | + +Swift Network.framework byl zvolen pro TCP, DNS a WoL, protože sjednocuje rušení, timeouty a +výběr rozhraní s ostatními nativními API. POSIX je omezen na ICMP a čtení lokálního rozhraní, +kde Network.framework neposkytuje potřebný datagramový ICMP transport. Žádná nová síťová knihovna. +LAN sondy používají systémovou trasu; iOS P1 neslibuje Android vazbu všech LAN nástrojů na Wi-Fi. +Uživatel potvrzuje, že zkoumá vlastní nebo povolený cíl, před zahájením operace. + +WoL připíná konkrétní `NWInterface`, vyžaduje Wi-Fi a při změně pozorované cesty ruší operace. +Bez entitlementu nelze zaručit detekci každé změny AP/SSID na stejném rozhraní; timeout a token +cesty jsou konzervativní ochrana, nikoli důkaz stejné fyzické sítě. Mobilní fallback pro WoL není. +Routovaný unicast mimo místní podsíť P1 nepovoluje. Úspěšné UDP odeslání samo nedokazuje probuzení. +Profily se ukládají atomicky do Application Support se zákazem zálohy, přes sdílený verzovaný +WoL codec a limit 1 MiB. Chyba čtení se nezamění za prázdný seznam ani automatický reset. +Adapter `WakeProber` podporuje připnutý TCP/ICMP pro profil s povolenou kontrolou; P1 formulář +zatím nevystavuje nastavení této kontroly u nových profilů. + +### Oprávnění, soukromí a testy + +`Info.plist` obsahuje `NSLocalNetworkUsageDescription`, `NSBonjourServices` a +`NSLocationWhenInUseUsageDescription`; popisy jsou v CS/EN `InfoPlist.strings`. Uživatelské texty +jsou ve String Catalogu. Aplikace bez entitlementu nežádá polohu, kterou pro Wi-Fi nemůže využít. +`PrivacyInfo.xcprivacy` deklaruje žádné sledování a důvod `35F9.1` pro měření intervalů. +Obsahuje i deklaraci diagnostických/síťových údajů předávaných při volitelném NDT7: veřejná IP +není anonymní údaj a M-Lab výsledky uchovává a zveřejňuje. Před každým startem je potvrzení +objemu dat a u NDT7 také zveřejnění IP a odkaz na zásady. App Store formuláře se v této fázi nevyplňují. + +Speedtest nic nespouští automaticky, odpovědi mají velikostní limity a přesměrování se odmítají. +Přístupové URL s tokeny se neukládají ani nelogují. Testy nepřenášejí zátěž na veřejné servery: +TCP, DNS a WoL používají loopback; speed transporty používají lokální mocky. WSS fake ověřuje +orchestraci, nenahrazuje handshake skutečného M-Lab serveru ani měření rychlosti na zařízení. + +Testy P1 prošly v CI uvedeném v úvodu; následná regrese prošla i v P2b. Linuxové testy samy +nemohou potvrdit Swift kompilaci, Objective-C export, Apple linkování ani síťové API simulátoru. +Fyzická Wi-Fi zůstává neověřena. Local Network dialog podle Apple simulátor nepodporuje. + +Ověřené oficiální zdroje (2026-10-31): + +- [Apple TN3179](https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy): Local Network, Bonjour, multicast/broadcast a omezení simulátoru. +- [NEHotspotNetwork.fetchCurrent](https://developer.apple.com/documentation/networkextension/nehotspotnetwork/fetchcurrent(completionhandler:)): podmínky údajů o aktuální Wi-Fi. +- [Apple privacy API reasons](https://developer.apple.com/documentation/bundleresources/app-privacy-configuration/nsprivacyaccessedapitypes/nsprivacyaccessedapitype): důvod pro intervalové měření. +- [M-Lab NDT](https://www.measurementlab.net/tests/ndt/index.html) a [Apple privacy details](https://developer.apple.com/app-store/app-privacy-details/): předávaná IP, výsledky a deklarace sběru. + + +## 10. SSH klient a terminál (P2, 2026-10-31) + +P1 je ověřena v simulátoru: [CI 41236666699](https://github.com/Losminek/netkit-ios/actions/runs/41236666699), +Linux i macOS PASS, XCTest 30/30, UI 3/3 a Kotlin/Native testy PASS. +P2b prošla v [CI 41286184503](https://github.com/Losminek/netkit-ios/actions/runs/41286184503): +45 XCTest a 6 UI testů. Tento běh ověřil Swift sestavení, Apple linkování a Keychain simulátoru; +lokální Linux navíc ověřuje přenosné Kotlin bridge testy, ale nenahrazuje macOS ani zařízení. + +- SwiftUI obrazovka SSH umožňuje uložit/upravit profil, přihlásit se heslem nebo v aplikaci + vygenerovaným Ed25519 klíčem, otevřít PTY shell a relaci zavřít. Veřejný OpenSSH klíč lze + zkopírovat pro registraci na vlastním serveru. Tajemství jsou pouze v Keychainu. +- Používá oficiální SwiftNIO SSH 0.15.1; přesné přímé i tranzitivní verze a licence jsou + v [zavislosti.md §8](zavislosti.md#8-ios-ssh-p2-ověřeno-2026-10-31). Podporovaná kryptografická + sada je podmnožinou Android allowlistu, bez slabšího fallbacku. +- TOFU před autentizací ukáže endpoint, algoritmus a SHA256 otisk z SSH veřejného blobu. + První klíč vyžaduje výslovné potvrzení; jiný již uložený klíč je odmítnut a UI ukáže varování. + Reset důvěry je samostatně potvrzená akce a zavře aktivní relaci. Pozdní odpověď na zrušenou + či vypršelou výzvu nemůže potvrdit další spojení. Metadata se ukládají atomicky a bez záloh. +- JSON import profilů používá `SshProfileImport`, maximálně 256 KiB a hloubku JSON 16, + náhled přidaných/změněných/přeskočených položek a potvrzení. Změna hosta/portu/uživatele + odpojí uložené heslo; import nepřenáší tajemství ani důvěru k serverům. +- Vykreslení používá shared `TerminalBuffer`, vstup `TerminalInput` a `TerminalComposition`. + Zachovává VT subset, barvy, bold, kurzor a změnu velikosti PTY. Klávesnice má Ctrl, Esc a šipky; + vložení řídicích znaků se potvrzuje a sanitizuje. Neimplementuje OSC schránku, odkazy ani obrázky. +- Kopie terminálu je lokální schránka s expirací 60 s; podrobnosti a meze v bezpečnostní dokumentaci. + Terminál ani příkazy se nezapisují do souboru nebo logu. Příchozí a odchozí fronty jsou omezené. +- Jedna aktivní relace používá systémovou trasu včetně VPN. Pozadí má stejnou pětiminutovou + ochrannou lhůtu jako sdílená politika, ale iOS může proces pozastavit nebo ukončit; není + zapnutý background mode a aplikace neslibuje trvalé SSH na pozadí. + +Omezení P2: RSA host/user klíče, import cizích privátních klíčů, keyboard-interactive, +SFTP/tunely, automatické startup příkazy a keepalive nejsou implementovány. Metadata startupCommand +/keepaliveSeconds se zachovají, ale transport je neprovádí. Generované privátní klíče se neexportují. +Původní P2 ponechávala po nahrazení přihlašovacího údaje neodkazované položky v Keychainu; +opravu úklidu a mazání profilů/klíčů řeší R1 (§12). Tato omezení nezavádějí slabší autentizaci. + +XCTest používají skutečný NIOSSH server pouze na 127.0.0.1, runtime generované host/user klíče +a heslo, bez spouštění příkazů hostitele. Prověřují password/key auth, TOFU před autentizací, +změnu host key, zrušení/pozdní potvrzení, Keychain a sdílený terminál. UI smoke přidává prázdný +stav SSH. Výsledek P2b je uveden výše; dosavadní síťové testy zůstávají součástí regrese. + +Od opravy P2 3/3 běží unit testy v hostitelské `NetKit.app` přes `TEST_HOST`/`BUNDLE_LOADER`, +aby používaly oprávnění procesu aplikace. Test target obsahuje jen testy a fixture; +aplikační typy zpřístupňuje `@testable import NetKit` s testability v Debug. NetKitShared +linkuje aplikace; v test targetu je odstraněn explicitní link i autolink tohoto frameworku. +Import jeho typů zachovává framework search paths. Přímé Swift Package produkty lokálního +SSH test serveru zůstávají. P2b doplnila aplikační produkt `NIOFoundationCompat` z již +pinovaného swift-nio; test target jej přímo nelinkuje. Linkování a Keychain potvrdil zelený běh P2b. + +**Export compliance před distribucí:** SSH přidává do aplikace vlastní protokolovou vrstvu +s kryptografií, i když matematické primitivy na iOS poskytuje CryptoKit. Hodnota +`ITSAppUsesNonExemptEncryption` a případné podklady se rozhodnou před distribucí; +P2 ji nenastavuje a nečiní právní závěr o výjimce. Zdrojem postupu je +[Apple export compliance](https://developer.apple.com/help/app-store-connect/manage-app-information/overview-of-export-compliance/) +(ověřeno 2026-10-31). Apple účet, podepisování pro zařízení, TestFlight a App Store zůstávají mimo rozsah. + +Na zařízení zbývá ověřit zamčený Keychain, pozastavení/ukončení aplikace, změnu síťové cesty, +VPN a Wi-Fi/mobilní přechod, IME/hardwarovou klávesnici a skutečné chování schránky/Universal Clipboard. +Simulátor tato ověření nenahrazuje. + + +## 11. Dokončení — P3 (ověřeno 2026-11-01) + +P3 upravuje navigaci na právě čtyři záložky ve stejném pořadí jako Android: +Přehled / Zařízení / SSH / WoL (EN Overview / Devices / SSH / WoL). Přehled zobrazuje +aktuální Wi-Fi přímo a odkazy na podobrazovky Speedtest a O aplikaci; Zařízení obsahuje mDNS, ping, +TCP porty a DNS. Systémová položka More se nepoužívá. Spektrum není součástí iOS. +CS i EN UI testy mají ověřit čtyři položky, přístup k O aplikaci a prázdné stavy (AC-009). +P3 potvrdil zelený běh [CI 41287557230](https://github.com/Losminek/netkit-ios/actions/runs/41287557230); +nejde o ověření na fyzickém zařízení. + +O aplikaci poskytuje verzi, lokalizovaný odkaz na zásady a offline licence komponent. +`IosAboutDomain.privacyUrl(language:)` přijímá jazykový kód: `cs` (bez ohledu na velikost +písmen) vrátí `https://www.daniel.losak.cz/netkit/privacy`, ostatní kódy +`https://www.daniel.losak.cz/en/netkit/privacy`. Wrapper předává českou základní URL a lokalizaci +provede sdílené `privacyPolicyUrl` (přes `localizedWebUrl`) z `update/ProjectLinks.kt`. +Kotlin testy kontrolují českou variantu i anglický fallback bez síťového přístupu. + +MVP podporuje host keys Ed25519 a ECDSA; přihlášení klíčem v UI používá pouze v aplikaci +vygenerovaný Ed25519 klíč. RSA host ani uživatelské klíče SwiftNIO SSH nepodporuje. +P3 při selhání vyjednávání zobrazuje obecnou CS/EN hlášku s informací o podporovaných +Ed25519/ECDSA host keys; chyba vyjednávání sama neurčuje, zda příčinou bylo RSA. +Nepřidává slabší fallback ani obejití kontroly host key. Offline licence a oznámení vycházejí z přesných pinovaných +verzí; přehled verzí, zdrojů a licencí zůstává v [zavislosti.md](zavislosti.md). + +Fyzický iPhone, entitlementy, distribuce a export compliance zůstávají mimo toto ověření; +checklist zařízení v §8 a §10 platí dál. Nezávislá revize před merge je nadále nutná. + + +## 12. Opravy nezávislé revize — R1 (implementace, čeká CI) + +R1 opravuje nálezy nad P0–P2 a přidává schválené cílené kontroly. Předchozí zelený P3 běh +nepotvrzuje tyto nové změny. Výsledek Swift sestavení, Kotlin/Native a simulátorových testů R1 +se doplní po CI; na Linuxu nelze Apple transporty ani Keychain ověřit. Přenosné Kotlin bridge +testy prošly v dočasné JVM konfiguraci (22 testů); nejde o Swift ani Kotlin/Native běh. + +- SSH: monotónní hodiny zahrnující spánek a životní cyklus na úrovni aplikace, překryv terminálu + při neaktivní scéně, úklid odpojených hesel až po úspěšném zápisu metadat a mazání profilů/klíčů. + Klíč odkazovaný jakýmkoli profilem nelze smazat. Chybějící metadata při čisté instalaci vedou + k vyčištění příslušné Keychain služby; chybu čtení nelze zaměnit za čistou instalaci. + Při startu s validními metadaty se přes `accountIDs` znovu porovnají reference a odstraní + osiřelé položky, takže neúspěšný dřívější úklid lze zopakovat. Při poškozených nebo nečitelných + metadatech se Keychain tímto postupem nemaže. Skutečné snímky přepínače aplikací s překryvem + terminálu zatím nebyly ověřeny (NOT RUN). +- Změněný host key zůstává bezpečnostním varováním i při chybě zápisu odmítnutého otisku. + UI doplňuje uložený/nabízený otisk a kontext dříve odmítnutého klíče. Import ukazuje + `user@[host]:port → user@[host]:port` ze sdíleného endpointu; změna cíle odpojí heslo, + ale záměrně zachová `keyRef`. Náhled a TOFU zůstávají povinné. +- LAN: kontrola vlastní sítě dostává aktuální Wi-Fi CIDR a konkrétní důvody potvrzení; + odepřené Local Network oprávnění má vlastní chybu. Vstupy se ořezávají a validují před startem, + zrušení čistí průběžný stav. Cílené testy doplňují souběžnost a rušení. Klasifikace PolicyDenied + má test čisté rozhodovací funkce; skutečný `currentPath.unsatisfiedReason` při odepření + oprávnění vyžaduje zařízení, nikoli jen tuto statickou kontrolu. +- LibreSpeed upload zmenšuje tělo pouze při HTTP 413, nejníže na 256 KiB; ostatní chyby + měření ukončí jako neúspěšné. Pozdní 413 souběžného staršího pokusu s větším tělem vede + k opakování s aktuální velikostí, i když ji mezitím jiný proud úspěšně přijal. Test NDT7 + řídí pořadí asynchronním signálem a zachovává potřebnou dobu přenosu. +- R1-11: RTT a rychlosti používají `formatted(.number.precision(.fractionLength(...)))`, + což je doloženo statickou kontrolou volání API; skutečné CS/EN vykreslení R1 čeká na CI. +- WoL připíná generaci rozhraní a IPv4/masky místo každé aktualizace cesty. Wi-Fi vybírá + podle typu v `availableInterfaces`, bez podmínky `path.status == .satisfied`, aby ji + nevyřadilo samotné chybějící internetové připojení. Broadcast se bez entitlementu v editoru nenabízí. + Unicast může po vypršení ARP cache uspaného cíle selhat i při úspěšném UDP send; + bez zařízení nelze účinnost probuzení doložit. Toto omezení nenahrazuje varování v UI. + +CI před kontrolou verze explicitně vybírá instalovaný Xcode 16.4 a Linux job navíc kontroluje +zakázané importy v `commonMain` stejně jako hlavní CI. R1 nemění `commonMain`, `commonTest`, +Android ani Gradle konfiguraci. Nezávislá kontrola diffu a zelené R1 CI zůstávají branou před předáním. + + +## 13. SSH profily v2 — implementace, čeká simulátorové CI + +SwiftUI používá stávající sdílené jádro přes `IosSshDomain`; `commonMain` ani Android se nemění. +Export vytváří pouze v2 (`netkit-ssh-profiles.json`), se stejným pořadím jako v seznamu a bez +lokálních ID, referencí, přihlašovacích údajů, klíčů a důvěry serverů. Před otevřením Files se +připraví a ověří neměnný snapshot. Duplicitní jména se vypíšou, překročení 256 KiB má vlastní +hlášku; při těchto chybách se exportní dialog neotevře. Chyby lze zavřít tlačítkem OK. + +Import přijímá v1, v2 a starý export telefonu podle [SSH §9](funkce/ssh.md#9-výměnný-formát-v2-starý-export-a-pořadí-profilů). +Náhled ukazuje změněná pole před → po: host, port, uživatel, ověření, startovací příkaz a keepalive. +Upozorňuje na změnu příkazu, odpojení hesla a chybějící klíč. Volba lokálního klíče přepočítá +náhled nových profilů; v1 se podle ní přepne mezi heslem a klíčem, v2/legacy zachová explicitní +typ ověření. Změna typu z PASSWORD odpojí heslo stejně jako změna cíle; nepoužívaný záznam +se smaže z Keychainu až po úspěšném uložení potvrzeného importu. Import nepřenáší klíče ani důvěru. + +Pořadí se mění šipkami nahoru/dolů, ukládá se do metadat a přežije restart. Krajní šipky a šipky +během operace či otevřeného náhledu jsou zakázané. VoiceOver popisky CS/EN obsahují jméno profilu. +Profil KEY bez existujícího přiřazeného klíče před connect i reconnect zobrazí výzvu k editoru, +aniž vznikne transport. Editor zachová KEY a vyžádá klíč; vytvoření nového Ed25519 klíče je +přístupné i s jinými klíči v seznamu. Klávesnici editoru lze zavřít tlačítkem Hotovo/Done. +Návrat zachová netajná rozepsaná pole, heslo se vymaže. +Smazaný profil nelze z výzvy znovu vytvořit. Reconnect používá přesný profil potvrzený v dialogu. + +Keyboard-interactive iOS MVP nepodporuje. Importovaný INTERACTIVE profil má v seznamu i při +pokusu o spojení CS/EN vysvětlení a doporučení upravit ověření na heslo nebo klíč. Editor žádá +výslovnou podporovanou volbu a tu předá při uložení; nepřevádí profil automaticky na heslo. +RSA, cizí privátní klíče, automatické startup příkazy a keepalive zůstávají mimo podporu MVP. + +**Ověření:** zelené [CI 41323807968](https://github.com/Losminek/netkit-ios/actions/runs/41323807968) +na `f3b5fad` potvrdilo Swift build, Kotlin/Native, **83 XCTest / 0 selhání**, **18/18 UI testů +CS/EN** a Linux regresi. Exportní UI test přes výslovný DEBUG launch argument zachytí skutečná +připravená data; ověří JSON v2, pořadí po restartu a nepřítomnost lokálních ID, referencí, +klíčů a důvěry. Systémový panel Files při tomto testu neotevírá. Běžný fileExporter se nemění. + +UI testy mají opt-in fixture harness jen v Debug simulátoru, izolovaný podle UUID od běžných +metadat a Keychain služby. Obsahuje pouze syntetická data a blokuje síťový transport. +Test náhledu obchází pouze systémový výběr fixture souboru; dále používá běžné dekódování, +plánování a potvrzení importu. Exportní DEBUG háček nahrazuje pouze systémový dialog, +nikoli přípravu nebo validaci exportu. Původní launch a SSH empty testy fixture harness nepoužívají. + +**Na iPhonu zbývá:** fyzický export přes Files (otevření, zápis i zrušení dialogu), import +a přenos v1/v2/legacy mezi platformami, VoiceOver/velikost písma, +uložené pořadí po ukončení procesu, výzva → editor → vytvoření klíče, ovládání s klávesnicí, +zamknutý Keychain a reconnect při změně sítě nebo VPN. Platí také checklist §8/§10; +simulátor nenahrazuje fyzické přijetí. Distribuce, Apple účet a podpis pro zařízení nejsou součástí. diff --git a/docs/plan.md b/docs/plan.md index 82583eb..547c8f8 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -52,6 +52,7 @@ Kritérium úspěchu M1: správce týden nepoužije žádnou ze čtyř původní | D25 | (2026-10-29) Před publikací **bezpečnostní revize** Codex Security (`gpt-6.1-sol`: threat model, hloubkový sken, validace) a **právní checklist** (GDPR, ePrivacy, Play, licence v binárce, CRA, identifikace podnikatele) s oficiálními zdroji. | Veřejné vydání pod jménem podnikatele; nález P1/P2 vydání blokuje. | | D26 | (2026-10-31) **Mění D23 (spouštěč):** build webu spouští **Deploy Hook Workers Builds** (`osobni-web`, větev `main`), URL v secretu `OSOBNI_WEB_DEPLOY_HOOK` (environment `release`). `publish.yml` po ověření release hook zavolá a až 15 min čeká na `/latest.json` s novou verzí; první publikovaný release hook přeskočí (web přepne `netkitReleased` vlastním PR). `repository_dispatch` a `WEB_DISPATCH_TOKEN` odstraněny, žádný Cloudflare token v GitHubu. | Web nemá deploy job ani token v GitHubu (interní záznam). Rotace = smazat hook, vytvořit nový, vyměnit secret. | | D27 | (2026-10-31) **Výjimka z D16:** 1.0.0 vychází před fyzickým testem M3/M4; správce ho provede nad vydaným release APK a nález řeší opravná verze 1.0.x. | Rozhodnutí správce; aplikace prošla emulátorem, CI a revizemi, release podpis je potřeba ověřit stejně jen na vydaném APK. | +| D28 | (2026-10-31) **Mění D12 (iOS):** iOS se začíná stavět. SwiftUI nad `:shared` (XCFramework), MVP včetně SSH (ping, porty, DNS, mDNS, info o Wi-Fi, speedtest, WoL, SSH), Android beze změny. Vývoj ve **veřejném** `Losminek/netkit-ios` (čistý export, jen syntetická data), protože standardní macOS runnery jsou ve veřejných repech zdarma; po auditu přenos do `netkit-dev` přes PR a archivace repa. Apple účet, TestFlight a test na zařízení mimo rozsah (rozhodne správce později). Zadání `prompty/28-ios-mvp.md`. | xtool (Linux) zamítnut: nepřeloží Kotlin `:shared`, Xcode SDK licencované jen pro Apple hardware, bez simulátoru (ověřeno 2026-10-31, `docs/ios.md` §7). Veřejné repo nejde zpětně „očistit“, proto čisté od začátku. | ## 3. Rozsah M1 diff --git a/docs/testovani.md b/docs/testovani.md index 92271d2..007f151 100644 --- a/docs/testovani.md +++ b/docs/testovani.md @@ -672,3 +672,39 @@ nebo veřejné resolvery (1.1.1.1, 8.8.8.8). Výsledek PASS / FAIL + poznámka. | M4-39 | WoL → ⋮ → Exportovat CSV (Wake On Lan), uložte do Stažených. | Dialog upozorní, co CSV nepřenáší; vznikne `wol-netkit.csv`. | NOT RUN | | M4-40 | Soubor z M4-39 naimportujte v aplikaci Wake On Lan (Mike Webb) do prázdného seznamu, pak jedno zařízení probuďte. | Aplikace import přijme; jména, MAC, broadcast, port, IP a skupiny sedí; paket zařízení probudí. | NOT RUN | | M4-41 | Přepněte jazyk telefonu na angličtinu, v NetKitu znovu exportujte CSV. | Skupiny z poznámek „Skupina: …“ zůstanou zachované (nespadnou do „NetKit“). | NOT RUN | + +## 14. SSH profily v2 — fyzický checklist (zadání 29) + +Pouze správce na fyzickém telefonu. Zapsat +verzi/commit APK, jazyk, písmo/zobrazení, výsledek a případný screenshot. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SSH2-01 | Exportovat PASSWORD, KEY a INTERACTIVE s odlišným keepalive a neškodným startovacím příkazem; soubor importovat do čisté testovací instalace. | V2, pořadí a přenosná pole shodná; žádné ID/reference/klíče/důvěra serverů. | NOT RUN | +| SSH2-02 | Importovat starý export telefonu bez referencí a metadat důvěry. | Přenosná pole zachována; nové lokální identity. | NOT RUN | +| SSH2-03 | Importovat aktualizaci všech šesti polí existujícího profilu. | Každé změněné pole před → po, příkaz zvýrazněný; pozice profilu zachována, změna cíle odpojí heslo. | NOT RUN | +| SSH2-04 | Šipkami přesunout profily, zkontrolovat kraje, restartovat aplikaci a exportovat. | Pořadí trvá a souhlasí s JSON; krajní šipky neaktivní, TalkBack oznámí směr i jméno. | NOT RUN | +| SSH2-05 | Importovat nový KEY bez výběru klíče; Připojit a potvrdit. | Výzva k výběru klíče s přechodem do editoru, žádná nová relace ani změna typu na heslo. | NOT RUN | +| SSH2-06 | Opakovat SSH2-05 s jiným existujícím klíčem v telefonu. | Editor i tak explicitně požaduje přiřazení; po výběru lze uložit. | NOT RUN | +| SSH2-07 | V editoru KEY bez klíčů klepnout Vytvořit klíč, vygenerovat Ed25519 a vrátit se. | Rozepsaná netajná pole zůstala; lze klíč vybrat a uložit; neukládá se rozepsané heslo. | NOT RUN | +| SSH2-08 | V Klíčích vygenerovat Ed25519, importovat v1 bez klíče, Upravit → Privátní klíč → vybrat klíč → Uložit. Opakovat import → generování a restart mezi kroky. | Klíč je v editoru viditelný i volitelný, uložení aktivní. Zapsat zvlášť release a DEV/debug APK; případný prázdný blok zachytit včetně vybraného ověřování, klávesnice a velikosti písma. | NOT RUN | +| SSH2-09 | V CS i EN a se zvětšeným písmem projít náhled, editor a šipky. | Čitelné texty, dostupné akce a posuv; nic se neztratí za klávesnicí. | NOT RUN | +| SSH2-10 | Reconnect relace, jejíž KEY profil už nemá existující přiřazený klíč (v izolované testovací instalaci). | Stejná výzva do editoru před transportem; původní relace/výpis se nepřepíše. | NOT RUN | + +### Doplnění R1 (revize zadání 29) + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SSH2-R1-01 | Export dvou profilů stejného jména, pak validních profilů s celkovým JSON nad 256 KiB. | Konkrétní CS/EN hláška (u duplicit jejich jména), SAF se neotevře a nevznikne 0 B soubor; běžné ukládání duplicit funguje. | NOT RUN | +| SSH2-R1-02 | Import v1 s existujícím klíčem; přepínat klíč / bez klíče. | Náhled nového profilu přepíná KEY/PASSWORD stejně jako následné uložení. | NOT RUN | +| SSH2-R1-03 | Importem změnit PASSWORD → KEY/INTERACTIVE a KEY → PASSWORD/INTERACTIVE. | Nepoužívaná reference odstraněna, opuštěné heslo smazáno; při KEY bez přiřazení varování. Samotná změna cíle zachová keyRef. | NOT RUN | +| SSH2-R1-04 | KEY bez přiřazení s jiným klíčem v seznamu; TalkBack nad správou více profilů. | Vytvořit klíč dostupné; Upravit/Smazat oznamují i jméno profilu, monogram jako před změnou v2. | NOT RUN | +| SSH2-R1-05 | Reconnect a souběžná editace/smazání profilu v izolovaném testu. | Použije se potvrzený cíl/příkaz; smazání vyvolá jen chybu, nenabídne editor obnovující profil. | NOT RUN | + +### Doplnění malého kola P3 (po merge zadání 29) + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SSH2-P3-01 | Exportovat profily, během SAF ukončit proces aplikace a dokončit výběr cíle. | Export vznikne z aktuálního úložiště i bez připraveného snapshotu. Při duplicitách nebo překročení 256 KiB konkrétní hláška, žádné UNKNOWN; validace před zápisem. | NOT RUN | +| SSH2-P3-02 | Vyvolat chybu exportu / reconnectu smazaného profilu, klepnout OK. | Hláška i její OK zmizí. | NOT RUN | +| SSH2-P3-03 | V CS i EN importovat změnu PASSWORD → KEY/INTERACTIVE s uloženým heslem. | Varování říká jen, že heslo bude odpojeno a smazáno; neslibuje jeho opětovné zadání. | NOT RUN | diff --git a/docs/zavislosti.md b/docs/zavislosti.md index 0ec75bf..45fb4a5 100644 --- a/docs/zavislosti.md +++ b/docs/zavislosti.md @@ -488,3 +488,119 @@ licence; nenahrazují kontrolu licencí v konkrétním release APK. nemají aplikační velikostní strop příchozí datové zprávy před callbackem. [`RealWebSocket.MAX_QUEUE_SIZE`](https://github.com/square/okhttp/blob/parent-5.3.2/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/ws/RealWebSocket.kt#L411-L427) omezuje odchozí frontu. Dopad F4 a přesné rozlišení v reportu 30 (interní záznam). + +## 6. iOS kostra a CI (P0, 2026-10-31) + +P0 nepřidává přímou knihovnu ani Swift Package. SwiftUI, Foundation a XCTest jsou součástí +Apple SDK používaného jen na macOS runneru. Stávající KMP závislosti nově vyžadují Apple varianty; +Android/JVM verze a katalog se nemění. Licence knihoven byly ověřeny 2026-10-31: + +| Komponenta | Verze | Licence | Oficiální zdroj / účel | +|---|---|---|---| +| Kotlin/Native, stdlib a kotlin-test | 2.2.20 | Apache-2.0, soupis přibalených částí v licenci Kotlinu | [Kotlin licence](https://github.com/JetBrains/kotlin/blob/v2.2.20/license/README.md); existující Kotlin plugin, nově native targety | +| kotlinx-coroutines-core, kotlinx-coroutines-test (iosarm64, iossimulatorarm64) | 1.10.2 | Apache-2.0 | [LICENSE](https://github.com/Kotlin/kotlinx.coroutines/blob/1.10.2/LICENSE.txt), [Maven core](https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-coroutines-core-iosarm64/1.10.2/); existující přímé závislosti | +| kotlinx-serialization-core, kotlinx-serialization-json (iosarm64, iossimulatorarm64) | 1.9.0 | Apache-2.0 | [LICENSE](https://github.com/Kotlin/kotlinx.serialization/blob/v1.9.0/LICENSE.txt), [Maven JSON](https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-serialization-json-iosarm64/1.9.0/); existující JSON knihovna | +| atomicfu, atomicfu-iosarm64, atomicfu-iossimulatorarm64 včetně cinterop | 0.26.1 | Apache-2.0 | [LICENSE](https://github.com/Kotlin/kotlinx-atomicfu/blob/0.26.1/LICENSE.txt), [POM](https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/atomicfu/0.26.1/atomicfu-0.26.1.pom); nová native tranzitivní závislost coroutines | + +SHA-256 Apple artefaktů a jejich metadat jsou doplněny do `gradle/verification-metadata.xml`. +Získání z oficiálního Maven Central bylo porovnáno s publikovanými SHA-1 sidecary a u souborů +odkazovaných z Gradle `.module` také s jejich SHA-256. Toto ověření stejného zdroje není nezávislý +podpis vydavatele. Přísné ověřování zůstává zapnuté; úplnost grafu pro macOS musí potvrdit CI. +Swift `Package.resolved` nevzniká, protože projekt nemá Swift balíčky. + +### Toolchain CI + +Ověřeno v oficiální dokumentaci 2026-10-31; nejde o výsledek spuštěného CI: + +| Součást | Zvolená verze | Zdroj | +|---|---|---| +| Standardní ARM runner | `macos-15`; dokumentovaný image `20261028.0489.1`, macOS 15.8.2 | [runner image](https://github.com/actions/runner-images/blob/main/images/macos/macos-15-arm64-Readme.md), [mapování labelů](https://docs.github.com/en/actions/reference/runners/github-hosted-runners) | +| Xcode / iOS simulátor | 16.4, build 16F6 / iOS 18.5 | stejný runner image; [kompatibilita Kotlin 2.2.20](https://kotlinlang.org/docs/multiplatform/multiplatform-compatibility-guide.html) | +| Linux / Java | `ubuntu-24.04` / Temurin 21 | stejné jako stávající release workflow | +| GitHub Actions | checkout 7.0.1, setup-java 6.0.1, upload-artifact 7.0.2 | plné SHA převzaté beze změny z [release.yml](../.github/workflows/release.yml) | + +Workflow ověřuje architekturu a přesnou výchozí verzi Xcode; při změně image selže, nepřejde tiše +na jinou verzi. Image jako celek není neměnně připnutý. Dokumentace runneru uvádí potřebný Android +SDK 35 a build-tools 35.0.0; workflow neinstaluje SDK komponenty. Kotlin/Native toolchain se získává +standardním Gradle mechanismem na macOS runneru, nikoli na lokálním Linuxu. +Runner provisioning má [MIT licenci](https://github.com/actions/runner-images/blob/main/LICENSE); +ta se nevztahuje na Apple SDK, pro které platí +[Apple SDK agreement](https://www.apple.com/legal/sla/docs/xcode.pdf). SDK se nepřibaluje do repa. +Distribuce aplikace ani posouzení SSH kryptografie nejsou součástí P0. + +## 7. iOS síťové nástroje (P1, 2026-10-31) + +Žádná nová knihovna, Swift Package, verze Gradle závislosti ani změna verification metadat. +Používají se stávající coroutines/serialization a sdílená doména. SwiftUI, Network.framework, +Foundation/URLSession, NetworkExtension, Security (náhodné bajty) a Darwin jsou systémová API +SDK Xcode 16.4 / iOS 18.5 z §6; SDK se nepřibaluje. Swift `Package.resolved` nadále není potřeba. + +Network.framework obsluhuje TCP, DNS UDP, Bonjour a WoL. POSIX datagramový ICMP je vlastní +implementace nad veřejným API, bez přibalení či kopírování cizího síťového kódu. Speedtest používá +URLSession HTTPS/WSS a existující sdílené parsery; neposkytuje ani nevyžaduje placenou službu. +Runner, Xcode, SHA akcí a Linux build se kvůli P1 nemění. Skutečný stav ověření je v +[ios.md §9](ios.md#9-síťové-nástroje--p1-ověřeno-v-simulátoru). + + +## 8. iOS SSH (P2, ověřeno 2026-10-31) + +SwiftNIO SSH je oficiální SSH protokolová knihovna; aplikace doplňuje životní cyklus, TOFU, +Keychain a PTY. Přímé i tranzitivní balíčky mají v Xcode `exactVersion`; commitnutý +`iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved` obsahuje +verze a revize ze stejných tagů. CI vyžaduje pinované řešení bez automatické aktualizace. +SwiftPM/Xcode resolve na Linuxu neproběhl; kompatibilitu grafu a sestavení potvrzuje macOS CI. + +| Balíček | Verze | Licence | Zdroj na přesném tagu | Datum ověření | +|---|---|---|---|---| +| `swift-nio-ssh` | 0.15.1 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-nio-ssh/blob/0.15.1/LICENSE.txt), [Package.swift](https://github.com/apple/swift-nio-ssh/blob/0.15.1/Package.swift) | 2026-10-31 | +| `swift-nio` | 2.84.0 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-nio/blob/2.84.0/LICENSE.txt), [Package.swift](https://github.com/apple/swift-nio/blob/2.84.0/Package.swift) | 2026-10-31 | +| `swift-crypto` | 3.12.3 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-crypto/blob/3.12.3/LICENSE.txt), [Package.swift](https://github.com/apple/swift-crypto/blob/3.12.3/Package.swift) | 2026-10-31 | +| `swift-atomics` | 1.3.0 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-atomics/blob/1.3.0/LICENSE.txt), [Package.swift](https://github.com/apple/swift-atomics/blob/1.3.0/Package.swift) | 2026-10-31 | +| `swift-collections` | 1.2.0 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-collections/blob/1.2.0/LICENSE.txt), [Package.swift](https://github.com/apple/swift-collections/blob/1.2.0/Package.swift) | 2026-10-31 | +| `swift-system` | 1.5.0 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-system/blob/1.5.0/LICENSE.txt), [Package.swift](https://github.com/apple/swift-system/blob/1.5.0/Package.swift) | 2026-10-31 | +| `swift-asn1` | 1.4.0 | Apache-2.0 | [LICENSE.txt](https://github.com/apple/swift-asn1/blob/1.4.0/LICENSE.txt), [Package.swift](https://github.com/apple/swift-asn1/blob/1.4.0/Package.swift) | 2026-10-31 | + +Graf: NIOSSH → NIO, Crypto, Atomics; NIO → Atomics, Collections, System; Crypto → ASN1. +ASN1 se řeší z manifestu Crypto i přesto, že iOS aplikace používá pouze produkt `Crypto`, +nikoli `_CryptoExtras`. `Crypto` na Apple platformě v této konfiguraci exportuje systémový +CryptoKit; nevynucujeme BoringSSL backend. NIO obsahuje také MIT llhttp, ale produkt NIOHTTP1 +ani jeho CNIOLLHTTP target tato aplikace nepoužívá. Žádný kód závislostí se nekopíruje do aplikace. + +NIOSSH 0.15.1 vyžaduje Swift tools 6.1 (Xcode 16.4); ostatní manifesty nejvýše 5.10. +Použitelná sada algoritmů je bezpečná podmnožina sdíleného allowlistu: Ed25519 a ECDSA +P-256/P-384/P-521, ECDH těchto křivek a Curve25519, AES-128/256-GCM. Pořadí preference KEX +se liší od Androidu. RSA autentizace a RSA host keys nejsou v této knihovně podporovány; +žádné RSA/SHA-1, DSA ani jiný slabý fallback se nepřidává. PTY a změna velikosti jsou +součástí NIOSSH channel requests; vlastní vykreslení používá sdílený TerminalBuffer. + +Citadel 0.12.1 nebyl přidán: kořenová MIT licence nepokrývá povinný +[CCitadelBcrypt/bcrypt.c](https://github.com/orlandos-nl/Citadel/blob/0.12.1/Sources/CCitadelBcrypt/bcrypt.c) +pod ISC (zde není povolená výjimka). Jeho +[RSA.swift](https://github.com/orlandos-nl/Citadel/blob/0.12.1/Sources/Citadel/Algorithms/RSA.swift) +navíc používá podpis SSH-RSA/SHA-1, který společná politika odmítá. Nejde o kompromis +s bezpečností výměnou za širší kompatibilitu. Stav ověření aplikace je v [ios.md](ios.md). + +Licence Atomics, Collections a System zahrnují Runtime Library Exception k Apache-2.0. +NIO NOTICE dále uvádí MIT cpp_magic.h a BSD-3-Clause části FreeBSD; tyto permisivní +licence byly zkontrolovány v tagu 2.84.0 spolu s [NOTICE](https://github.com/apple/swift-nio/blob/2.84.0/NOTICE.txt). + + +## 9. Offline licence v O aplikaci (P3, ověřeno 2026-11-01) + +P3 nepřidává závislosti ani nemění verze. Offline atribuce pokrývají stejných sedm Swift +balíčků z §8 a Kotlin 2.2.20, coroutines 1.10.2, serialization 1.9.0 a atomicfu 0.26.1 z §6. +Licenční texty a oznámení byly znovu načteny přes oficiální GitHub API z přesných tagů +uvedených v těchto tabulkách dne 2026-11-01; nejde o texty pohyblivé větve main. + +Offline resource zahrnuje Apache-2.0 včetně Runtime Library Exception tam, kde ji balíček +uvádí, a příslušná BSD/MIT oznámení. Doplňuje také atribuce částí již používaného Kotlin +runtime: Boost Software License 1.0 a Unicode notice; nezavádí tím novou závislost. +Původ těchto částí dokládá [Kotlin license README na v2.2.20](https://github.com/JetBrains/kotlin/blob/v2.2.20/license/README.md) +(včetně runtime `runtime/src/main/cpp/Utils.cpp`) a [Kotlin/Native third-party licence na v2.2.20](https://github.com/JetBrains/kotlin/tree/v2.2.20/kotlin-native/licenses/third_party): +Unicode, bounded MPMC queue, Apache Harmony a jeho NOTICE, libbacktrace. +Licenční hlavička [runtime utf8.h](https://github.com/JetBrains/kotlin/blob/v2.2.20/kotlin-native/runtime/src/main/cpp/utf8.h) +dokládá Boost licenci této další části. Uvedení těchto textů je atribuce stávajícího runtime, +nikoli rozšíření povolených licencí pro nové knihovny. + +Offline zobrazení nevyžaduje síťový přístup. Stav implementace a dosud neprovedeného P3 +simulátorového ověření je v [ios.md §11](ios.md#11-dokončení--p3-ověřeno-2026-11-01). diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index eb6e67c..239699f 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -2838,6 +2838,9 @@ + + + @@ -2933,6 +2936,9 @@ + + + @@ -3087,6 +3093,12 @@ + + + + + + @@ -3150,6 +3162,12 @@ + + + + + + @@ -3184,6 +3202,12 @@ + + + + + + @@ -3208,6 +3232,12 @@ + + + + + + @@ -3365,5 +3395,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iosApp/NetKit.xcodeproj/project.pbxproj b/iosApp/NetKit.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b076d93 --- /dev/null +++ b/iosApp/NetKit.xcodeproj/project.pbxproj @@ -0,0 +1,669 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = {}; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 000000000000000000000C01 /* OpenSourceLicenses.txt in Resources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000C00 /* OpenSourceLicenses.txt */; }; + 000000000000000000000001 /* NetKitApp.swift in Sources */ = { + isa = PBXBuildFile; + fileRef = 000000000000000000000015 /* NetKitApp.swift */; + }; + 000000000000000000000002 /* Localizable.xcstrings in Resources */ = { + isa = PBXBuildFile; + fileRef = 000000000000000000000016 /* Localizable.xcstrings */; + }; + 000000000000000000000003 /* PrivacyInfo.xcprivacy in Resources */ = { + isa = PBXBuildFile; + fileRef = 000000000000000000000017 /* PrivacyInfo.xcprivacy */; + }; + 000000000000000000000004 /* NetKitTests.swift in Sources */ = { + isa = PBXBuildFile; + fileRef = 000000000000000000000018 /* NetKitTests.swift */; + }; + 000000000000000000000005 /* NetKitUITests.swift in Sources */ = { + isa = PBXBuildFile; + fileRef = 000000000000000000000019 /* NetKitUITests.swift */; + }; + 000000000000000000000200 /* LanView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000100 /* LanView.swift */; }; + 000000000000000000000201 /* PortScan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000101 /* PortScan.swift */; }; + 000000000000000000000202 /* IcmpPing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000102 /* IcmpPing.swift */; }; + 000000000000000000000203 /* WifiView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000103 /* WifiView.swift */; }; + 000000000000000000000204 /* SpeedView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000104 /* SpeedView.swift */; }; + 000000000000000000000205 /* WolPlatform.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000105 /* WolPlatform.swift */; }; + 000000000000000000000206 /* WolView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000106 /* WolView.swift */; }; + 000000000000000000000207 /* WolPersistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000107 /* WolPersistence.swift */; }; + 000000000000000000000307 /* LanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000108 /* LanTests.swift */; }; + 000000000000000000000308 /* SpeedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000109 /* SpeedTests.swift */; }; + 000000000000000000000403 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000400 /* InfoPlist.strings */; }; + 000000000000000000000700 /* NIOSSH in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000600 /* NIOSSH */; }; + 000000000000000000000701 /* NIOCore in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000601 /* NIOCore */; }; + 000000000000000000000702 /* NIOPosix in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000602 /* NIOPosix */; }; + 000000000000000000000703 /* Crypto in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000603 /* Crypto */; }; + 000000000000000000000704 /* NIOFoundationCompat in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000604 /* NIOFoundationCompat */; }; + 000000000000000000000710 /* NIOSSH in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000610 /* NIOSSH */; }; + 000000000000000000000711 /* NIOCore in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000611 /* NIOCore */; }; + 000000000000000000000712 /* NIOPosix in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000612 /* NIOPosix */; }; + 000000000000000000000713 /* Crypto in Frameworks */ = {isa = PBXBuildFile; productRef = 000000000000000000000613 /* Crypto */; }; + 000000000000000000000900 /* KeychainSecrets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000800 /* KeychainSecrets.swift */; }; + 000000000000000000000901 /* SshMetadataStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000801 /* SshMetadataStore.swift */; }; + 000000000000000000000902 /* SshHostKeyValidator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000802 /* SshHostKeyValidator.swift */; }; + 000000000000000000000903 /* SshTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000803 /* SshTransport.swift */; }; + 000000000000000000000904 /* SshViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000804 /* SshViewModel.swift */; }; + 000000000000000000000905 /* SshKeyboard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000805 /* SshKeyboard.swift */; }; + 000000000000000000000906 /* SshView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000806 /* SshView.swift */; }; + 000000000000000000000A04 /* KeychainSecretsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000807 /* KeychainSecretsTests.swift */; }; + 000000000000000000000A05 /* SshMetadataStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000808 /* SshMetadataStoreTests.swift */; }; + 000000000000000000000A06 /* LocalSshServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000809 /* LocalSshServer.swift */; }; + 000000000000000000000A07 /* SshIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00000000000000000000080A /* SshIntegrationTests.swift */; }; + 00000000000000000000090B /* SshTerminalRows.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00000000000000000000080B /* SshTerminalRows.swift */; }; + 000000000000000000000A0C /* SshTerminalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00000000000000000000080C /* SshTerminalTests.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 00000000000000000000002F = { + isa = PBXContainerItemProxy; + containerPortal = 000000000000000000000030 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 00000000000000000000002C /* NetKit */; + remoteInfo = NetKit; + }; + 000000000000000000000B01 /* NetKitTests host proxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 000000000000000000000030 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 00000000000000000000002C /* NetKit */; + remoteInfo = NetKit; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 000000000000000000000C00 /* OpenSourceLicenses.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = OpenSourceLicenses.txt; sourceTree = ""; }; + 000000000000000000000015 /* NetKitApp.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = NetKitApp.swift; + sourceTree = ""; + }; + 000000000000000000000016 /* Localizable.xcstrings */ = { + isa = PBXFileReference; + lastKnownFileType = text.json.xcstrings; + path = Localizable.xcstrings; + sourceTree = ""; + }; + 000000000000000000000017 /* PrivacyInfo.xcprivacy */ = { + isa = PBXFileReference; + lastKnownFileType = text.xml; + path = PrivacyInfo.xcprivacy; + sourceTree = ""; + }; + 000000000000000000000018 /* NetKitTests.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = NetKitTests.swift; + sourceTree = ""; + }; + 000000000000000000000019 /* NetKitUITests.swift */ = { + isa = PBXFileReference; + lastKnownFileType = sourcecode.swift; + path = NetKitUITests.swift; + sourceTree = ""; + }; + 000000000000000000000023 /* NetKit.app */ = { + isa = PBXFileReference; + explicitFileType = wrapper.application; + path = NetKit.app; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 000000000000000000000024 /* NetKitTests.xctest */ = { + isa = PBXFileReference; + explicitFileType = wrapper.cfbundle; + path = NetKitTests.xctest; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 000000000000000000000025 /* NetKitUITests.xctest */ = { + isa = PBXFileReference; + explicitFileType = wrapper.cfbundle; + path = NetKitUITests.xctest; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 000000000000000000000100 /* LanView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanView.swift; sourceTree = ""; }; + 000000000000000000000101 /* PortScan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PortScan.swift; sourceTree = ""; }; + 000000000000000000000102 /* IcmpPing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IcmpPing.swift; sourceTree = ""; }; + 000000000000000000000103 /* WifiView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WifiView.swift; sourceTree = ""; }; + 000000000000000000000104 /* SpeedView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpeedView.swift; sourceTree = ""; }; + 000000000000000000000105 /* WolPlatform.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WolPlatform.swift; sourceTree = ""; }; + 000000000000000000000106 /* WolView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WolView.swift; sourceTree = ""; }; + 000000000000000000000107 /* WolPersistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WolPersistence.swift; sourceTree = ""; }; + 000000000000000000000108 /* LanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LanTests.swift; sourceTree = ""; }; + 000000000000000000000109 /* SpeedTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpeedTests.swift; sourceTree = ""; }; + 000000000000000000000401 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + 000000000000000000000402 /* cs */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = cs; path = cs.lproj/InfoPlist.strings; sourceTree = ""; }; + 000000000000000000000800 /* KeychainSecrets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainSecrets.swift; sourceTree = ""; }; + 000000000000000000000801 /* SshMetadataStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshMetadataStore.swift; sourceTree = ""; }; + 000000000000000000000802 /* SshHostKeyValidator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshHostKeyValidator.swift; sourceTree = ""; }; + 000000000000000000000803 /* SshTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshTransport.swift; sourceTree = ""; }; + 000000000000000000000804 /* SshViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshViewModel.swift; sourceTree = ""; }; + 000000000000000000000805 /* SshKeyboard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshKeyboard.swift; sourceTree = ""; }; + 000000000000000000000806 /* SshView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshView.swift; sourceTree = ""; }; + 000000000000000000000807 /* KeychainSecretsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainSecretsTests.swift; sourceTree = ""; }; + 000000000000000000000808 /* SshMetadataStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshMetadataStoreTests.swift; sourceTree = ""; }; + 000000000000000000000809 /* LocalSshServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalSshServer.swift; sourceTree = ""; }; + 00000000000000000000080A /* SshIntegrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshIntegrationTests.swift; sourceTree = ""; }; + 00000000000000000000080B /* SshTerminalRows.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshTerminalRows.swift; sourceTree = ""; }; + 00000000000000000000080C /* SshTerminalTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SshTerminalTests.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 000000000000000000000020 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000700 /* NIOSSH in Frameworks */, + 000000000000000000000701 /* NIOCore in Frameworks */, + 000000000000000000000702 /* NIOPosix in Frameworks */, + 000000000000000000000703 /* Crypto in Frameworks */, + 000000000000000000000704 /* NIOFoundationCompat in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000021 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000710 /* NIOSSH in Frameworks */, + 000000000000000000000711 /* NIOCore in Frameworks */, + 000000000000000000000712 /* NIOPosix in Frameworks */, + 000000000000000000000713 /* Crypto in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000022 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 00000000000000000000001B = { + isa = PBXGroup; + children = ( + 00000000000000000000001C /* NetKit */, + 00000000000000000000001D /* NetKitTests */, + 00000000000000000000001E /* NetKitUITests */, + 00000000000000000000001F /* Products */ + ); + sourceTree = ""; + }; + 00000000000000000000001C /* NetKit */ = { + isa = PBXGroup; + children = ( + 00000000000000000000080B /* SshTerminalRows.swift */, + 000000000000000000000800 /* KeychainSecrets.swift */, + 000000000000000000000801 /* SshMetadataStore.swift */, + 000000000000000000000802 /* SshHostKeyValidator.swift */, + 000000000000000000000803 /* SshTransport.swift */, + 000000000000000000000804 /* SshViewModel.swift */, + 000000000000000000000805 /* SshKeyboard.swift */, + 000000000000000000000806 /* SshView.swift */, + 000000000000000000000015 /* NetKitApp.swift */, + 000000000000000000000C00 /* OpenSourceLicenses.txt */, + 000000000000000000000016 /* Localizable.xcstrings */, + 000000000000000000000017 /* PrivacyInfo.xcprivacy */, + 000000000000000000000100 /* LanView.swift */, + 000000000000000000000101 /* PortScan.swift */, + 000000000000000000000102 /* IcmpPing.swift */, + 000000000000000000000103 /* WifiView.swift */, + 000000000000000000000104 /* SpeedView.swift */, + 000000000000000000000105 /* WolPlatform.swift */, + 000000000000000000000106 /* WolView.swift */, + 000000000000000000000107 /* WolPersistence.swift */, + 000000000000000000000400 /* InfoPlist.strings */ + ); + path = NetKit; + sourceTree = ""; + }; + 00000000000000000000001D /* NetKitTests */ = { + isa = PBXGroup; + children = ( + 000000000000000000000807 /* KeychainSecretsTests.swift */, + 000000000000000000000808 /* SshMetadataStoreTests.swift */, + 000000000000000000000809 /* LocalSshServer.swift */, + 00000000000000000000080A /* SshIntegrationTests.swift */, + 00000000000000000000080C /* SshTerminalTests.swift */, + 000000000000000000000018 /* NetKitTests.swift */, + 000000000000000000000108 /* LanTests.swift */, + 000000000000000000000109 /* SpeedTests.swift */ + ); + path = NetKitTests; + sourceTree = ""; + }; + 00000000000000000000001E /* NetKitUITests */ = { + isa = PBXGroup; + children = ( + 000000000000000000000019 /* NetKitUITests.swift */ + ); + path = NetKitUITests; + sourceTree = ""; + }; + 00000000000000000000001F /* Products */ = { + isa = PBXGroup; + children = ( + 000000000000000000000023 /* NetKit.app */, + 000000000000000000000024 /* NetKitTests.xctest */, + 000000000000000000000025 /* NetKitUITests.xctest */ + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 00000000000000000000002C /* NetKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = 000000000000000000000010; + buildPhases = ( + 000000000000000000000029 /* Sources */, + 000000000000000000000020 /* Frameworks */, + 000000000000000000000026 /* Resources */ + ); + buildRules = ( + ); + dependencies = ( + ); + name = NetKit; + packageProductDependencies = ( + 000000000000000000000600 /* NIOSSH */, + 000000000000000000000601 /* NIOCore */, + 000000000000000000000602 /* NIOPosix */, + 000000000000000000000603 /* Crypto */, + 000000000000000000000604 /* NIOFoundationCompat */, + ); + productName = NetKit; + productReference = 000000000000000000000023 /* NetKit.app */; + productType = "com.apple.product-type.application"; + }; + 00000000000000000000002D /* NetKitTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 000000000000000000000011; + buildPhases = ( + 00000000000000000000002A /* Sources */, + 000000000000000000000021 /* Frameworks */, + 000000000000000000000027 /* Resources */ + ); + buildRules = ( + ); + dependencies = ( + 000000000000000000000B02 /* NetKitTests host dependency */, + ); + name = NetKitTests; + packageProductDependencies = ( + 000000000000000000000610 /* NIOSSH */, + 000000000000000000000611 /* NIOCore */, + 000000000000000000000612 /* NIOPosix */, + 000000000000000000000613 /* Crypto */, + ); + productName = NetKitTests; + productReference = 000000000000000000000024 /* NetKitTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 00000000000000000000002E /* NetKitUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 000000000000000000000012; + buildPhases = ( + 00000000000000000000002B /* Sources */, + 000000000000000000000022 /* Frameworks */, + 000000000000000000000028 /* Resources */ + ); + buildRules = ( + ); + dependencies = ( + 000000000000000000000014 + ); + name = NetKitUITests; + productName = NetKitUITests; + productReference = 000000000000000000000025 /* NetKitUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 000000000000000000000030 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1600; + TargetAttributes = { + 00000000000000000000002C /* NetKit */ = { + CreatedOnToolsVersion = 16.0; + }; + 00000000000000000000002D /* NetKitTests */ = { + CreatedOnToolsVersion = 16.0; + TestTargetID = 00000000000000000000002C /* NetKit */; + }; + 00000000000000000000002E /* NetKitUITests */ = { + CreatedOnToolsVersion = 16.0; + TestTargetID = 00000000000000000000002C /* NetKit */; + }; + }; + }; + buildConfigurationList = 00000000000000000000000F; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + knownRegions = ( + en, + cs, + Base + ); + mainGroup = 00000000000000000000001B; + productRefGroup = 00000000000000000000001F /* Products */; + packageReferences = ( + 000000000000000000000500 /* swift-nio-ssh */, + 000000000000000000000501 /* swift-nio */, + 000000000000000000000502 /* swift-crypto */, + 000000000000000000000503 /* swift-atomics */, + 000000000000000000000504 /* swift-collections */, + 000000000000000000000505 /* swift-system */, + 000000000000000000000506 /* swift-asn1 */, + ); + projectDirPath = ""; + projectRoot = ""; + targets = ( + 00000000000000000000002C /* NetKit */, + 00000000000000000000002D /* NetKitTests */, + 00000000000000000000002E /* NetKitUITests */ + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 000000000000000000000026 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000002 /* Localizable.xcstrings in Resources */, + 000000000000000000000003 /* PrivacyInfo.xcprivacy in Resources */, + 000000000000000000000C01 /* OpenSourceLicenses.txt in Resources */, + 000000000000000000000403 /* InfoPlist.strings in Resources */ + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000027 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000028 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 000000000000000000000029 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 00000000000000000000090B /* SshTerminalRows.swift in Sources */, + 000000000000000000000900 /* KeychainSecrets.swift in Sources */, + 000000000000000000000901 /* SshMetadataStore.swift in Sources */, + 000000000000000000000902 /* SshHostKeyValidator.swift in Sources */, + 000000000000000000000903 /* SshTransport.swift in Sources */, + 000000000000000000000904 /* SshViewModel.swift in Sources */, + 000000000000000000000905 /* SshKeyboard.swift in Sources */, + 000000000000000000000906 /* SshView.swift in Sources */, + 000000000000000000000001 /* NetKitApp.swift in Sources */, + 000000000000000000000200 /* LanView.swift in Sources */, + 000000000000000000000201 /* PortScan.swift in Sources */, + 000000000000000000000202 /* IcmpPing.swift in Sources */, + 000000000000000000000203 /* WifiView.swift in Sources */, + 000000000000000000000204 /* SpeedView.swift in Sources */, + 000000000000000000000205 /* WolPlatform.swift in Sources */, + 000000000000000000000206 /* WolView.swift in Sources */, + 000000000000000000000207 /* WolPersistence.swift in Sources */ + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 00000000000000000000002A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000A0C /* SshTerminalTests.swift in Sources */, + 000000000000000000000A04 /* KeychainSecretsTests.swift in Sources */, + 000000000000000000000A05 /* SshMetadataStoreTests.swift in Sources */, + 000000000000000000000A06 /* LocalSshServer.swift in Sources */, + 000000000000000000000A07 /* SshIntegrationTests.swift in Sources */, + 000000000000000000000004 /* NetKitTests.swift in Sources */, + 000000000000000000000307 /* LanTests.swift in Sources */, + 000000000000000000000308 /* SpeedTests.swift in Sources */ + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 00000000000000000000002B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000005 /* NetKitUITests.swift in Sources */ + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 000000000000000000000014 = { + isa = PBXTargetDependency; + target = 00000000000000000000002C /* NetKit */; + targetProxy = 00000000000000000000002F; + }; + 000000000000000000000B02 /* NetKitTests host dependency */ = { + isa = PBXTargetDependency; + target = 00000000000000000000002C /* NetKit */; + targetProxy = 000000000000000000000B01 /* NetKitTests host proxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 000000000000000000000400 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = (000000000000000000000401 /* en */, 000000000000000000000402 /* cs */); + name = InfoPlist.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCSwiftPackageProductDependency section */ + 000000000000000000000600 /* NIOSSH */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000500 /* swift-nio-ssh */; productName = NIOSSH; }; + 000000000000000000000601 /* NIOCore */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000501 /* swift-nio */; productName = NIOCore; }; + 000000000000000000000602 /* NIOPosix */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000501 /* swift-nio */; productName = NIOPosix; }; + 000000000000000000000603 /* Crypto */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000502 /* swift-crypto */; productName = Crypto; }; + 000000000000000000000604 /* NIOFoundationCompat */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000501 /* swift-nio */; productName = NIOFoundationCompat; }; + 000000000000000000000610 /* NIOSSH */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000500 /* swift-nio-ssh */; productName = NIOSSH; }; + 000000000000000000000611 /* NIOCore */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000501 /* swift-nio */; productName = NIOCore; }; + 000000000000000000000612 /* NIOPosix */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000501 /* swift-nio */; productName = NIOPosix; }; + 000000000000000000000613 /* Crypto */ = {isa = XCSwiftPackageProductDependency; package = 000000000000000000000502 /* swift-crypto */; productName = Crypto; }; +/* End XCSwiftPackageProductDependency section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 000000000000000000000500 /* swift-nio-ssh */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-nio-ssh.git"; requirement = {kind = exactVersion; version = 0.15.1; }; }; + 000000000000000000000501 /* swift-nio */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-nio.git"; requirement = {kind = exactVersion; version = 2.84.0; }; }; + 000000000000000000000502 /* swift-crypto */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-crypto.git"; requirement = {kind = exactVersion; version = 3.12.3; }; }; + 000000000000000000000503 /* swift-atomics */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-atomics.git"; requirement = {kind = exactVersion; version = 1.3.0; }; }; + 000000000000000000000504 /* swift-collections */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-collections.git"; requirement = {kind = exactVersion; version = 1.2.0; }; }; + 000000000000000000000505 /* swift-system */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-system.git"; requirement = {kind = exactVersion; version = 1.5.0; }; }; + 000000000000000000000506 /* swift-asn1 */ = {isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/apple/swift-asn1.git"; requirement = {kind = exactVersion; version = 1.4.0; }; }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCBuildConfiguration section */ + 000000000000000000000007 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MARKETING_VERSION = 0.1.0; + SDKROOT = iphoneos; + SWIFT_VERSION = 5.0; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) DEBUG"; + }; + name = Debug; + }; + 000000000000000000000008 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ENABLE_MODULES = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MARKETING_VERSION = 0.1.0; + SDKROOT = iphoneos; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 000000000000000000000009 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ENABLE_TESTABILITY = YES; + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; + "FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]" = "$(PROJECT_DIR)/../shared/build/bin/iosSimulatorArm64/debugFramework"; + "FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]" = "$(PROJECT_DIR)/../shared/build/bin/iosArm64/debugFramework"; + OTHER_LDFLAGS = ( + "$(inherited)", + "-framework", + NetKitShared + ); + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = NetKit/Info.plist; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + PRODUCT_BUNDLE_IDENTIFIER = cz.netkit.ios; + PRODUCT_NAME = "$(TARGET_NAME)"; + CURRENT_PROJECT_VERSION = 1; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 00000000000000000000000A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; + "FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]" = "$(PROJECT_DIR)/../shared/build/bin/iosSimulatorArm64/releaseFramework"; + "FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]" = "$(PROJECT_DIR)/../shared/build/bin/iosArm64/releaseFramework"; + OTHER_LDFLAGS = ( + "$(inherited)", + "-framework", + NetKitShared + ); + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = NetKit/Info.plist; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + PRODUCT_BUNDLE_IDENTIFIER = cz.netkit.ios; + PRODUCT_NAME = "$(TARGET_NAME)"; + CURRENT_PROJECT_VERSION = 1; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 00000000000000000000000B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; + "FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]" = "$(PROJECT_DIR)/../shared/build/bin/iosSimulatorArm64/debugFramework"; + "FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]" = "$(PROJECT_DIR)/../shared/build/bin/iosArm64/debugFramework"; + BUNDLE_LOADER = "$(TEST_HOST)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/NetKit.app/NetKit"; + OTHER_SWIFT_FLAGS = ("$(inherited)", "-Xfrontend", "-disable-autolink-framework", "-Xfrontend", NetKitShared); + GENERATE_INFOPLIST_FILE = YES; + PRODUCT_BUNDLE_IDENTIFIER = cz.netkit.ios.tests; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 00000000000000000000000C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; + "FRAMEWORK_SEARCH_PATHS[sdk=iphonesimulator*]" = "$(PROJECT_DIR)/../shared/build/bin/iosSimulatorArm64/releaseFramework"; + "FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]" = "$(PROJECT_DIR)/../shared/build/bin/iosArm64/releaseFramework"; + BUNDLE_LOADER = "$(TEST_HOST)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/NetKit.app/NetKit"; + OTHER_SWIFT_FLAGS = ("$(inherited)", "-Xfrontend", "-disable-autolink-framework", "-Xfrontend", NetKitShared); + GENERATE_INFOPLIST_FILE = YES; + PRODUCT_BUNDLE_IDENTIFIER = cz.netkit.ios.tests; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 00000000000000000000000D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; + GENERATE_INFOPLIST_FILE = YES; + PRODUCT_BUNDLE_IDENTIFIER = cz.netkit.ios.uitests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_TARGET_NAME = NetKit; + }; + name = Debug; + }; + 00000000000000000000000E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + "EXCLUDED_ARCHS[sdk=iphonesimulator*]" = x86_64; + GENERATE_INFOPLIST_FILE = YES; + PRODUCT_BUNDLE_IDENTIFIER = cz.netkit.ios.uitests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_TARGET_NAME = NetKit; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 00000000000000000000000F = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000000000007 /* Debug */, + 000000000000000000000008 /* Release */ + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 000000000000000000000010 = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000000000009 /* Debug */, + 00000000000000000000000A /* Release */ + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 000000000000000000000011 = { + isa = XCConfigurationList; + buildConfigurations = ( + 00000000000000000000000B /* Debug */, + 00000000000000000000000C /* Release */ + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 000000000000000000000012 = { + isa = XCConfigurationList; + buildConfigurations = ( + 00000000000000000000000D /* Debug */, + 00000000000000000000000E /* Release */ + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 000000000000000000000030 /* Project object */; +} diff --git a/iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..8a5e03e --- /dev/null +++ b/iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,68 @@ +{ + "pins": [ + { + "identity": "swift-asn1", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-asn1.git", + "state": { + "revision": "f70225981241859eb4aa1a18a75531d26637c8cc", + "version": "1.4.0" + } + }, + { + "identity": "swift-atomics", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-atomics.git", + "state": { + "revision": "b601256eab081c0f92f059e12818ac1d4f178ff7", + "version": "1.3.0" + } + }, + { + "identity": "swift-collections", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-collections.git", + "state": { + "revision": "c1805596154bb3a265fd91b8ac0c4433b4348fb0", + "version": "1.2.0" + } + }, + { + "identity": "swift-crypto", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-crypto.git", + "state": { + "revision": "e8d6eba1fef23ae5b359c46b03f7d94be2f41fed", + "version": "3.12.3" + } + }, + { + "identity": "swift-nio", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-nio.git", + "state": { + "revision": "ad6b5f17270a7008f60d35ec5378e6144a575162", + "version": "2.84.0" + } + }, + { + "identity": "swift-nio-ssh", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-nio-ssh.git", + "state": { + "revision": "d1985926494b624e751b379009dc83f3395fd88a", + "version": "0.15.1" + } + }, + { + "identity": "swift-system", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-system.git", + "state": { + "revision": "61e4ca4b81b9e09e2ec863b00c340eb13497dac6", + "version": "1.5.0" + } + } + ], + "version": 2 +} diff --git a/iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme b/iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme new file mode 100644 index 0000000..79cfda1 --- /dev/null +++ b/iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/iosApp/NetKit/IcmpPing.swift b/iosApp/NetKit/IcmpPing.swift new file mode 100644 index 0000000..f2f4ecc --- /dev/null +++ b/iosApp/NetKit/IcmpPing.swift @@ -0,0 +1,105 @@ +import Darwin +import Foundation +import NetKitShared + +/// One IPv4 ICMP datagram probe. The descriptor is owned by the worker until it exits. +enum IcmpResult { case reply(Double), timeout, invalid } + +final class IcmpPing { + private let lock = NSLock() + private var cancelled = false + var onProbeStarted: (() -> Void)? + + func cancel() { + lock.lock() + cancelled = true + lock.unlock() + } + + private var isCancelled: Bool { + lock.lock() + defer { lock.unlock() } + return cancelled + } + + func start(address: String, interfaceName: String? = nil, completion: @escaping (IcmpResult) -> Void) { + DispatchQueue.global(qos: .userInitiated).async { + let result = self.probe(address: address, interfaceName: interfaceName) + DispatchQueue.main.async { + if !self.isCancelled { completion(result) } + } + } + } + + static func makeRequest(payload: [UInt8]) -> [UInt8] { + precondition(payload.count > 0 && payload.count % 2 == 0) + var packet: [UInt8] = [8, 0, 0, 0, 0, 0, 0, 1] + payload + var sum: UInt32 = 0 + for index in stride(from: 0, to: packet.count, by: 2) { + sum += UInt32(packet[index]) << 8 | UInt32(packet[index + 1]) + } + while sum >> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16) } + let checksum = UInt16(truncatingIfNeeded: ~sum) + packet[2] = UInt8(checksum >> 8) + packet[3] = UInt8(checksum & 0xff) + return packet + } + + private func probe(address: String, interfaceName: String?) -> IcmpResult { + var destination = sockaddr_in() + destination.sin_len = UInt8(MemoryLayout.size) + destination.sin_family = sa_family_t(AF_INET) + guard address.withCString({ inet_pton(AF_INET, $0, &destination.sin_addr) }) == 1 else { return .invalid } + let fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) + guard fd >= 0 else { return .invalid } + defer { close(fd) } + if let interfaceName { + var index = if_nametoindex(interfaceName) + guard index != 0, + setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &index, socklen_t(MemoryLayout.size(ofValue: index))) == 0 else { return .invalid } + } + let connected = withUnsafePointer(to: &destination) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) + } + } + guard connected == 0 else { return .invalid } + let request = Self.makeRequest(payload: (0..<16).map { _ in UInt8.random(in: 0...255) }) + guard !isCancelled else { return .invalid } + let sentAt = ProcessInfo.processInfo.systemUptime + guard request.withUnsafeBytes({ send(fd, $0.baseAddress, $0.count, 0) }) == request.count else { return .invalid } + onProbeStarted?() + let deadline = ProcessInfo.processInfo.systemUptime + 5 + while !isCancelled && ProcessInfo.processInfo.systemUptime < deadline { + var descriptor = pollfd(fd: fd, events: Int16(POLLIN), revents: 0) + let ready = poll(&descriptor, 1, 100) + if ready < 0 { return .invalid } + if ready == 0 { continue } + var buffer = [UInt8](repeating: 0, count: 2048) + let count = buffer.withUnsafeMutableBytes { recv(fd, $0.baseAddress, $0.count, 0) } + guard count > 0 else { return .invalid } + let bytes = Array(buffer.prefix(count)) + let reply: [UInt8] + if let first = bytes.first, first >> 4 == 4 { + let headerLength = Int(first & 0x0f) * 4 + guard headerLength >= 20, bytes.count >= headerLength, bytes.count >= 20, + bytes[9] == UInt8(IPPROTO_ICMP) else { continue } + reply = Array(bytes[headerLength...]) + } else { + reply = bytes + } + let sent = KotlinByteArray(size: Int32(request.count)) + for (index, byte) in request.enumerated() { + sent.set(index: Int32(index), value: Int8(bitPattern: byte)) + } + let received = KotlinByteArray(size: Int32(reply.count)) + for (index, byte) in reply.enumerated() { + received.set(index: Int32(index), value: Int8(bitPattern: byte)) + } + if IosNetworkDomain().icmpReplyMatches(request: sent, reply: received) { + return .reply((ProcessInfo.processInfo.systemUptime - sentAt) * 1000) + } + } + return isCancelled ? .invalid : .timeout + } +} diff --git a/iosApp/NetKit/Info.plist b/iosApp/NetKit/Info.plist new file mode 100644 index 0000000..9f3dde8 --- /dev/null +++ b/iosApp/NetKit/Info.plist @@ -0,0 +1,7 @@ + + + +NSBonjourServices_ssh._tcp +NSLocalNetworkUsageDescriptionNetKit connects to devices you choose on your local network. +NSLocationWhenInUseUsageDescriptionLocation permission can allow NetKit to identify the current Wi-Fi network. + diff --git a/iosApp/NetKit/KeychainSecrets.swift b/iosApp/NetKit/KeychainSecrets.swift new file mode 100644 index 0000000..db33128 --- /dev/null +++ b/iosApp/NetKit/KeychainSecrets.swift @@ -0,0 +1,114 @@ +import Foundation +import Security + +/// Secret bytes never enter UserDefaults, profile JSON, logs, or backups. +final class KeychainSecrets { + enum Failure: Error { case invalidReference, tooLarge, unavailable(OSStatus) } + private let service: String + private let limit = 256 * 1024 + + init(service: String = "cz.netkit.ios.ssh.secrets") { + self.service = service + } + + private func query(_ id: String) throws -> [String: Any] { + guard !id.isEmpty, id.utf8.count <= 80, + id.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0) || $0 == 45 }) else { + throw Failure.invalidReference + } + return [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: id, + kSecAttrSynchronizable as String: false] + } + + func put(_ id: String, secret: Data) throws { + guard secret.count <= limit else { throw Failure.tooLarge } + let search = try query(id) + let update: [String: Any] = [kSecValueData as String: secret, + kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly] + let status = SecItemUpdate(search as CFDictionary, update as CFDictionary) + if status == errSecSuccess { return } + guard status == errSecItemNotFound else { throw Failure.unavailable(status) } + var item = search + for (key, value) in update { item[key] = value } + let added = SecItemAdd(item as CFDictionary, nil) + if added == errSecDuplicateItem { + let retried = SecItemUpdate(search as CFDictionary, update as CFDictionary) + guard retried == errSecSuccess else { throw Failure.unavailable(retried) } + } else if added != errSecSuccess { + throw Failure.unavailable(added) + } + } + + func get(_ id: String) throws -> Data? { + var search = try query(id) + search[kSecReturnData as String] = true + search[kSecMatchLimit as String] = kSecMatchLimitOne + var value: CFTypeRef? + let status = SecItemCopyMatching(search as CFDictionary, &value) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess, let data = value as? Data, data.count <= limit else { + throw Failure.unavailable(status == errSecSuccess ? errSecDecode : status) + } + return data + } + + func delete(_ id: String) throws { + let status = SecItemDelete(try query(id) as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { throw Failure.unavailable(status) } + } + + func deleteServiceItems() throws { + let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrSynchronizable as String: false] + let status = SecItemDelete(query as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { throw Failure.unavailable(status) } + } + + func accountIDs() throws -> [String] { + let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrSynchronizable as String: false, + kSecReturnAttributes as String: true, + kSecMatchLimit as String: kSecMatchLimitAll] + var result: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return [] } + guard status == errSecSuccess, let attributes = result as? [[String: Any]] else { + throw Failure.unavailable(status == errSecSuccess ? errSecDecode : status) + } + return try attributes.map { + guard let id = $0[kSecAttrAccount as String] as? String else { throw Failure.unavailable(errSecDecode) } + return id + } + } +} + +import NetKitShared + +final class KeychainSecretBackend: NSObject, IosSecretBackend { + private let keychain: KeychainSecrets + init(keychain: KeychainSecrets = KeychainSecrets()) { self.keychain = keychain } + + func store(id: String, bytes: KotlinByteArray) -> SshFailure? { + let secret = Data((0.. IosSecretReadResult { + do { + guard let secret = try keychain.get(id) else { return IosSecretReadResult(bytes: nil, failure: nil) } + let bytes = KotlinByteArray(size: Int32(secret.count)) + for (index, value) in secret.enumerated() { bytes.set(index: Int32(index), value: Int8(bitPattern: value)) } + return IosSecretReadResult(bytes: bytes, failure: nil) + } catch { return IosSecretReadResult(bytes: nil, failure: .secretUnavailable) } + } + + func remove(id: String) -> SshFailure? { + do { try keychain.delete(id); return nil } + catch { return .secretUnavailable } + } +} diff --git a/iosApp/NetKit/LanView.swift b/iosApp/NetKit/LanView.swift new file mode 100644 index 0000000..f3820f6 --- /dev/null +++ b/iosApp/NetKit/LanView.swift @@ -0,0 +1,310 @@ +import Darwin +import Network +import NetKitShared +import SwiftUI + +/// Owns one operation. All state and callbacks are serialized on the main queue. +final class LanSession: ObservableObject { + @Published var status = "" + @Published var results: [String] = [] + @Published var running = false + private var connection: NWConnection? + private var browser: NWBrowser? + private var timer: DispatchWorkItem? + private var ping: IcmpPing? + private let domain = IosNetworkDomain() + private let wifi = WolPlatform() + var activeWifiCIDR: String? { wifi.activeWifiCIDR() } + + func cancel() { + scan?.cancel() + scan = nil + ping?.cancel() + ping = nil + timer?.cancel() + timer = nil + connection?.cancel() + connection = nil + browser?.cancel() + browser = nil + running = false + if status == String(localized: "network.running") || status == String(localized: "network.waiting") { status = "" } + } + + private var scan: PortScan? + + func scanPorts(host: String, input: String) { + cancel() + guard !host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + let parsed = domain.ports(input: input), !parsed.isEmpty, parsed.count <= 64 else { + status = String(localized: "network.invalid") + return + } + let host = host.trimmingCharacters(in: .whitespacesAndNewlines) + let ports = parsed.map { UInt16($0.intValue) } + let reasons = domain.confirmationReasons(address: host, ownCidr: activeWifiCIDR, portCount: Int32(ports.count)) + guard !reasons.contains("INVALID_TARGET"), !reasons.contains("INVALID_PORT_COUNT") else { + status = String(localized: "network.invalid") + return + } + results = [] + running = true + status = String(localized: "network.running") + let operation = PortScan(host: host, ports: ports) + scan = operation + operation.start { [weak self, weak operation] port, result, done in + guard let self, let operation, self.scan === operation else { return } + if let port, let result { + self.results.append("\(port): \(result)") + } + if done { + self.status = String(localized: "lan.scan.finished") + self.cancel() + } + } + } + + func dns(host: String, server: String, serverPort: UInt16 = 53) { + cancel() + let host = host.trimmingCharacters(in: .whitespacesAndNewlines) + let server = server.trimmingCharacters(in: .whitespacesAndNewlines) + let id = Int32.random(in: 0...65535) + guard let query = domain.dnsQuery(host: host, type: 1, id: id), + Self.validIPv4(server), + let endpointPort = NWEndpoint.Port(rawValue: serverPort) else { + status = String(localized: "network.invalid") + return + } + let bytes = Data((0.. Bool { + var address = in_addr() + return value.withCString { inet_pton(AF_INET, $0, &address) } == 1 + } + + static func permissionDenied(_ error: NWError, connection: NWConnection) -> Bool { + let denied = connection.currentPath?.unsatisfiedReason == .localNetworkDenied + return permissionDenied(error, localNetworkDenied: denied) + } + + static func permissionDenied(_ error: NWError, localNetworkDenied: Bool) -> Bool { + if localNetworkDenied { return true } + if case .dns(let code) = error, code == -65570 { return true } + return false + } + + func pingHost(_ host: String) { + cancel() + let host = host.trimmingCharacters(in: .whitespacesAndNewlines) + guard Self.validIPv4(host) else { status = String(localized: "network.invalid"); return } + running = true + status = String(localized: "network.running") + let probe = IcmpPing() + ping = probe + probe.start(address: host) { [weak self, weak probe] result in + guard let self, let probe, self.ping === probe else { return } + switch result { + case .reply(let milliseconds): + self.status = String(localized: "lan.ping.reply") + " " + milliseconds.formatted(.number.precision(.fractionLength(1))) + " ms" + case .timeout: self.status = String(localized: "network.timeout") + case .invalid: self.status = String(localized: "network.failed") + } + self.cancel() + } + } + + func browse(loopbackOnly: Bool = false, stateObserver: ((NWBrowser.State) -> Void)? = nil) { + cancel() + results = [] + running = true + status = String(localized: "network.running") + let parameters = NWParameters.tcp + if loopbackOnly { parameters.requiredInterfaceType = .loopback } + let browse = NWBrowser(for: .bonjour(type: "_ssh._tcp", domain: "local."), using: parameters) + browser = browse + browse.stateUpdateHandler = { [weak self, weak browse] state in + stateObserver?(state) + guard let self, let browse, self.browser === browse else { return } + switch state { + case .waiting: self.status = String(localized: "network.waiting") + case .failed: + self.status = String(localized: "network.failed") + self.cancel() + default: break + } + } + browse.browseResultsChangedHandler = { [weak self, weak browse] results, _ in + guard let self, let browse, self.browser === browse else { return } + var names = Set() + for result in results { + if names.count >= 128 { break } + if case let .service(name, type, domain, interface) = result.endpoint, + let safeName = self.domain.mdnsName(raw: name)?.value { + names.insert("\(safeName) — \(type) \(domain) \(interface?.name ?? "")") + } + } + self.results = names.sorted() + } + let timeout = DispatchWorkItem { [weak self, weak browse] in + guard let self, let browse, self.browser === browse else { return } + if self.status != String(localized: "network.waiting") { + self.status = String(localized: "lan.browse.finished") + } + self.cancel() + } + timer = timeout + DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: timeout) + browse.start(queue: .main) + } +} + +struct ScanConsent: Equatable { + let host: String + let ports: String + let cidr: String? + + var reasons: [String] { + let domain = IosNetworkDomain() + return domain.confirmationReasons(address: host, ownCidr: cidr, + portCount: Int32(domain.ports(input: ports)?.count ?? 0)) + } + + func message(resolve: (String) -> String) -> String { + var lines = [resolve("lan.warning")] + if reasons.contains("OUTSIDE_WIFI") { lines.append(resolve("lan.reason.outside")) } + if reasons.contains("NON_PRIVATE_ADDRESS") { lines.append(resolve("lan.reason.nonprivate")) } + if reasons.contains("LARGE_PORT_SET") { lines.append(resolve("lan.reason.ports")) } + return lines.joined(separator: "\n") + } +} + +struct LanView: View { + @Environment(\.scenePhase) private var scenePhase + @StateObject private var session = LanSession() + @State private var host = "" + @State private var port = "22" + @State private var dnsServer = "" + @State private var pending: Action? + @State private var showingConsent = false + @State private var scanConsent: ScanConsent? + @FocusState private var focusedField: Field? + + private enum Field: Hashable { case host, port, dnsServer } + private enum Action { case scan, dns, ping, browse } + private var currentScanConsent: ScanConsent { + ScanConsent(host: host.trimmingCharacters(in: .whitespacesAndNewlines), + ports: port.trimmingCharacters(in: .whitespacesAndNewlines), cidr: session.activeWifiCIDR) + } + private func request(_ action: Action) { + focusedField = nil + pending = action + scanConsent = action == .scan ? currentScanConsent : nil + showingConsent = true + } + + var body: some View { + Form { + Text("lan.warning") + TextField("lan.host", text: $host).textInputAutocapitalization(.never).autocorrectionDisabled() + .focused($focusedField, equals: .host) + TextField("lan.port", text: $port).keyboardType(.numbersAndPunctuation) + .focused($focusedField, equals: .port) + Button("lan.tcp") { request(.scan) }.disabled(session.running) + TextField("lan.dns.server", text: $dnsServer).textInputAutocapitalization(.never).autocorrectionDisabled() + .focused($focusedField, equals: .dnsServer) + Button("lan.dns") { request(.dns) }.disabled(session.running) + Button("lan.ping") { request(.ping) }.disabled(session.running) + Button("lan.browse") { request(.browse) }.disabled(session.running) + if session.running { Button("network.cancel") { session.cancel() } } + if !session.status.isEmpty { Text(verbatim: session.status) } + if session.status.isEmpty && session.results.isEmpty { Text("devices.empty") } + ForEach(Array(session.results.enumerated()), id: \.offset) { _, value in Text(verbatim: value) } + } + .confirmationDialog("lan.consent.title", isPresented: $showingConsent, titleVisibility: .visible) { + Button("lan.consent.confirm") { + switch pending { + case .scan: + let current = currentScanConsent + if current != scanConsent { + scanConsent = current + DispatchQueue.main.async { showingConsent = true } + return + } + session.scanPorts(host: current.host, input: current.ports) + case .dns: session.dns(host: host, server: dnsServer) + case .ping: session.pingHost(host) + case .browse: session.browse() + case nil: break + } + pending = nil + } + Button("network.cancel", role: .cancel) { pending = nil } + } message: { + Text(verbatim: scanConsent?.message { NSLocalizedString($0, comment: "") } + ?? String(localized: "lan.warning")) + } + .navigationTitle("tab.devices") + .onChange(of: scenePhase) { _, phase in + if phase == .background { session.cancel() } + } + .onDisappear { session.cancel() } + } +} diff --git a/iosApp/NetKit/Localizable.xcstrings b/iosApp/NetKit/Localizable.xcstrings new file mode 100644 index 0000000..5a3043c --- /dev/null +++ b/iosApp/NetKit/Localizable.xcstrings @@ -0,0 +1,2806 @@ +{ + "sourceLanguage": "en", + "strings": { + "app.title": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "NetKit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "NetKit" + } + } + } + }, + "app.version": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Verze" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Version" + } + } + } + }, + "shared.ipv4": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "IPv4 ze sdíleného jádra" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "IPv4 from shared core" + } + } + } + }, + "tab.lan": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "LAN" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "LAN" + } + } + } + }, + "tab.wifi": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Wi-Fi" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Wi-Fi" + } + } + } + }, + "tab.speed": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Rychlost" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Speed" + } + } + } + }, + "tab.wol": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "WoL" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "WoL" + } + } + } + }, + "tab.about": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "O aplikaci" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "About" + } + } + } + }, + "wifi.ssid": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Název sítě" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Network name" + } + } + } + }, + "wifi.bssid": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "BSSID" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "BSSID" + } + } + } + }, + "wifi.refresh": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zjistit aktuální Wi-Fi" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Check current Wi-Fi" + } + } + } + }, + "wifi.unavailable": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Údaje o aktuální Wi-Fi nejsou dostupné. Systém vyžaduje příslušné oprávnění a splnění podmínek přístupu." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Current Wi-Fi details are unavailable. The system requires the appropriate entitlement and access conditions." + } + } + } + }, + "network.running": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Probíhá…" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Running…" + } + } + } + }, + "network.invalid": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zkontrolujte zadané údaje." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Check the entered values." + } + } + } + }, + "network.failed": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Operace selhala nebo není povolena." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The operation failed or is not permitted." + } + } + } + }, + "network.timeout": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Časový limit vypršel." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Timed out." + } + } + } + }, + "network.cancel": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zrušit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Cancel" + } + } + } + }, + "lan.open": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Otevřeno" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Open" + } + } + } + }, + "lan.closed": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Odmítnuto" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Refused" + } + } + } + }, + "lan.scan.finished": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Sondování dokončeno." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Probe complete." + } + } + } + }, + "lan.browse.finished": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vyhledávání dokončeno." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Browsing complete." + } + } + } + }, + "lan.warning": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Skenujte pouze vlastní sítě nebo sítě, k nimž máte výslovné svolení." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Scan only networks you own or are explicitly authorized to test." + } + } + } + }, + "lan.host": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Cíl nebo název" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Target or name" + } + } + } + }, + "lan.port": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Porty" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Ports" + } + } + } + }, + "lan.tcp": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Prověřit TCP porty" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Probe TCP ports" + } + } + } + }, + "lan.dns.server": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "DNS server" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "DNS server" + } + } + } + }, + "lan.dns": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "DNS dotaz A" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "DNS A query" + } + } + } + }, + "lan.dns.complete": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "DNS odpověď přijata." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "DNS response received." + } + } + } + }, + "lan.ping": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Ping IPv4" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "IPv4 ping" + } + } + } + }, + "lan.ping.reply": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Odpověď přijata." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Reply received." + } + } + } + }, + "lan.browse": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vyhledat Bonjour SSH služby" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Browse Bonjour SSH services" + } + } + } + }, + "lan.consent.title": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Potvrzení oprávnění" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Confirm authorization" + } + } + } + }, + "lan.consent.confirm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Mám oprávnění, pokračovat" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "I am authorized; continue" + } + } + } + }, + "speed.engine": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Metoda" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Method" + } + } + } + }, + "speed.libre": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "LibreSpeed" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "LibreSpeed" + } + } + } + }, + "speed.ndt7": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "M-Lab NDT7" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "M-Lab NDT7" + } + } + } + }, + "speed.server": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Server LibreSpeed" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "LibreSpeed server" + } + } + } + }, + "speed.parallel_warning": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Paralelní HTTP přenosy mohou být v HTTP/2 nebo HTTP/3 sdíleny na jednom spojení." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Parallel HTTP transfers may be multiplexed over one connection with HTTP/2 or HTTP/3." + } + } + } + }, + "speed.cancel": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zrušit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Cancel" + } + } + } + }, + "speed.start": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Spustit měření" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Start measurement" + } + } + } + }, + "speed.error": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Měření selhalo. Zkontrolujte server a připojení." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Measurement failed. Check the server and connection." + } + } + } + }, + "speed.download": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Stahování" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Download" + } + } + } + }, + "speed.upload": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Odesílání" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Upload" + } + } + } + }, + "speed.title": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Rychlost připojení" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Connection speed" + } + } + } + }, + "speed.confirm.title": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Spustit měření?" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Start measurement?" + } + } + } + }, + "speed.confirm.start": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Spustit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Start" + } + } + } + }, + "speed.warning.ndt7": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "M-Lab uchovává a veřejně zveřejňuje výsledky včetně vaší veřejné IP adresy. Měření může přenést stovky MB až jednotky GB a na mobilním nebo měřeném připojení zvýšit náklady." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "M-Lab stores and publicly publishes results including your public IP address. Measurement may transfer hundreds of MB to several GB and incur charges on cellular or metered connections." + } + } + } + }, + "speed.warning.data": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Měření může přenést stovky MB až jednotky GB. Na mobilním nebo měřeném připojení může spotřebovat datový limit a zvýšit náklady." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Measurement may transfer hundreds of MB to several GB. On cellular or metered connections it may use your data allowance and incur charges." + } + } + } + }, + "speed.privacy_link": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zásady soukromí M-Lab" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "M-Lab privacy policy" + } + } + } + }, + "network.waiting": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Čeká se na síť nebo oprávnění k místní síti." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Waiting for network connectivity or local network permission." + } + } + } + }, + "speed.ndt_method": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Stahování se počítá v aplikaci po náběhu; odesílání měří server za celý test. Výsledky proto používají odlišná měřicí období." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Download is calculated in the app after warm-up; upload is measured by the server over the whole test. The results therefore use different measurement periods." + } + } + } + }, + "wol.warning": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Používejte jen ve vlastní nebo povolené síti. iOS verze NetKitu podporuje pouze unicast v aktuální Wi-Fi síti. Pokud spící zařízení vypadne z ARP cache, paket nemusí dorazit ani po hlášení o odeslání." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Use only on networks you own or are authorized to use. NetKit for iOS supports only unicast on the current Wi-Fi network. If a sleeping device is absent from the ARP cache, the packet may not arrive even when sending is reported as successful." + } + } + } + }, + "wol.load.error": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Profily nelze načíst. Původní data zůstala zachována." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Profiles could not be loaded. The original data has been preserved." + } + } + } + }, + "wol.add": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nový profil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "New profile" + } + } + } + }, + "wol.name": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Název" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Name" + } + } + } + }, + "wol.mac": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "MAC adresa" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "MAC address" + } + } + } + }, + "wol.broadcast": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Broadcast" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Broadcast" + } + } + } + }, + "wol.broadcast.unavailable": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Broadcast není dostupný bez zvláštního oprávnění Apple." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Broadcast is unavailable without the special Apple entitlement." + } + } + } + }, + "wol.host": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "IPv4 cíl" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "IPv4 target" + } + } + } + }, + "wol.save": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Uložit profil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Save profile" + } + } + } + }, + "wol.devices": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zařízení" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Devices" + } + } + } + }, + "wol.delete": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Smazat" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete" + } + } + } + }, + "wol.delete.confirm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Smazat tento profil?" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete this profile?" + } + } + } + }, + "wol.sent": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Požadavek byl odeslán." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Request sent." + } + } + } + }, + "wol.no.wifi": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Není dostupná vhodná Wi-Fi." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "A suitable Wi-Fi network is unavailable." + } + } + } + }, + "wol.save.error": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Profil se nepodařilo uložit." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The profile could not be saved." + } + } + } + }, + "tab.ssh": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "SSH" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "SSH" + } + } + } + }, + "ssh.notice": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Připojujte se pouze k zařízením, pro která máte oprávnění. RSA a import soukromých OpenSSH klíčů nejsou zatím podporovány. Uložené startovací příkazy ani keepalive se zatím neprovádějí." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Connect only to devices you are authorized to access. RSA and private OpenSSH key import are not yet supported. Saved startup commands and keepalive are not yet applied." + } + } + } + }, + "ssh.profiles": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Profily" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Profiles" + } + } + } + }, + "ssh.empty": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zatím žádné SSH profily." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No SSH profiles yet." + } + } + } + }, + "ssh.add": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Přidat profil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Add profile" + } + } + } + }, + "ssh.edit": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Upravit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit" + } + } + } + }, + "ssh.import": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Importovat profily" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Import profiles" + } + } + } + }, + "ssh.keys": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Klíče Ed25519" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Ed25519 keys" + } + } + } + }, + "ssh.key.name": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Název klíče" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Key name" + } + } + } + }, + "ssh.key.generate": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vytvořit klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Generate key" + } + } + } + }, + "ssh.key.copy": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Kopírovat veřejný klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy public key" + } + } + } + }, + "ssh.trusted": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Ověřené servery" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Trusted servers" + } + } + } + }, + "ssh.terminal": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Terminál" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Terminal" + } + } + } + }, + "ssh.ctrl": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Ctrl" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Ctrl" + } + } + } + }, + "ssh.esc": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Esc" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Esc" + } + } + } + }, + "ssh.left": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vlevo" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Left" + } + } + } + }, + "ssh.up": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nahoru" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Up" + } + } + } + }, + "ssh.down": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Dolů" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Down" + } + } + } + }, + "ssh.right": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vpravo" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Right" + } + } + } + }, + "ssh.columns": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Sloupce" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Columns" + } + } + } + }, + "ssh.rows": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Řádky" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Rows" + } + } + } + }, + "ssh.resize": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Změnit velikost" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Resize" + } + } + } + }, + "ssh.copy": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Kopírovat terminál" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy terminal" + } + } + } + }, + "ssh.disconnect": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Odpojit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Disconnect" + } + } + } + }, + "ssh.host.first": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Ověřte otisk serveru" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Verify the server fingerprint" + } + } + } + }, + "ssh.host.accept": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Důvěřovat" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Trust" + } + } + } + }, + "ssh.host.reject": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Odmítnout" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Reject" + } + } + } + }, + "ssh.import.preview": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Náhled importu" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Import preview" + } + } + } + }, + "ssh.import.apply": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Použít import" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Apply import" + } + } + } + }, + "ssh.import.new": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nové" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "New" + } + } + } + }, + "ssh.import.updated": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Změněné" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Updated" + } + } + } + }, + "ssh.import.unchanged": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Beze změny" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Unchanged" + } + } + } + }, + "ssh.import.skipped": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vynechané" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Skipped" + } + } + } + }, + "ssh.paste.warning": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vložený text obsahuje řídicí znaky. Ty budou nahrazeny mezerami." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The pasted text contains control characters. They will be replaced with spaces." + } + } + } + }, + "ssh.paste.confirm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vložit upravený text" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Paste sanitized text" + } + } + } + }, + "ssh.trust.reset.warning": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zapomenout důvěru serveru a ukončit spojení? Při dalším připojení znovu ověřte otisk; hrozí útok prostředníka." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Forget server trust and close the connection? Verify the fingerprint again on the next connection; interception is possible." + } + } + } + }, + "ssh.trust.reset": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zapomenout důvěru" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Forget trust" + } + } + } + }, + "ssh.error.storage": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Úložiště není dostupné nebo je poškozené." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Storage is unavailable or corrupted." + } + } + } + }, + "ssh.error.invalid": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zkontrolujte zadané údaje nebo soubor." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Check the entered values or file." + } + } + } + }, + "ssh.error.credentials": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Přihlašovací údaje nejsou dostupné." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Credentials are unavailable." + } + } + } + }, + "ssh.error.connection": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Připojení SSH selhalo." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The SSH connection failed." + } + } + } + }, + "ssh.error.host.changed": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "VAROVÁNÍ: Klíč serveru se změnil. Spojení bylo odmítnuto; ověřte možnost útoku prostředníka." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "WARNING: The server key changed. The connection was rejected; verify whether interception occurred." + } + } + } + }, + "ssh.error.host.rejected": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Klíč serveru byl odmítnut." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The server key was rejected." + } + } + } + }, + "ssh.error.timeout": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vypršel čas na ověření serveru." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Server verification timed out." + } + } + } + }, + "ssh.error.input": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vstupní fronta je plná nebo spojení není připravené." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The input queue is full or the connection is not ready." + } + } + } + }, + "ssh.name": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Název" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Name" + } + } + } + }, + "ssh.host": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Server" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Server" + } + } + } + }, + "ssh.user": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Uživatel" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Username" + } + } + } + }, + "ssh.authentication": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Ověření" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Authentication" + } + } + } + }, + "ssh.password": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Heslo" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Password" + } + } + } + }, + "ssh.save": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Uložit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Save" + } + } + } + }, + "ssh.profile": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "SSH profil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "SSH profile" + } + } + } + }, + "ssh.skip.proxyjump": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "ProxyJump není podporován" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "ProxyJump is unsupported" + } + } + } + }, + "ssh.skip.proxycommand": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "ProxyCommand není podporován" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "ProxyCommand is unsupported" + } + } + } + }, + "ssh.skip.match": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Match není podporován" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Match is unsupported" + } + } + } + }, + "ssh.skip.wildcard": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zástupný znak není podporován" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Wildcard is unsupported" + } + } + } + }, + "ssh.skip.missinghost": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Chybí hostitel" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Host is missing" + } + } + } + }, + "ssh.skip.unsupported": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nepodporovaná volba" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsupported option" + } + } + } + }, + "ssh.follow": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Sledovat výstup" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Follow output" + } + } + } + }, + "tab.overview": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Přehled" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Overview" + } + } + } + }, + "tab.devices": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zařízení" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Devices" + } + } + } + }, + "wifi.not_checked": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Aktuální Wi-Fi zatím nebyla zjištěna." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Current Wi-Fi has not been checked yet." + } + } + } + }, + "devices.empty": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zatím žádné výsledky." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No results yet." + } + } + } + }, + "wol.empty": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zatím žádná zařízení." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No devices yet." + } + } + } + }, + "ssh.error.algorithm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nepodařilo se vyjednat kompatibilní SSH algoritmy. iOS verze NetKitu podporuje hostitelské klíče Ed25519 a ECDSA; RSA nepodporuje." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Could not negotiate compatible SSH algorithms. NetKit for iOS supports Ed25519 and ECDSA host keys; RSA is unsupported." + } + } + } + }, + "ssh.error.unsupported_credential": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nepodporovaný přihlašovací klíč. iOS verze NetKitu podporuje přihlašování klíčem pouze s Ed25519 vygenerovaným v aplikaci." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsupported authentication key. NetKit for iOS supports key authentication only with Ed25519 keys generated in the app." + } + } + } + }, + "about.privacy": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zásady ochrany soukromí" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Privacy policy" + } + } + } + }, + "about.licenses": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Open source licence" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Open source licenses" + } + } + } + }, + "about.licenses.unavailable": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Licence nejsou dostupné." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Licenses are unavailable." + } + } + } + }, + "about.licenses.content": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Texty licencí" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "License texts" + } + } + } + }, + "ssh.host.changed.context": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Změněný hostitelský klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Changed host key" + } + } + } + }, + "ssh.host.saved": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Uložený otisk" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Saved fingerprint" + } + } + } + }, + "ssh.host.offered": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Nabízený otisk" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Offered fingerprint" + } + } + } + }, + "ssh.host.previously.rejected": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Dříve odmítnutý otisk:" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Previously rejected fingerprint:" + } + } + } + }, + "ssh.host.rejected.again": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Pozor: tento klíč jste již odmítli." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Warning: you previously rejected this key." + } + } + } + }, + "ssh.profile.delete": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Smazat profil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete profile" + } + } + } + }, + "ssh.profile.delete.confirm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Smazat SSH profil?" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete SSH profile?" + } + } + } + }, + "ssh.key.delete": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Smazat klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete key" + } + } + } + }, + "ssh.key.delete.confirm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Smazat SSH klíč?" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete SSH key?" + } + } + } + }, + "ssh.error.key.in.use": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Klíč používá některý profil. Nejprve jej odpojte." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "A profile uses this key. Detach it first." + } + } + } + }, + "network.permission": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Chybí oprávnění k místní síti. Povolte jej v Nastavení iOS." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Local network access is denied. Enable it in iOS Settings." + } + } + } + }, + "lan.reason.outside": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Cíl neleží v aktuální Wi-Fi síti nebo její rozsah nelze zjistit." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The target is outside the current Wi-Fi network or its range is unavailable." + } + } + } + }, + "lan.reason.nonprivate": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Rozsah zahrnuje adresu mimo privátní, sdílené nebo link-local bloky." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The range includes an address outside private, shared or link-local blocks." + } + } + } + }, + "lan.reason.ports": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Skenujete větší počet portů." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "You are scanning a large number of ports." + } + } + } + }, + "ssh.ok": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "OK" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "OK" + } + } + } + }, + "ssh.export": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Exportovat profily" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Export profiles" + } + } + } + }, + "ssh.export.failed": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Export se nezdařil" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Export failed" + } + } + } + }, + "ssh.export.duplicate.names": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Profily mají duplicitní názvy. Před exportem je přejmenujte:" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Profiles have duplicate names. Rename them before exporting:" + } + } + } + }, + "ssh.export.too.large": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Export překračuje limit 256 KiB. Zmenšete počet profilů nebo délku startovacích příkazů." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The export exceeds 256 KiB. Reduce the number of profiles or shorten startup commands." + } + } + } + }, + "ssh.move.up": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Posunout profil %@ nahoru" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Move profile %@ up" + } + } + } + }, + "ssh.move.down": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Posunout profil %@ dolů" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Move profile %@ down" + } + } + } + }, + "ssh.key.required.title": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vyberte klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Select a key" + } + } + } + }, + "ssh.key.required.message": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Profil nemá přiřazený existující klíč. Vyberte klíč nebo vytvořte nový v editoru profilu." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "This profile has no existing key assigned. Select a key or create one in the profile editor." + } + } + } + }, + "ssh.key.choose": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vyberte klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Select a key" + } + } + } + }, + "ssh.profile.unavailable": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Profil byl smazán nebo už není dostupný." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The profile was deleted or is no longer available." + } + } + } + }, + "ssh.authentication.key": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Key" + } + } + } + }, + "ssh.authentication.interactive": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Keyboard-interactive" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Keyboard-interactive" + } + } + } + }, + "ssh.authentication.choose": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Vyberte heslo nebo klíč" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose password or key" + } + } + } + }, + "ssh.interactive.unsupported": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "iOS verze nepodporuje keyboard-interactive, upravte profil na heslo nebo klíč." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The iOS version does not support keyboard-interactive. Edit the profile to use a password or key." + } + } + } + }, + "ssh.import.key": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Klíč pro nové profily" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Key for new profiles" + } + } + } + }, + "ssh.import.no.key": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Bez přiřazeného klíče" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No key assigned" + } + } + } + }, + "ssh.import.startup.warning": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Zkontrolujte startovací příkaz před připojením. iOS ho zatím neprovádí." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Check the startup command before connecting. iOS does not run it yet." + } + } + } + }, + "ssh.import.password.detached": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Po potvrzení se odpojí uložené heslo. Pokud ho nepoužívá jiný profil, smaže se z Keychainu." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Confirmation detaches the saved password. It is deleted from Keychain if no other profile uses it." + } + } + } + }, + "ssh.startup.command": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Startovací příkaz" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Startup command" + } + } + } + }, + "ssh.keepalive": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Keepalive (sekundy)" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Keepalive (seconds)" + } + } + } + }, + "ssh.value.empty": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Prázdné" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Empty" + } + } + } + }, + "ssh.reconnect": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Znovu připojit" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Reconnect" + } + } + } + }, + "ssh.reconnect.confirm": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Znovu připojit tento profil?" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Reconnect this profile?" + } + } + } + }, + "ssh.keyboard.done": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "Hotovo" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Done" + } + } + } + } + }, + "version": "1.0" +} diff --git a/iosApp/NetKit/NetKitApp.swift b/iosApp/NetKit/NetKitApp.swift new file mode 100644 index 0000000..b5cc86c --- /dev/null +++ b/iosApp/NetKit/NetKitApp.swift @@ -0,0 +1,174 @@ +import SwiftUI +import NetworkExtension +import NetKitShared + +@main +struct NetKitApp: App { + var body: some Scene { + WindowGroup { ContentView() } + } +} + +struct ContentView: View { + @Environment(\.scenePhase) private var scenePhase + @StateObject private var ssh = SshViewModel.forApp() + var body: some View { + TabView { + NavigationStack { OverviewView() } + .tabItem { Label("tab.overview", systemImage: "wifi") } + NavigationStack { LanView() } + .tabItem { Label("tab.devices", systemImage: "network") } + NavigationStack { SshView(model: ssh) } + .tabItem { Label("tab.ssh", systemImage: "terminal") } + NavigationStack { WolView() } + .tabItem { Label("tab.wol", systemImage: "power") } + } + .onChange(of: scenePhase) { _, phase in + if phase == .background { ssh.background() } + else if phase == .active { ssh.foreground() } + } + .overlay { + if scenePhase != .active { + Color(uiColor: .systemBackground).ignoresSafeArea() + } + } + } +} + +struct OverviewView: View { + @State private var network: NEHotspotNetwork? + @State private var checked = false + @State private var loading = false + + var body: some View { + Form { + Section("tab.wifi") { + if let network { + LabeledContent("wifi.ssid", value: network.ssid) + LabeledContent("wifi.bssid", value: network.bssid) + } else if checked { + Text("wifi.unavailable") + } else { + Text("wifi.not_checked") + } + Button("wifi.refresh") { + loading = true + Task { + network = await NEHotspotNetwork.fetchCurrent() + checked = true + loading = false + } + }.disabled(loading) + } + NavigationLink("speed.title") { SpeedView() } + NavigationLink("tab.about") { AboutView() } + } + .navigationTitle("tab.overview") + } +} + +struct AboutView: View { + private let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "—" + + var body: some View { + Form { + Text("app.title").font(.largeTitle).bold() + HStack { + Text("app.version") + Spacer() + Text(verbatim: version).accessibilityIdentifier("appVersionValue") + } + .accessibilityElement(children: .contain) + if let url = URL(string: IosAboutDomain().privacyUrl(language: Bundle.main.preferredLocalizations.first ?? "en")) { + Link("about.privacy", destination: url) + } + NavigationLink("about.licenses") { OpenSourceLicensesView() } + } + .navigationTitle("tab.about") + } +} + +struct OpenSourceLicensesView: View { + private let text: String? = Bundle.main.url(forResource: "OpenSourceLicenses", withExtension: "txt") + .flatMap { try? String(contentsOf: $0, encoding: .utf8) } + + var body: some View { + ScrollView { + VStack(alignment: .leading) { + Text("about.licenses.content").font(.headline) + Text(verbatim: text ?? String(localized: "about.licenses.unavailable")) + .textSelection(.enabled) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding() + } + .navigationTitle("about.licenses") + } +} + +@MainActor +extension SshViewModel { + static func forApp() -> SshViewModel { + #if DEBUG && targetEnvironment(simulator) + let environment = ProcessInfo.processInfo.environment + if let token = environment["NETKIT_UI_SSH_ID"], let id = UUID(uuidString: token), + let scenario = environment["NETKIT_UI_SSH_SCENARIO"], + ["empty", "profiles", "preview", "preview-v1", "reconnect", "interactive", "duplicates", "large"].contains(scenario) { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("netkit-ui-ssh-" + id.uuidString, isDirectory: true) + let chain = KeychainSecrets(service: "cz.netkit.ios.ui-tests." + id.uuidString) + do { + if environment["NETKIT_UI_SSH_RESET"] == "1", FileManager.default.fileExists(atPath: root.path) { + try FileManager.default.removeItem(at: root) + try chain.deleteServiceItems() + } + let exists = FileManager.default.fileExists(atPath: root.appendingPathComponent("ssh.json").path) + let store = try SshMetadataStore(directory: root) + let domain = IosSshDomain() + if !exists && scenario != "empty" { + try store.save(key: SshKeyInfo(id: "other-key", name: "Other key", publicKey: "ssh-ed25519 example")) + let reconnectReference = UUID().uuidString + if scenario == "reconnect" { try chain.put(reconnectReference, secret: Data(UUID().uuidString.utf8)) } + let count = scenario == "large" ? 65 : scenario.hasPrefix("preview") || scenario == "interactive" || scenario == "reconnect" ? 1 : 2 + for index in 0...txt file, which is located in +the 'license' directory of the distribution file, for the license terms of the +components that this product depends on. + +------------------------------------------------------------------------------- + +This product is heavily influenced by Netty. + + * LICENSE (Apache License 2.0): + * https://github.com/netty/netty/blob/4.1/LICENSE.txt + * HOMEPAGE: + * https://netty.io + +--- + +This product contains NodeJS's llhttp. + + * LICENSE (MIT): + * https://github.com/nodejs/llhttp/blob/1e1c5b43326494e97cf8244ff57475eb72a1b62c/LICENSE-MIT + * HOMEPAGE: + * https://github.com/nodejs/llhttp + +--- + +This product contains "cpp_magic.h" from Thomas Nixon & Jonathan Heathcote's uSHET + + * LICENSE (MIT): + * https://github.com/18sg/uSHET/blob/c09e0acafd86720efe42dc15c63e0cc228244c32/lib/cpp_magic.h + * HOMEPAGE: + * https://github.com/18sg/uSHET + +--- + +This product contains "sha1.c" and "sha1.h" from FreeBSD (Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project) + + * LICENSE (BSD-3): + * https://opensource.org/licenses/BSD-3-Clause + * HOMEPAGE: + * https://github.com/freebsd/freebsd-src + +--- + +This product contains a derivation of Fabian Fett's 'Base64.swift'. + + * LICENSE (Apache License 2.0): + * https://github.com/swift-extras/swift-extras-base64/blob/b8af49699d59ad065b801715a5009619100245ca/LICENSE + * HOMEPAGE: + * https://github.com/fabianfett/swift-base64-kit + +--- + +This product contains a derivation of "XCTest+AsyncAwait.swift" from AsyncHTTPClient. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/swift-server/async-http-client + +--- + +This product contains a derivation of "_TinyArray.swift" from SwiftCertificates. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-certificates + +--- + +This product contains a derivation of the mocking infrastructure from Swift System. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-system + +--- + +This product contains a derivation of "TokenBucket.swift" from Swift Package Manager. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/swiftlang/swift-package-manager + + + +===== swift-crypto 3.12.3: LICENSE.txt ===== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +===== swift-crypto 3.12.3: NOTICE.txt ===== + + The SwiftCrypto Project + ======================= + +Please visit the SwiftCrypto web site for more information: + + * https://github.com/apple/swift-crypto + +Copyright 2019 The SwiftCrypto Project + +The SwiftCrypto Project licenses this file to you under the Apache License, +version 2.0 (the "License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at: + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations +under the License. + +Also, please refer to each LICENSE..txt file, which is located in +the 'license' directory of the distribution file, for the license terms of the +components that this product depends on. + +------------------------------------------------------------------------------- + +This product contains test vectors from Google's wycheproof project. + + * LICENSE (Apache License 2.0): + * https://github.com/C2SP/wycheproof/blob/31387e2cd596587c859c611027b6a44d2e2b65ff/LICENSE + * HOMEPAGE: + * https://github.com/google/wycheproof + +--- + +This product contains a derivation of various scripts from SwiftNIO. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-nio + + + +===== swift-atomics 1.3.0: LICENSE.txt ===== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +## Runtime Library Exception to the Apache 2.0 License: ## + + + As an exception, if you use this Software to compile your source code and + portions of this Software are embedded into the binary product as a result, + you may redistribute such product without providing attribution as would + otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. + + + +===== swift-collections 1.2.0: LICENSE.txt ===== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +## Runtime Library Exception to the Apache 2.0 License: ## + + + As an exception, if you use this Software to compile your source code and + portions of this Software are embedded into the binary product as a result, + you may redistribute such product without providing attribution as would + otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. + + + +===== swift-system 1.5.0: LICENSE.txt ===== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +## Runtime Library Exception to the Apache 2.0 License: ## + + + As an exception, if you use this Software to compile your source code and + portions of this Software are embedded into the binary product as a result, + you may redistribute such product without providing attribution as would + otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. + + +===== swift-asn1 1.4.0: LICENSE.txt ===== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + + +===== swift-asn1 1.4.0: NOTICE.txt ===== + + + The SwiftASN1 Project + ===================== + +Please visit the SwiftASN1 web site for more information: + + * https://github.com/apple/swift-asn1 + +Copyright 2022 The SwiftASN1 Project + +The SwiftASN1 Project licenses this file to you under the Apache License, +version 2.0 (the "License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at: + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +License for the specific language governing permissions and limitations +under the License. + +Also, please refer to each LICENSE.txt file, which is located in +the 'license' directory of the distribution file, for the license terms of the +components that this product depends on. + +--- + +This product contains derivations of various scripts from SwiftNIO. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-nio + +--- + +This product contains derivations of various scripts from Swift OpenAPI Generator. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-openapi-generator + + + +===== Kotlin 2.2.20 ===== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +===== Kotlin stdlib collections: derived from GWT, copyright 2007-08 Google Inc. ===== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +===== Kotlin/Native unsigned integers: derived from Guava, copyright 2011 The Guava Authors ===== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +===== Kotlin stdlib time: ThreeTen ===== + +Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos. + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of JSR-310 nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +===== Kotlin/Native Utils.cpp: Boost hash functions, copyright 2005-2014 Daniel James ===== + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +===== kotlinx-coroutines 1.10.2 ===== + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2000-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +===== kotlinx-serialization 1.9.0 ===== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +===== kotlinx-atomicfu 0.26.1 ===== + +/* + * Copyright 2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +===== swift-nio CNIOSHA1 BSD-3-Clause ===== + +/* Additional changes for SwiftNIO: + - prefixed all symbols by 'c_nio_' + - removed the _KERNEL include guards + - defined the __min_size macro inline + - included sys/endian.h on Android + - use welcoming language (soundness check) + - ensure BYTE_ORDER is defined +*/ +/* $KAME: sha1.c,v 1.5 2000/11/08 06:13:08 itojun Exp $ */ +/*- + * SPDX-License-Identifier: BSD-3-Clause + * + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + + + +===== swift-nio cpp_magic.h upstream uSHET LICENSE ===== + +uSHET Library +============= + +Copyright (c) 2014 Thomas Nixon, Jonathan Heathcote + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +jsmn Library +============ + +Copyright (c) 2010 Serge A. Zaitsev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== Kotlin/Native UnicodeData ===== + +Portions, Copyright © 1991-2005 Unicode, Inc. The following applies to Unicode. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2005 Unicode, Inc. All rights reserved. Distributed under +the Terms of Use in http://www.unicode.org/copyright.html. Permission is +hereby granted, free of charge, to any person obtaining a copy of the +Unicode data files and any associated documentation (the "Data Files") +or Unicode software and any associated documentation (the "Software") +to deal in the Data Files or Software without restriction, including without +limitation the rights to use, copy, modify, merge, publish, distribute, +and/or sell copies of the Data Files or Software, and to permit persons +to whom the Data Files or Software are furnished to do so, provided that +(a) the above copyright notice(s) and this permission notice appear with +all copies of the Data Files or Software, (b) both the above copyright +notice(s) and this permission notice appear in associated documentation, +and (c) there is clear notice in each modified Data File or in the Software +as well as in the documentation associated with the Data File(s) or Software +that the data or software has been modified. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS +INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT +OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +2. Additional terms from the Database: + +Copyright © 1995-1999 Unicode, Inc. All Rights reserved. + +Disclaimer + +The Unicode Character Database is provided as is by Unicode, Inc. +No claims are made as to fitness for any particular purpose. No warranties +of any kind are expressed or implied. The recipient agrees to determine +applicability of information provided. If this file has been purchased +on magnetic or optical media from Unicode, Inc., the sole remedy for any claim +will be exchange of defective media within 90 days of receipt. This disclaimer +is applicable for all other data files accompanying the Unicode Character Database, +some of which have been compiled by the Unicode Consortium, and some of which +have been supplied by other sources. + +Limitations on Rights to Redistribute This Data + +Recipient is granted the right to make copies in any form for internal +distribution and to freely use the information supplied in the creation of +products supporting the UnicodeTM Standard. The files in +the Unicode Character Database can be redistributed to third parties or other +organizations (whether for profit or not) as long as this notice and the disclaimer +notice are retained. Information can be extracted from these files and used +in documentation or programs, as long as there is an accompanying notice +indicating the source. + + + +===== Kotlin/Native bounded queue ===== + +Multi-producer/multi-consumer bounded queue. +Copyright (c) 2010-2011, Dmitry Vyukov. All rights reserved. +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other materials + provided with the distribution. +THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted +as representing official policies, either expressed or implied, of Dmitry Vyukov. + + +===== Kotlin/Native Apache Harmony ===== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +===== Kotlin/Native Apache Harmony NOTICE ===== + +Apache Harmony +Copyright 2006, 2010 The Apache Software Foundation. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +Portions of Apache Harmony were originally developed by +Intel Corporation and are licensed to the Apache Software +Foundation under the "Software Grant and Corporate Contribution +License Agreement" and for which the following copyright notices +apply + (C) Copyright 2005 Intel Corporation + (C) Copyright 2005-2006 Intel Corporation + (C) Copyright 2006 Intel Corporation + + + +===== Kotlin/Native libbacktrace ===== + +# Copyright (C) 2012-2016 Free Software Foundation, Inc. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: + +# (1) Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. + +# (2) Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. + +# (3) The name of the author may not be used to +# endorse or promote products derived from this software without +# specific prior written permission. + +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + + +===== Kotlin/Native UTF8-CPP ===== + +// Copyright 2006 Nemanja Trifunovic + +/* +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ diff --git a/iosApp/NetKit/PortScan.swift b/iosApp/NetKit/PortScan.swift new file mode 100644 index 0000000..e70edfc --- /dev/null +++ b/iosApp/NetKit/PortScan.swift @@ -0,0 +1,77 @@ +import Foundation +import Network + +/// Main-queue-only, bounded to four simultaneous connections and 64 requested ports. +final class PortScan { + private let host: String + private var pending: [UInt16] + private let stateObserver: ((UInt16, NWConnection.State) -> Void)? + private var active: [UInt16: NWConnection] = [:] + private(set) var peakActive = 0 + private var timeouts: [UInt16: DispatchWorkItem] = [:] + private var handler: ((UInt16?, String?, Bool) -> Void)? + private var cancelled = false + + init(host: String, ports: [UInt16], stateObserver: ((UInt16, NWConnection.State) -> Void)? = nil) { + self.host = host + self.stateObserver = stateObserver + self.pending = ports.count <= 64 ? Array(Set(ports)).sorted() : [] + } + + func start(_ handler: @escaping (UInt16?, String?, Bool) -> Void) { + self.handler = handler + guard !pending.isEmpty else { + handler(nil, String(localized: "network.invalid"), true) + return + } + fill() + } + + func cancel() { + cancelled = true + timeouts.values.forEach { $0.cancel() } + timeouts.removeAll() + active.values.forEach { $0.cancel() } + active.removeAll() + pending.removeAll() + handler = nil + } + + private func fill() { + while !cancelled && active.count < 4 && !pending.isEmpty { + let port = pending.removeFirst() + guard let endpoint = NWEndpoint.Port(rawValue: port) else { continue } + let connection = NWConnection(host: NWEndpoint.Host(host), port: endpoint, using: .tcp) + active[port] = connection + peakActive = max(peakActive, active.count) + let timeout = DispatchWorkItem { [weak self] in self?.finish(port, key: "network.timeout") } + timeouts[port] = timeout + DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: timeout) + connection.stateUpdateHandler = { [weak self, weak connection] state in + guard let connection else { return } + self?.stateObserver?(port, state) + switch state { + case .ready: self?.finish(port, key: "lan.open") + case .waiting(let error): + if LanSession.permissionDenied(error, connection: connection) { self?.finish(port, key: "network.permission") } + else if case .posix(.ECONNREFUSED) = error { self?.finish(port, key: "lan.closed") } + case .failed(let error): + if LanSession.permissionDenied(error, connection: connection) { self?.finish(port, key: "network.permission") } + else if case .posix(.ECONNREFUSED) = error { self?.finish(port, key: "lan.closed") } + else { self?.finish(port, key: "network.failed") } + default: break + } + } + connection.start(queue: .main) + } + if !cancelled && pending.isEmpty && active.isEmpty { handler?(nil, nil, true) } + } + + private func finish(_ port: UInt16, key: String.LocalizationValue) { + guard !cancelled, let connection = active.removeValue(forKey: port) else { return } + timeouts.removeValue(forKey: port)?.cancel() + connection.cancel() + handler?(port, String(localized: key), false) + fill() + } +} diff --git a/iosApp/NetKit/PrivacyInfo.xcprivacy b/iosApp/NetKit/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..fba63b5 --- /dev/null +++ b/iosApp/NetKit/PrivacyInfo.xcprivacy @@ -0,0 +1,48 @@ + + + + + NSPrivacyTracking + + NSPrivacyCollectedDataTypes + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeOtherDiagnosticData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeOther + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeOtherDataTypes + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeOther + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategorySystemBootTime + NSPrivacyAccessedAPITypeReasons + + 35F9.1 + + + + + diff --git a/iosApp/NetKit/SpeedView.swift b/iosApp/NetKit/SpeedView.swift new file mode 100644 index 0000000..428003a --- /dev/null +++ b/iosApp/NetKit/SpeedView.swift @@ -0,0 +1,501 @@ +import Foundation +import SwiftUI +import Security +import NetKitShared + +final class SpeedCounter { + private let lock = NSLock() + private var bytes: Int64 = 0 + private var failures = 0 + private var serverMbps: Double? + private var completed = false + func add(_ count: Int64) { lock.lock(); bytes += count; lock.unlock() } + func fail() { lock.lock(); failures += 1; lock.unlock() } + func setServerMbps(_ value: Double) { lock.lock(); serverMbps = value; lock.unlock() } + func serverRate() -> Double? { lock.lock(); defer { lock.unlock() }; return serverMbps } + func markCompleted() { lock.lock(); completed = true; lock.unlock() } + func isCompleted() -> Bool { lock.lock(); defer { lock.unlock() }; return completed } + func snapshot() -> (Int64, Int) { lock.lock(); defer { lock.unlock() }; return (bytes, failures) } +} + +/// Each task uses a serial delegate queue, discards download chunks and bounds other bodies. +protocol SpeedTransport { + func read(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) + func download(_ request: URLRequest, counter: SpeedCounter) async throws + func upload(_ request: URLRequest, payload: Data, counter: SpeedCounter) async throws +} + +final class SpeedHTTP: SpeedTransport { + enum Failure: Error { case invalidResponse, responseTooLarge, payloadTooLarge } + private let configuration: URLSessionConfiguration + init(configuration: URLSessionConfiguration = .ephemeral) { + self.configuration = configuration + configuration.timeoutIntervalForRequest = 5 + configuration.timeoutIntervalForResource = 15 + configuration.urlCache = nil + configuration.requestCachePolicy = .reloadIgnoringLocalCacheData + } + func read(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) { + try await SpeedHTTPTask(configuration: configuration, mode: .collect(limit)).run(request) + } + func download(_ request: URLRequest, counter: SpeedCounter) async throws { + _ = try await SpeedHTTPTask(configuration: configuration, mode: .download(counter)).run(request) + } + func upload(_ request: URLRequest, payload: Data, counter: SpeedCounter) async throws { + _ = try await SpeedHTTPTask(configuration: configuration, mode: .upload(counter, payload)).run(request) + } +} + +private final class SpeedHTTPTask: NSObject, URLSessionDataDelegate { + enum Mode { case collect(Int), download(SpeedCounter), upload(SpeedCounter, Data) } + private let configuration: URLSessionConfiguration + private let mode: Mode + private var session: URLSession! + private var task: URLSessionTask? + private var continuation: CheckedContinuation<(Data, HTTPURLResponse), Error>? + private let lock = NSLock() + private var cancelled = false + private var body = Data() + private var received: Int64 = 0 + private var lastSent: Int64 = 0 + private var response: HTTPURLResponse? + private var failure: Error? + init(configuration: URLSessionConfiguration, mode: Mode) { + self.configuration = configuration; self.mode = mode + } + func run(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { + try await withTaskCancellationHandler(operation: { + try await withCheckedThrowingContinuation { continuation in + let queue = OperationQueue(); queue.maxConcurrentOperationCount = 1 + let session = URLSession(configuration: configuration, delegate: self, delegateQueue: queue) + let task: URLSessionTask + if case .upload(_, let payload) = mode { task = session.uploadTask(with: request, from: payload) } + else { task = session.dataTask(with: request) } + lock.lock() + self.continuation = continuation; self.session = session; self.task = task + let cancelled = self.cancelled + lock.unlock() + if cancelled { task.cancel() } else { task.resume() } + } + }, onCancel: { + self.lock.lock(); self.cancelled = true; let task = self.task; self.lock.unlock() + task?.cancel() + }) + } + func urlSession(_ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { + guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else { + failure = (response as? HTTPURLResponse)?.statusCode == 413 ? SpeedHTTP.Failure.payloadTooLarge : SpeedHTTP.Failure.invalidResponse + completionHandler(.cancel); return + } + self.response = http + if case .download = mode { + let mime = (http.mimeType ?? "").lowercased() + guard !mime.hasPrefix("text/"), !["application/json", "application/xml"].contains(mime), + response.expectedContentLength < 0 || response.expectedContentLength >= 1_048_576 else { + failure = SpeedHTTP.Failure.invalidResponse; completionHandler(.cancel); return + } + } + completionHandler(.allow) + } + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + received += Int64(data.count) + switch mode { + case .download(let counter): counter.add(Int64(data.count)) + case .collect(let limit): + guard data.count <= limit - body.count else { failure = SpeedHTTP.Failure.responseTooLarge; dataTask.cancel(); return } + body.append(data) + case .upload: + guard data.count <= 512 - body.count else { failure = SpeedHTTP.Failure.responseTooLarge; dataTask.cancel(); return } + body.append(data) + } + } + func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { + guard case .upload(let counter, _) = mode else { return } + counter.add(max(0, totalBytesSent - lastSent)); lastSent = totalBytesSent + } + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if case .download = mode, error == nil, received < 1_048_576 { failure = SpeedHTTP.Failure.invalidResponse } + let result: Result<(Data, HTTPURLResponse), Error> + if let failure = failure { result = .failure(failure) } + else if let error = error { result = .failure(error) } + else if let response = response { result = .success((body, response)) } + else { result = .failure(SpeedHTTP.Failure.invalidResponse) } + lock.lock() + let continuation = self.continuation + self.continuation = nil; self.task = nil; self.session = nil + lock.unlock() + continuation?.resume(with: result) + session.finishTasksAndInvalidate() + } +} + +struct SpeedResult { + let downloadMbps: Double + let uploadMbps: Double +} + +enum SpeedFailure: Error { case invalidServer, invalidResponse, incomplete, random } + +final class UploadSizing { + private let lock = NSLock() + private var size = 8 * 1_048_576 + private var accepted = false + func current() -> Int { lock.lock(); defer { lock.unlock() }; return size } + func markAccepted() { lock.lock(); accepted = true; lock.unlock() } + func reduce(after attempted: Int) -> Bool { + lock.lock(); defer { lock.unlock() } + if attempted > size { return true } + guard !accepted, attempted > 256 * 1024 else { return false } + if size == attempted { size = attempted / 2 } + return true + } +} + +/// Parallel HTTP transfers; URLSession may multiplex them over HTTP/2 or HTTP/3. +final class LibreSpeedClient { + private let http: any SpeedTransport + private let domain = IosSpeedDomain() + private let phaseDuration: TimeInterval + init(http: any SpeedTransport = SpeedHTTP(), phaseDuration: TimeInterval = 10) { + self.http = http + self.phaseDuration = phaseDuration + } + + func measure(input: String) async throws -> SpeedResult { + guard let server = domain.libreServer(input: input) else { throw SpeedFailure.invalidServer } + let empty = try url(domain.emptyUrl(base: server.baseUrl, nonce: Int64.random(in: 1...Int64.max))) + let (probe, _) = try await http.read(URLRequest(url: empty), limit: 512) + guard probe.count <= 512 else { throw SpeedFailure.invalidResponse } + var payload = Data(count: 8 * 1_048_576) + guard payload.withUnsafeMutableBytes({ buffer in + SecRandomCopyBytes(kSecRandomDefault, buffer.count, buffer.baseAddress!) + }) == errSecSuccess else { throw SpeedFailure.random } + let down = try await phase(base: server.baseUrl, download: true, payload: payload) + let up = try await phase(base: server.baseUrl, download: false, payload: payload) + return SpeedResult(downloadMbps: down, uploadMbps: up) + } + + private func url(_ value: String) throws -> URL { + guard let result = URL(string: value), result.scheme == "https" else { throw SpeedFailure.invalidServer } + return result + } + + private func phase(base: String, download: Bool, payload: Data) async throws -> Double { + let counter = SpeedCounter() + let trace = domain.createTrace() + let start = ProcessInfo.processInfo.systemUptime + let streamCount = download ? 6 : 3 + let sizing = UploadSizing() + try await withThrowingTaskGroup(of: Void.self) { group in + for _ in 0.. 0, let summary = domain.summarize(trace: trace) else { + throw SpeedFailure.incomplete + } + return summary.mbps + } +} + +protocol NdtSocket { + func open() async throws + func receive() async throws -> URLSessionWebSocketTask.Message + func send(_ message: URLSessionWebSocketTask.Message) async throws + var normalClosure: Bool { get } + func close() +} + +/// URLSession delegate reports the negotiated subprotocol once the upgrade completes. +final class URLSessionNdtSocket: NSObject, NdtSocket, URLSessionWebSocketDelegate { + private let url: URL + private let subprotocol: String + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var timeout: Task? + private var session: URLSession! + private var socket: URLSessionWebSocketTask! + private var isCancelled = false + private var receivedCloseCode: URLSessionWebSocketTask.CloseCode? + init(url: URL, subprotocol: String) { self.url = url; self.subprotocol = subprotocol } + var normalClosure: Bool { + lock.lock(); let code = receivedCloseCode; let socket = self.socket; lock.unlock() + return code == .normalClosure || socket?.closeCode == .normalClosure + } + + func open() async throws { + try await withTaskCancellationHandler(operation: { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = 10 + // Includes up to 10 s handshake plus the bounded 13 s direction. + config.timeoutIntervalForResource = 25 + let queue = OperationQueue(); queue.maxConcurrentOperationCount = 1 + let session = URLSession(configuration: config, delegate: self, delegateQueue: queue) + let socket = session.webSocketTask(with: url, protocols: [subprotocol]) + socket.maximumMessageSize = 16 * 1_048_576 + let deadline = Task { [weak self] in + do { try await Task.sleep(nanoseconds: 10_000_000_000) } catch { return } + if self?.finishOpen(.failure(URLError(.timedOut))) == true { self?.close() } + } + lock.lock() + self.continuation = continuation; self.session = session; self.socket = socket; self.timeout = deadline + let cancelled = isCancelled + lock.unlock() + if cancelled { deadline.cancel(); finishOpen(.failure(CancellationError())); socket.cancel(); session.invalidateAndCancel(); return } + socket.resume() + } + }, onCancel: { self.close() }) + } + @discardableResult private func finishOpen(_ result: Result) -> Bool { + lock.lock(); let waiting = continuation; continuation = nil; lock.unlock() + waiting?.resume(with: result) + return waiting != nil + } + private func cancelTimeout() { + lock.lock(); let deadline = timeout; timeout = nil; lock.unlock() + deadline?.cancel() + } + func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocolName: String?) { + guard protocolName == subprotocol else { finishOpen(.failure(SpeedFailure.invalidResponse)); close(); return } + cancelTimeout(); finishOpen(.success(())) + } + func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, + didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + lock.lock(); receivedCloseCode = closeCode; lock.unlock() + } + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let error = error { cancelTimeout(); finishOpen(.failure(error)) } + } + func urlSession(_ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } + func receive() async throws -> URLSessionWebSocketTask.Message { try await socket.receive() } + func send(_ message: URLSessionWebSocketTask.Message) async throws { try await socket.send(message) } + func close() { + cancelTimeout() + lock.lock(); isCancelled = true; let socket = self.socket; let session = self.session; lock.unlock() + finishOpen(.failure(CancellationError())) + socket?.cancel(with: .normalClosure, reason: nil) + session?.invalidateAndCancel() + } +} + +final class Ndt7Client { + typealias SocketFactory = (URL, String) -> NdtSocket + private let domain = IosSpeedDomain() + private let http: any SpeedTransport + private let socketFactory: SocketFactory + private let duration: TimeInterval + private let grace: TimeInterval + init(http: any SpeedTransport = SpeedHTTP(), duration: TimeInterval = 10, grace: TimeInterval = 3, + socketFactory: @escaping SocketFactory = { URLSessionNdtSocket(url: $0, subprotocol: $1) }) { + self.http = http; self.duration = duration; self.grace = grace; self.socketFactory = socketFactory + } + func measure() async throws -> SpeedResult { + guard let locate = URL(string: domain.ndtLocateUrl()) else { throw SpeedFailure.invalidServer } + let (data, _) = try await http.read(URLRequest(url: locate), limit: 65_536) + guard let text = String(data: data, encoding: .utf8), let target = domain.ndtTargets(text: text).first, + let downURL = URL(string: target.downloadUrl), let upURL = URL(string: target.uploadUrl) else { + throw SpeedFailure.invalidResponse + } + let down = try await direction(url: downURL, download: true) + let up = try await direction(url: upURL, download: false) + return SpeedResult(downloadMbps: down, uploadMbps: up) + } + func direction(url: URL, download: Bool) async throws -> Double { + let socket = socketFactory(url, domain.ndtSubprotocol()) + defer { socket.close() } + try await socket.open() + let counter = SpeedCounter() + let trace = domain.createTrace() + let start = ProcessInfo.processInfo.systemUptime + let reader = Task { + do { + while !Task.isCancelled { + switch try await socket.receive() { + case .data(let data): + guard download else { counter.fail(); return } + counter.add(Int64(data.count)) + case .string(let text): + if text.utf8.count <= 65_536, + let rate = self.domain.ndtView(text: text, download: download)?.appMbps?.doubleValue, + rate.isFinite && rate >= 0 { counter.setServerMbps(rate) } + @unknown default: counter.fail(); return + } + } + } catch { + if !Task.isCancelled { + let elapsed = ProcessInfo.processInfo.systemUptime - start + let normalDownloadEnd = download && socket.normalClosure && counter.snapshot().0 > 0 && elapsed >= 1 + let normalUploadEnd = !download && socket.normalClosure && counter.serverRate() != nil && elapsed >= self.duration * 0.95 + if normalDownloadEnd || normalUploadEnd { counter.markCompleted() } + else { counter.fail() } + } + } + } + let writer = Task { + guard !download else { return } + let sizer = self.domain.createMessageSizer() + do { + while !Task.isCancelled && ProcessInfo.processInfo.systemUptime - start < self.duration { + let size = Int(sizer.size) + var bytes = Data(count: size) + guard bytes.withUnsafeMutableBytes({ SecRandomCopyBytes(kSecRandomDefault, $0.count, $0.baseAddress!) }) == errSecSuccess else { + counter.fail(); return + } + try await socket.send(.data(bytes)) + counter.add(Int64(size)); sizer.onQueued(bytes: Int32(size)) + } + } catch { + if !Task.isCancelled { + let normalEnd = socket.normalClosure && counter.serverRate() != nil && + ProcessInfo.processInfo.systemUptime - start >= self.duration * 0.95 + if !normalEnd { counter.fail() } + } + } + } + do { + try await withTaskCancellationHandler(operation: { + while ProcessInfo.processInfo.systemUptime - start < duration { + try await Task.sleep(nanoseconds: 250_000_000) + _ = trace.add(elapsedMs: Int64((ProcessInfo.processInfo.systemUptime - start) * 1000), bytes: counter.snapshot().0) + if counter.isCompleted() { break } + } + writer.cancel() + if !counter.isCompleted() { try await Task.sleep(nanoseconds: UInt64(grace * 1_000_000_000)) } + }, onCancel: { socket.close() }) + } catch { + writer.cancel(); reader.cancel(); socket.close() + _ = await writer.result; _ = await reader.result + throw error + } + writer.cancel(); reader.cancel(); socket.close() + _ = await writer.result; _ = await reader.result + let (bytes, failures) = counter.snapshot() + guard failures == 0, bytes > 0, let summary = domain.summarize(trace: trace) else { throw SpeedFailure.incomplete } + if download { return summary.mbps } + guard let serverRate = counter.serverRate() else { throw SpeedFailure.incomplete } + return serverRate + } +} + +@MainActor +final class SpeedViewModel: ObservableObject { + enum Engine: String, CaseIterable { case libre, ndt7 } + @Published var engine: Engine = .libre + @Published var server = "" + @Published var running = false + @Published var failed = false + @Published var result: SpeedResult? + private var task: Task? + + func start() { + guard task == nil else { return } + result = nil; failed = false; running = true + let selected = engine + let input = server + task = Task { + do { + let value: SpeedResult + if selected == .libre { + value = try await LibreSpeedClient().measure(input: input) + } else { + value = try await Ndt7Client().measure() + } + if !Task.isCancelled { self.result = value } + } catch { + if !Task.isCancelled { self.failed = true } + } + self.running = false + self.task = nil + } + } + func cancel() { task?.cancel() } +} + +struct SpeedView: View { + @Environment(\.scenePhase) private var scenePhase + @StateObject private var model = SpeedViewModel() + @State private var showConfirmation = false + var body: some View { + Form { + Picker("speed.engine", selection: $model.engine) { + Text("speed.libre").tag(SpeedViewModel.Engine.libre) + Text("speed.ndt7").tag(SpeedViewModel.Engine.ndt7) + }.disabled(model.running) + if model.engine == .libre { + TextField("speed.server", text: $model.server) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(.URL) + .disabled(model.running) + Text("speed.parallel_warning").font(.footnote) + } else { + Link("speed.privacy_link", destination: URL(string: "https://www.measurementlab.net/privacy/")!) + Text("speed.ndt_method").font(.footnote) + } + if model.running { + ProgressView() + Button("speed.cancel") { model.cancel() } + } else { + Button("speed.start") { showConfirmation = true } + } + if model.failed { Text("speed.error").foregroundStyle(.red) } + if let result = model.result { + LabeledContent("speed.download", value: result.downloadMbps.formatted(.number.precision(.fractionLength(2))) + " Mbit/s") + LabeledContent("speed.upload", value: result.uploadMbps.formatted(.number.precision(.fractionLength(2))) + " Mbit/s") + } + } + .navigationTitle("speed.title") + .confirmationDialog("speed.confirm.title", isPresented: $showConfirmation, titleVisibility: .visible) { + Button("speed.confirm.start") { model.start() } + Button("speed.cancel", role: .cancel) { } + } message: { + if model.engine == .ndt7 { Text("speed.warning.ndt7") } + else { Text("speed.warning.data") } + } + .onChange(of: scenePhase) { _, phase in + if phase == .background { model.cancel() } + } + .onDisappear { model.cancel() } + } +} diff --git a/iosApp/NetKit/SshHostKeyValidator.swift b/iosApp/NetKit/SshHostKeyValidator.swift new file mode 100644 index 0000000..e1ee7ab --- /dev/null +++ b/iosApp/NetKit/SshHostKeyValidator.swift @@ -0,0 +1,105 @@ +import CryptoKit +import Foundation +import NIOCore +import NIOSSH +import NetKitShared + +/// Host-key validation is completed before NIOSSH can authenticate the user. +final class SshHostKeyValidator: NIOSSHClientServerAuthenticationDelegate { + enum Failure: Error { case invalid, changed, rejected, storage, cancelled, timeout } + typealias Confirmation = (_ endpoint: String, _ algorithm: String, _ fingerprint: String, _ previous: TrustedHostKey?, _ repeated: Bool, _ reply: @escaping (Bool) -> Void) -> Void + private let endpoint: String + private let store: SshMetadataStore + private let prompt: Confirmation + private let onFailure: (Failure) -> Void + private let onChanged: (TrustedHostKey, TrustedHostKey) -> Void + private let timeout: TimeInterval + private let lock = NSLock() + private var pending: (UUID, EventLoopPromise)? + private var closed = false + + init(endpoint: String, store: SshMetadataStore, timeout: TimeInterval = 180, + onFailure: @escaping (Failure) -> Void = { _ in }, + onChanged: @escaping (TrustedHostKey, TrustedHostKey) -> Void = { _, _ in }, prompt: @escaping Confirmation) { + self.endpoint = endpoint + self.store = store + self.onFailure = onFailure + self.onChanged = onChanged + self.timeout = timeout + self.prompt = prompt + } + + private func report(_ failure: Failure) { DispatchQueue.main.async { self.onFailure(failure) } } + + func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise promise: EventLoopPromise) { + let parts = String(openSSHPublicKey: hostKey).split(separator: " ", maxSplits: 2) + let allowed = ["ssh-ed25519", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521"] + guard parts.count >= 2, allowed.contains(String(parts[0])), + let blob = Data(base64Encoded: String(parts[1])), !blob.isEmpty, blob.count <= 16_384 else { + promise.fail(Failure.invalid); return + } + let digest = Data(SHA256.hash(data: blob)).base64EncodedString().replacingOccurrences(of: "=", with: "") + let offered = TrustedHostKey(endpoint: endpoint, algorithm: String(parts[0]), + publicKey: String(parts[1]), fingerprint: "SHA256:" + digest) + switch store.decision(offered) { + case .trusted: + lock.lock(); let isClosed = closed; lock.unlock() + if isClosed { promise.fail(Failure.cancelled) } + else { promise.succeed(()) } + case .changed: + let saved = store.snapshot().hostKeys.first { $0.endpoint == offered.endpoint } + try? store.reject(offered) + if let saved { DispatchQueue.main.async { self.onChanged(saved, offered) } } + report(.changed) + promise.fail(Failure.changed) + case .unknown: + let context = store.rejectionContext(offered) + let id = UUID() + lock.lock() + guard !closed, pending == nil else { lock.unlock(); promise.fail(Failure.cancelled); return } + pending = (id, promise) + lock.unlock() + DispatchQueue.main.async { [weak self] in + guard let self, self.isPending(id) else { return } + self.prompt(self.endpoint, offered.algorithm, offered.fingerprint, context.previous, context.repeated) { [weak self] accepted in + self?.answer(id: id, key: offered, accepted: accepted) + } + } + DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in self?.failPending(id: id, reason: .timeout) } + default: promise.fail(Failure.invalid) + } + } + + func cancel() { + lock.lock(); closed = true; let item = pending; pending = nil; lock.unlock() + item?.1.fail(Failure.cancelled) + } + + private func isPending(_ id: UUID) -> Bool { + lock.lock(); defer { lock.unlock() } + return !closed && pending?.0 == id + } + + private func failPending(id: UUID, reason: Failure) { + lock.lock() + guard let item = pending, item.0 == id else { lock.unlock(); return } + pending = nil + lock.unlock() + report(reason) + item.1.fail(reason) + } + + private func answer(id: UUID, key: TrustedHostKey, accepted: Bool) { + lock.lock() + guard let item = pending, item.0 == id, !closed else { lock.unlock(); return } + pending = nil + // Keep the lock through compare-and-insert so cancel cannot race a stale approval. + if accepted { + do { try store.trustUnknown(key); lock.unlock(); item.1.succeed(()) } + catch { lock.unlock(); report(.storage); item.1.fail(Failure.storage) } + } else { + do { try store.reject(key); lock.unlock(); report(.rejected); item.1.fail(Failure.rejected) } + catch { lock.unlock(); report(.storage); item.1.fail(Failure.storage) } + } + } +} diff --git a/iosApp/NetKit/SshKeyboard.swift b/iosApp/NetKit/SshKeyboard.swift new file mode 100644 index 0000000..bb6f92f --- /dev/null +++ b/iosApp/NetKit/SshKeyboard.swift @@ -0,0 +1,81 @@ +import SwiftUI +import UIKit +import NetKitShared + +/// Commits marked text before sanitized paste so terminal input keeps its order. +enum SshTerminalInput { + static func preparePaste(terminal: IosTerminal, value: String) -> (String, String)? { + terminal.composeFinish() + guard let pending = terminal.drainInput() else { return nil } + return (pending, terminal.safePaste(text: value)) + } +} + +/// Keeps marked text local until IME composition is committed. +struct SshKeyboard: UIViewRepresentable { + let inputEpoch: UUID + let onComposition: (String, Bool) -> Void + let onKey: (Bool) -> Void // true = enter, false = backspace + let onPaste: (String) -> Void + + func makeCoordinator() -> Coordinator { Coordinator(parent: self) } + func makeUIView(context: Context) -> TerminalInputView { + let view = TerminalInputView() + view.delegate = context.coordinator + view.onEmptyBackspace = { onKey(false) } + view.onPaste = onPaste + view.autocorrectionType = .no + view.spellCheckingType = .no + view.smartQuotesType = .no + view.smartDashesType = .no + view.autocapitalizationType = .none + view.font = .monospacedSystemFont(ofSize: 16, weight: .regular) + view.accessibilityIdentifier = "sshKeyboard" + return view + } + func updateUIView(_ view: TerminalInputView, context: Context) { + if context.coordinator.inputEpoch != inputEpoch { + context.coordinator.suppressChanges = true + view.unmarkText(); view.text = "" + context.coordinator.suppressChanges = false + context.coordinator.inputEpoch = inputEpoch + } + context.coordinator.parent = self + view.onEmptyBackspace = { onKey(false) } + view.onPaste = onPaste + } + + final class Coordinator: NSObject, UITextViewDelegate { + var parent: SshKeyboard + var inputEpoch: UUID + var suppressChanges = false + init(parent: SshKeyboard) { self.parent = parent; self.inputEpoch = parent.inputEpoch } + func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { + if text == "\n", textView.markedTextRange == nil { parent.onKey(true); return false } + return true + } + func textViewDidChange(_ textView: UITextView) { + guard !suppressChanges else { return } + let text = textView.text ?? "" + if textView.markedTextRange != nil { parent.onComposition(text, true) } + else { + parent.onComposition(text, false) + suppressChanges = true + textView.text = "" + suppressChanges = false + } + } + } +} + +final class TerminalInputView: UITextView { + var onEmptyBackspace: (() -> Void)? + var onPaste: ((String) -> Void)? + override func deleteBackward() { + if text.isEmpty && markedTextRange == nil { onEmptyBackspace?() } + else { super.deleteBackward() } + } + override func paste(_ sender: Any?) { + if let text = UIPasteboard.general.string { onPaste?(text) } + } +} diff --git a/iosApp/NetKit/SshMetadataStore.swift b/iosApp/NetKit/SshMetadataStore.swift new file mode 100644 index 0000000..cd8f515 --- /dev/null +++ b/iosApp/NetKit/SshMetadataStore.swift @@ -0,0 +1,132 @@ +import Foundation +import NetKitShared + +/// Serializes profile and host-key updates, including compare-and-insert after TOFU approval. +final class SshMetadataStore { + enum Failure: Error { case io, invalid, conflict } + private let lock = NSLock() + private let domain: IosSshDomain + private let directory: URL + private var data: SshData + + init(directory: URL? = nil, onFreshInstall: () throws -> Void = {}) throws { + let domain = IosSshDomain() + self.domain = domain + guard let root = directory ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.appendingPathComponent("NetKit", isDirectory: true) else { throw Failure.io } + self.directory = root + let file = root.appendingPathComponent("ssh.json") + do { + let handle = try FileHandle(forReadingFrom: file) + defer { try? handle.close() } + let raw = try handle.read(upToCount: 1_048_577) ?? Data() + guard raw.count <= 1_048_576 else { throw Failure.invalid } + let bytes = KotlinByteArray(size: Int32(raw.count)) + for (index, value) in raw.enumerated() { bytes.set(index: Int32(index), value: Int8(bitPattern: value)) } + let result = domain.decodeData(bytes: bytes) + guard let decoded = result.data, result.failure == nil else { throw Failure.invalid } + self.data = decoded + } catch let failure as Failure { throw failure + } catch { + guard WolPersistence.isMissingFile(error as NSError) else { throw Failure.io } + try onFreshInstall() + self.data = domain.emptyData() + try persist(self.data) + } + } + + func snapshot() -> SshData { + lock.lock(); defer { lock.unlock() } + return data + } + + func decision(_ key: TrustedHostKey) -> HostKeyDecision { + lock.lock(); defer { lock.unlock() } + return domain.hostDecision(data: data, offered: key) + } + + func rejectionContext(_ key: TrustedHostKey) -> (previous: TrustedHostKey?, repeated: Bool) { + lock.lock(); defer { lock.unlock() } + let previous = data.rejectedHostKeys.first { $0.endpoint == key.endpoint } + let distinct = domain.previousRejected(data: data, offered: key) + return (previous, previous != nil && distinct == nil) + } + + func update(_ transform: (SshData) -> IosSshDataResult) throws { + lock.lock(); defer { lock.unlock() } + let result = transform(data) + guard let next = result.data, result.failure == nil else { throw Failure.conflict } + try persist(next) + data = next + } + + func trustUnknown(_ key: TrustedHostKey) throws { + try update { domain.trustUnknown(data: $0, offered: key) } + } + + func reject(_ key: TrustedHostKey) throws { + try update { domain.recordRejected(data: $0, offered: key) } + } + + func forget(endpoint: String) throws { + try update { domain.forgetHost(data: $0, endpoint: endpoint) } + } + + func save(profile: SshProfile, withCredential updated: SshProfile? = nil) throws { + try update { current in + let first = domain.upsertProfile(data: current, profile: profile) + guard let updated, let intermediate = first.data, first.failure == nil else { return first } + return domain.upsertProfile(data: intermediate, profile: updated) + } + } + + func save(key: SshKeyInfo) throws { + try update { domain.upsertKey(data: $0, key: key) } + } + + func deleteProfile(id: String) throws { try update { domain.deleteProfile(data: $0, id: id) } } + func deleteKey(id: String) throws { try update { domain.deleteKey(data: $0, id: id) } } + + func moveProfile(id: String, delta: Int32) throws { + try update { domain.moveProfile(data: $0, id: id, delta: delta) } + } + + func prepareExport() -> IosSshExportResult { + lock.lock(); defer { lock.unlock() } + return domain.prepareExport(data: data) + } + + func previewImport(_ raw: Data, keyRef: String? = nil) throws -> SshImportPlan { + guard raw.count <= 256 * 1024 else { throw Failure.invalid } + let bytes = KotlinByteArray(size: Int32(raw.count)) + for (index, value) in raw.enumerated() { bytes.set(index: Int32(index), value: Int8(bitPattern: value)) } + guard let parsed = domain.decodeImport(bytes: bytes).imported else { throw Failure.invalid } + return try planImport(parsed, keyRef: keyRef) + } + + func planImport(_ imported: SshProfileImport, keyRef: String?) throws -> SshImportPlan { + lock.lock(); defer { lock.unlock() } + if let keyRef, !data.keys.contains(where: { $0.id == keyRef }) { throw Failure.invalid } + guard let plan = domain.planImport(current: data, imported: imported, keyRef: keyRef, + generateId: { UUID().uuidString }).plan else { throw Failure.invalid } + return plan + } + + func applyImport(_ plan: SshImportPlan) throws { + lock.lock(); defer { lock.unlock() } + guard let next = domain.applyImport(current: data, plan: plan).data else { throw Failure.conflict } + try persist(next) + data = next + } + + private func persist(_ value: SshData) throws { + guard let encoded = domain.encodeData(data: value) else { throw Failure.invalid } + let bytes = Data((0.. some View { + HStack(spacing: 0) { + ForEach(Array(row.runs.enumerated()), id: \.offset) { _, run in + Text(verbatim: run.text) + .font(.system(size: 14, weight: run.bold ? .bold : .regular, design: .monospaced)) + .foregroundStyle(color(run.foreground)) + .background(color(run.background)) + .fixedSize() + } + } + .frame(height: cellHeight, alignment: .leading) + .overlay(alignment: .topLeading) { + if let cursor { + Rectangle().stroke(Color.white, lineWidth: 1) + .frame(width: cellWidth, height: cellHeight) + .offset(x: CGFloat(cursor) * cellWidth) + .accessibilityHidden(true) + } + } + } + + private func color(_ value: Int32) -> Color { + let n = Int(value) + if n & 0x1000000 != 0 { + return Color(red: Double((n >> 16) & 255) / 255, green: Double((n >> 8) & 255) / 255, blue: Double(n & 255) / 255) + } + let basic: [(Double, Double, Double)] = [ + (0, 0, 0), (0.67, 0, 0), (0, 0.67, 0), (0.67, 0.33, 0), + (0, 0, 0.67), (0.67, 0, 0.67), (0, 0.67, 0.67), (0.75, 0.75, 0.75), + (0.33, 0.33, 0.33), (1, 0.33, 0.33), (0.33, 1, 0.33), (1, 1, 0.33), + (0.33, 0.33, 1), (1, 0.33, 1), (0.33, 1, 1), (1, 1, 1) + ] + if (0..<16).contains(n) { let c = basic[n]; return Color(red: c.0, green: c.1, blue: c.2) } + if (16..<232).contains(n) { + let index = n - 16 + let levels: [Double] = [0, 95, 135, 175, 215, 255] + return Color(red: levels[index / 36] / 255, green: levels[(index / 6) % 6] / 255, blue: levels[index % 6] / 255) + } + let gray = Double(8 + min(23, max(0, n - 232)) * 10) / 255 + return Color(red: gray, green: gray, blue: gray) + } +} diff --git a/iosApp/NetKit/SshTransport.swift b/iosApp/NetKit/SshTransport.swift new file mode 100644 index 0000000..86ae674 --- /dev/null +++ b/iosApp/NetKit/SshTransport.swift @@ -0,0 +1,275 @@ +import CryptoKit +import Foundation +import NIOCore +import NIOPosix +import NIOSSH + +enum SshCredential { + case password(String) + case ed25519(Data) +} + +enum SshTransportFailure: Error { case invalidCredential, unavailable, rejected, timeout, closed, protocolError } + +func sshAlgorithmNegotiationFailure(_ type: NIOSSHError.ErrorType) -> Bool { + type == .unknownPublicKey || type == .unknownSignature || type == .keyExchangeNegotiationFailure +} + +func sshSupportedCredentialKey(_ publicKey: String) -> Bool { + publicKey.hasPrefix("ssh-ed25519 ") +} + +private final class SshAuthentication: NIOSSHClientUserAuthenticationDelegate { + private let username: String + private var offer: NIOSSHUserAuthenticationOffer.Offer? + init(username: String, credential: SshCredential) throws { + self.username = username + switch credential { + case .password(let password): offer = .password(.init(password: password)) + case .ed25519(let bytes): + let key = try Curve25519.Signing.PrivateKey(rawRepresentation: bytes) + offer = .privateKey(.init(privateKey: NIOSSHPrivateKey(ed25519Key: key))) + } + } + func nextAuthenticationType(availableMethods: NIOSSHAvailableUserAuthenticationMethods, + nextChallengePromise: EventLoopPromise) { + guard let offer else { nextChallengePromise.succeed(nil); return } + self.offer = nil + switch offer { + case .password where !availableMethods.contains(.password): nextChallengePromise.succeed(nil) + case .privateKey where !availableMethods.contains(.publicKey): nextChallengePromise.succeed(nil) + default: nextChallengePromise.succeed(.init(username: username, serviceName: "", offer: offer)) + } + } +} + +/// A single bounded connection; no background thread blocks the UI or logs raw provider errors. +final class SshTransport { + enum State { case connected, closed, failed, algorithmFailure } + private let group: MultiThreadedEventLoopGroup + private let lock = NSLock() + private var closed = false + private var parent: Channel? + private var child: Channel? + private var pendingWriteBytes = 0 + private var terminalIsReady = false + private var handshakeTimeout: DispatchWorkItem? + private var shellTimeout: DispatchWorkItem? + private let validator: SshHostKeyValidator + private let auth: SshAuthentication + private let host: String + private let port: Int + private let output: (Data) -> Void + private let state: (State) -> Void + + init(host: String, port: Int, username: String, credential: SshCredential, + validator: SshHostKeyValidator, output: @escaping (Data) -> Void, + state: @escaping (State) -> Void) throws { + let auth = try SshAuthentication(username: username, credential: credential) + self.host = host; self.port = port; self.validator = validator + self.auth = auth + self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + self.output = output; self.state = state + } + + func start() { + let timeout = DispatchWorkItem { [weak self] in self?.fail() } + lock.lock() + guard !closed, handshakeTimeout == nil else { lock.unlock(); return } + handshakeTimeout = timeout + lock.unlock() + DispatchQueue.main.asyncAfter(deadline: .now() + 600, execute: timeout) + let bootstrap = ClientBootstrap(group: group) + .connectTimeout(.seconds(15)) + .channelInitializer { [weak self, auth, validator] channel in + let handler = NIOSSHHandler(role: .client(.init(userAuthDelegate: auth, serverAuthDelegate: validator)), + allocator: channel.allocator, inboundChildChannelInitializer: nil) + return channel.pipeline.addHandler(handler).flatMap { + channel.pipeline.addHandler(SshParentErrorHandler { [weak self] error in + if let error = error as? NIOSSHError, sshAlgorithmNegotiationFailure(error.type) { + self?.terminate(.algorithmFailure) + } else { self?.fail() } + }) + } + } + bootstrap.connect(host: host, port: port).whenComplete { [weak self] result in + guard let self else { if case .success(let channel) = result { channel.close(promise: nil) }; return } + switch result { + case .failure: self.fail() + case .success(let channel): + self.lock.lock() + guard !self.closed else { self.lock.unlock(); channel.close(promise: nil); return } + self.parent = channel + self.lock.unlock() + channel.closeFuture.whenComplete { [weak self] _ in self?.finishClosed() } + channel.pipeline.handler(type: NIOSSHHandler.self).flatMap { handler in + let promise = channel.eventLoop.makePromise(of: Channel.self) + handler.createChannel(promise, channelType: .session) { child, type in + guard type == .session else { return child.eventLoop.makeFailedFuture(SshTransportFailure.protocolError) } + let terminal = SshTerminalHandler(output: self.output, + ready: { [weak self] in self?.terminalReady() }, + failed: { [weak self] in self?.fail() }) + return child.pipeline.addHandler(terminal) + } + return promise.futureResult + }.whenComplete { [weak self] outcome in + guard let self else { return } + switch outcome { + case .failure: self.fail() + case .success(let child): + self.lock.lock() + if self.closed { self.lock.unlock(); child.close(promise: nil); return } + self.child = child + let ready = self.terminalIsReady + let timeout = ready ? nil : DispatchWorkItem { [weak self] in self?.fail() } + self.shellTimeout = timeout + self.lock.unlock() + child.closeFuture.whenComplete { [weak self] _ in self?.finishClosed() } + if ready { self.notify(.connected) } + if let timeout { DispatchQueue.main.asyncAfter(deadline: .now() + 20, execute: timeout) } + } + } + } + } + } + + func send(_ text: String) -> Bool { + guard text.utf8.count <= 16_384 else { return false } + let size = text.utf8.count + lock.lock() + guard !closed, let channel = child, channel.isActive, channel.isWritable, + pendingWriteBytes + size <= 65_536 else { lock.unlock(); return false } + pendingWriteBytes += size + lock.unlock() + var buffer = channel.allocator.buffer(capacity: size) + buffer.writeString(text) + let promise = channel.eventLoop.makePromise(of: Void.self) + promise.futureResult.whenComplete { [weak self] result in + guard let self else { return } + self.lock.lock(); self.pendingWriteBytes -= size; self.lock.unlock() + if case .failure = result { self.fail() } + } + channel.writeAndFlush(SSHChannelData(type: .channel, data: .byteBuffer(buffer)), promise: promise) + return true + } + + func resize(columns: Int, rows: Int) { + guard (10...240).contains(columns), (2...100).contains(rows) else { return } + lock.lock(); let channel = child; let ended = closed; lock.unlock() + guard !ended, let channel else { return } + channel.triggerUserOutboundEvent(SSHChannelRequestEvent.WindowChangeRequest( + terminalCharacterWidth: columns, terminalRowHeight: rows, terminalPixelWidth: 0, terminalPixelHeight: 0), promise: nil) + } + + func close() { terminate(nil) } + + private func terminate(_ terminalState: State?) { + lock.lock() + guard !closed else { lock.unlock(); return } + closed = true; let parent = self.parent; let child = self.child + handshakeTimeout?.cancel(); handshakeTimeout = nil + shellTimeout?.cancel(); shellTimeout = nil + self.parent = nil; self.child = nil + lock.unlock() + validator.cancel() + child?.close(promise: nil); parent?.close(promise: nil) + group.shutdownGracefully { _ in } + if let terminalState { notify(terminalState) } + } + + private func terminalReady() { + lock.lock() + guard !closed else { lock.unlock(); return } + terminalIsReady = true + handshakeTimeout?.cancel(); handshakeTimeout = nil + shellTimeout?.cancel(); shellTimeout = nil + let hasChild = child != nil + lock.unlock() + if hasChild { notify(.connected) } + } + private func fail() { terminate(.failed) } + private func finishClosed() { + lock.lock(); let wasConnected = terminalIsReady && child != nil; lock.unlock() + terminate(wasConnected ? .closed : .failed) + } + private func notify(_ value: State) { + DispatchQueue.main.async { + if case .connected = value { + self.lock.lock(); let ended = self.closed; self.lock.unlock() + if ended { return } + } + self.state(value) + } + } +} + +/// Errors before child-channel creation must close the parent and report failure. +private final class SshParentErrorHandler: ChannelInboundHandler { + typealias InboundIn = Any + private let failed: (Error) -> Void + init(failed: @escaping (Error) -> Void) { self.failed = failed } + func errorCaught(context: ChannelHandlerContext, error: Error) { + failed(error) + context.close(promise: nil) + } +} + +private final class SshTerminalHandler: ChannelInboundHandler { + typealias InboundIn = SSHChannelData + private let output: (Data) -> Void + private let ready: () -> Void + private let failed: () -> Void + private var stage = 0 + private let deliveryLock = NSLock() + private var pendingBytes = 0 + + init(output: @escaping (Data) -> Void, ready: @escaping () -> Void, failed: @escaping () -> Void) { + self.output = output; self.ready = ready; self.failed = failed + } + func channelActive(context: ChannelHandlerContext) { + context.triggerUserOutboundEvent(SSHChannelRequestEvent.PseudoTerminalRequest( + wantReply: true, term: "xterm", terminalCharacterWidth: 80, terminalRowHeight: 24, + terminalPixelWidth: 0, terminalPixelHeight: 0, terminalModes: SSHTerminalModes([:])), promise: nil) + } + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { + if event is ChannelFailureEvent { failed(); context.close(promise: nil); return } + guard event is ChannelSuccessEvent else { context.fireUserInboundEventTriggered(event); return } + if stage == 0 { + stage = 1 + context.triggerUserOutboundEvent(SSHChannelRequestEvent.ShellRequest(wantReply: true), promise: nil) + } else if stage == 1 { stage = 2; ready() } + } + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let message = unwrapInboundIn(data) + guard case .byteBuffer(let bytes) = message.data, bytes.readableBytes <= 131_072 else { + failed(); context.close(promise: nil); return + } + let chunk = Data(bytes.readableBytesView) + deliveryLock.lock() + guard pendingBytes + chunk.count <= 524_288 else { + deliveryLock.unlock(); failed(); context.close(promise: nil); return + } + pendingBytes += chunk.count + deliveryLock.unlock() + // One pending delivery at a time avoids an unbounded main-queue backlog. + context.channel.setOption(ChannelOptions.autoRead, value: false).whenComplete { _ in + DispatchQueue.main.async { + self.output(chunk) + self.deliveryLock.lock(); self.pendingBytes -= chunk.count; self.deliveryLock.unlock() + context.eventLoop.execute { if context.channel.isActive { context.read() } } + } + } + } + func errorCaught(context: ChannelHandlerContext, error: Error) { failed(); context.close(promise: nil) } +} + +import NetKitShared + +final class SshSessionAdapter: NSObject, SshSession { + private let transport: SshTransport + init(transport: SshTransport) { self.transport = transport } + func send(text: String) -> Bool { transport.send(text) } + func resize(columns: Int32, rows: Int32) { transport.resize(columns: Int(columns), rows: Int(rows)) } + func close() { transport.close() } + deinit { transport.close() } +} diff --git a/iosApp/NetKit/SshView.swift b/iosApp/NetKit/SshView.swift new file mode 100644 index 0000000..80f2675 --- /dev/null +++ b/iosApp/NetKit/SshView.swift @@ -0,0 +1,543 @@ +import SwiftUI +import Foundation +import NetKitShared +import UniformTypeIdentifiers + +private struct ProfileEdit: Identifiable { + let id = UUID() + let profile: SshProfile? +} + +/// The exporter owns a validated snapshot; no empty fallback document is constructed. +struct SshProfileDocument: FileDocument { + static var readableContentTypes: [UTType] { [.json] } + let contents: Data + init(contents: Data) { self.contents = contents } + init(configuration: ReadConfiguration) throws { + guard let contents = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) } + self.contents = contents + } + func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { + FileWrapper(regularFileWithContents: contents) + } +} + +/// Authentication is explicit. An imported INTERACTIVE profile starts with no supported choice. +struct SshProfileDraft { + var name: String + var host: String + var port: String + var username: String + var authenticationChoice: String + var keyRef: String + init(profile: SshProfile?) { + name = profile?.name ?? ""; host = profile?.host ?? ""; port = profile.map { String($0.port) } ?? "22" + username = profile?.username ?? ""; keyRef = profile?.keyRef ?? "" + authenticationChoice = profile?.authentication == .interactive ? "" : profile?.authentication == .key ? "KEY" : "PASSWORD" + } + var authentication: SshAuthentication? { + switch authenticationChoice { case "PASSWORD": .password; case "KEY": .key; default: nil } + } + func needsKeySelection(keys: [SshKeyInfo]) -> Bool { + authentication == .key && !keys.contains { $0.id == keyRef } + } +} + +func sshAuthenticationName(_ value: String) -> String { + switch value { + case "PASSWORD": String(localized: "ssh.password") + case "KEY": String(localized: "ssh.authentication.key") + default: String(localized: "ssh.authentication.interactive") + } +} + +func sshExportFailureMessage(_ failure: SshViewModel.ExportFailure) -> String { + switch failure { + case .duplicateNames(let names): String(localized: "ssh.export.duplicate.names") + "\n" + names.joined(separator: ", ") + case .tooLarge: String(localized: "ssh.export.too.large") + case .invalid: String(localized: "ssh.error.invalid") + } +} + +func errorKey(_ error: SshViewModel.ErrorKind) -> String { + switch error { + case .storage: "ssh.error.storage" + case .invalid: "ssh.error.invalid" + case .credentials: "ssh.error.credentials" + case .keyInUse: "ssh.error.key.in.use" + case .connection: "ssh.error.connection" + case .algorithm: "ssh.error.algorithm" + case .unsupportedCredential: "ssh.error.unsupported_credential" + case .interactiveUnsupported: "ssh.interactive.unsupported" + case .hostChanged: "ssh.error.host.changed" + case .hostRejected: "ssh.error.host.rejected" + case .timeout: "ssh.error.timeout" + case .inputOverflow: "ssh.error.input" + } +} + +@MainActor +func sshHostPromptMessage(_ prompt: SshViewModel.HostPrompt) -> String { + var text = "\(prompt.endpoint)\n\(prompt.algorithm)\n\(prompt.fingerprint)" + if let previous = prompt.previousRejected { + text += "\n\(String(localized: "ssh.host.previously.rejected"))\n\(previous)" + if prompt.repeatedRejected { text += "\n\(String(localized: "ssh.host.rejected.again"))" } + } + return text +} + +struct SshView: View { + @ObservedObject var model: SshViewModel + @State private var editing: ProfileEdit? + @State private var showImporter = false + @State private var showExporter = false + @State private var exportDocument: SshProfileDocument? + #if DEBUG && targetEnvironment(simulator) + @State private var capturedUIExport: String? + #endif + @State private var reconnecting: SshProfile? + @State private var showImportConfirm = false + @State private var control = false + @State private var followOutput = true + @State private var keyboardReset = UUID() + @State private var keyName = "" + @State private var pendingPaste: String? + @State private var showPasteConfirm = false + @State private var resetEndpoint: String? + @State private var showReset = false + @State private var deleteProfile: SshProfile? + @State private var deleteKey: SshKeyInfo? + @State private var columns = 80 + @State private var rows = 24 + + var body: some View { + Form { + Text("ssh.notice") + if let error = model.error { + Section { + Text(LocalizedStringKey(errorKey(error))).foregroundStyle(.red).accessibilityIdentifier("ssh.error") + Button("ssh.ok") { model.error = nil } + } + } + if model.profileUnavailable { + Section { + Text("ssh.profile.unavailable").foregroundStyle(.red).accessibilityIdentifier("ssh.profile.unavailable") + Button("ssh.ok") { model.profileUnavailable = false } + } + } + if let failure = model.exportFailure { + Section("ssh.export.failed") { + Text(verbatim: sshExportFailureMessage(failure)).foregroundStyle(.red).accessibilityIdentifier("ssh.export.error") + Button("ssh.ok") { model.exportFailure = nil } + } + } + if let changed = model.changedHost { + Section("ssh.host.changed.context") { + Text(verbatim: changed.endpoint) + LabeledContent("ssh.host.saved", value: changed.saved) + LabeledContent("ssh.host.offered", value: changed.offered) + Button("ssh.ok") { model.changedHost = nil; if model.error == .hostChanged { model.error = nil } } + } + } + Section("ssh.profiles") { + Button("ssh.add") { editing = ProfileEdit(profile: nil) }.accessibilityIdentifier("ssh.add") + Button("ssh.import") { requestImport() }.accessibilityIdentifier("ssh.import") + Button("ssh.export") { + #if DEBUG && targetEnvironment(simulator) + capturedUIExport = nil + #endif + if let prepared = model.prepareExport() { + #if DEBUG && targetEnvironment(simulator) + // Opt-in UI tests inspect the actual validated bytes without involving Files. + if ProcessInfo.processInfo.arguments.contains("-netkit-ui-capture-ssh-export") { + guard let json = String(data: prepared, encoding: .utf8) else { model.error = .invalid; return } + capturedUIExport = json; model.cancelExport(); return + } + #endif + exportDocument = SshProfileDocument(contents: prepared); showExporter = true + } + }.accessibilityIdentifier("ssh.export") + #if DEBUG && targetEnvironment(simulator) + if let capturedUIExport { + Text(verbatim: "Captured SSH export") + .accessibilityValue(Text(verbatim: capturedUIExport)) + .accessibilityIdentifier("ssh.ui.export.capture") + } + #endif + if let profiles = model.data?.profiles { + ForEach(profiles, id: \.id) { profile in profileRow(profile) } + if profiles.isEmpty { Text("ssh.empty") } + } + }.disabled(model.busy) + Section("ssh.keys") { + TextField("ssh.key.name", text: $keyName) + Button("ssh.key.generate") { model.generateKey(name: keyName); keyName = "" } + ForEach(model.data?.keys ?? [], id: \.id) { key in + HStack { + Text(verbatim: key.name) + Spacer() + Button(role: .destructive) { deleteKey = key } label: { Image(systemName: "trash") } + .accessibilityLabel("ssh.key.delete") + } + } + if let publicKey = model.publicKey { + Text(verbatim: publicKey).textSelection(.enabled) + Button("ssh.key.copy") { UIPasteboard.general.setItems([[UTType.utf8PlainText.identifier: publicKey]], options: [.localOnly: true, .expirationDate: Date().addingTimeInterval(60)]) } + } + } + if let keys = model.data?.hostKeys, !keys.isEmpty { + Section("ssh.trusted") { + ForEach(keys, id: \.endpoint) { key in + Button { resetEndpoint = key.endpoint; showReset = true } label: { + VStack(alignment: .leading) { + Text(verbatim: key.endpoint) + LabeledContent("ssh.host.saved", value: key.fingerprint) + if let rejected = model.data?.rejectedHostKeys.first(where: { $0.endpoint == key.endpoint }) { + LabeledContent("ssh.host.offered", value: rejected.fingerprint) + } + } + } + } + } + } + Section("ssh.terminal") { + Toggle("ssh.follow", isOn: $followOutput) + ScrollViewReader { proxy in + ScrollView([.horizontal, .vertical]) { + if let snapshot = model.terminalSnapshot { SshTerminalRows(snapshot: snapshot) } + } + .frame(minHeight: 160, maxHeight: 300) + .onChange(of: model.terminalRevision) { _, _ in + if followOutput { proxy.scrollTo("ssh-terminal-bottom", anchor: .bottom) } + } + } + if let profile = model.reconnectProfile, !model.connected { + Button("ssh.reconnect") { reconnecting = profile }.accessibilityIdentifier("ssh.reconnect") + } + if model.connected { + SshKeyboard(inputEpoch: keyboardReset, onComposition: { value, marked in + model.composition(value, marked: marked, control: control) + if !marked { control = false } + }, onKey: { enter in sendKey(enter ? .enter : .backspace) }, onPaste: { value in + if model.pasteNeedsConfirmation(value) { pendingPaste = value; showPasteConfirm = true } + else { model.paste(value); keyboardReset = UUID() } + }).frame(height: 44) + HStack { + Toggle("ssh.ctrl", isOn: $control).toggleStyle(.button) + Button("ssh.esc") { sendKey(.escape) } + Button("←") { sendKey(.left) }.accessibilityLabel("ssh.left") + Button("↑") { sendKey(.up) }.accessibilityLabel("ssh.up") + Button("↓") { sendKey(.down) }.accessibilityLabel("ssh.down") + Button("→") { sendKey(.right) }.accessibilityLabel("ssh.right") + } + Stepper(value: $columns, in: 10...240, step: 10) { LabeledContent("ssh.columns", value: String(columns)) } + Stepper(value: $rows, in: 2...100, step: 2) { LabeledContent("ssh.rows", value: String(rows)) } + Button("ssh.resize") { model.resize(columns: columns, rows: rows) } + Button("ssh.copy") { model.copyTerminal() } + Button("ssh.disconnect") { model.disconnect() } + } + } + } + .navigationTitle("tab.ssh") + .sheet(item: $editing) { item in + SshProfileEditor(model: model, profile: item.profile) + } + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in + switch result { + case .success(let url): model.previewImport(url); showImportConfirm = model.importPlan != nil + case .failure(let error): if !isUserCancellation(error) { model.error = .invalid } + } + } + .fileExporter(isPresented: $showExporter, document: exportDocument, contentType: .json, + defaultFilename: "netkit-ssh-profiles.json") { result in + if case .failure(let error) = result, !isUserCancellation(error) { model.error = .storage } + exportDocument = nil; model.cancelExport() + } + .alert("ssh.key.required.title", isPresented: Binding(get: { model.keySelectionRequired != nil }, + set: { if !$0 { model.keySelectionRequired = nil } }), presenting: model.keySelectionRequired) { presented in + Button("ssh.edit") { + if let profile = model.profileForKeySelection(presented) { editing = ProfileEdit(profile: profile) } + } + Button("ssh.ok", role: .cancel) { model.keySelectionRequired = nil } + } message: { profile in + Text(verbatim: profile.name + "\n" + String(localized: "ssh.key.required.message")) + } + .alert("ssh.host.first", isPresented: Binding(get: { model.hostPrompt != nil }, set: { _ in }), presenting: model.hostPrompt) { prompt in + Button("ssh.host.accept") { model.answerHost(id: prompt.id, accept: true) } + Button("ssh.host.reject", role: .cancel) { model.answerHost(id: prompt.id, accept: false) } + } message: { prompt in + Text(verbatim: sshHostPromptMessage(prompt)) + } + .sheet(isPresented: $showImportConfirm, onDismiss: { model.cancelImport() }) { + SshImportPreviewView(model: model) + } + .confirmationDialog("ssh.reconnect.confirm", isPresented: Binding(get: { reconnecting != nil }, + set: { if !$0 { reconnecting = nil } }), titleVisibility: .visible, presenting: reconnecting) { profile in + Button("ssh.reconnect") { model.reconnect(profile); reconnecting = nil } + Button("network.cancel", role: .cancel) { reconnecting = nil } + } message: { profile in + Text(verbatim: "\(profile.username)@\(profile.endpoint)" + + (profile.startupCommand.isEmpty ? "" : "\n" + String(localized: "ssh.startup.command") + ": " + profile.startupCommand)) + } + .confirmationDialog("ssh.paste.warning", isPresented: $showPasteConfirm, titleVisibility: .visible) { + Button("ssh.paste.confirm") { if let text = pendingPaste { model.paste(text); keyboardReset = UUID() }; pendingPaste = nil } + Button("network.cancel", role: .cancel) { pendingPaste = nil } + } + .confirmationDialog("ssh.trust.reset.warning", isPresented: $showReset, titleVisibility: .visible) { + Button("ssh.trust.reset", role: .destructive) { if let endpoint = resetEndpoint { model.resetTrust(endpoint: endpoint) }; resetEndpoint = nil } + Button("network.cancel", role: .cancel) { resetEndpoint = nil } + } message: { + if let endpoint = resetEndpoint, let key = model.data?.hostKeys.first(where: { $0.endpoint == endpoint }) { + Text(verbatim: trustResetMessage(key, rejected: model.data?.rejectedHostKeys.first(where: { $0.endpoint == endpoint }))) + } + } + .confirmationDialog("ssh.profile.delete.confirm", isPresented: Binding(get: { deleteProfile != nil }, set: { if !$0 { deleteProfile = nil } }), titleVisibility: .visible, presenting: deleteProfile) { profile in + Button("ssh.profile.delete", role: .destructive) { model.deleteProfile(profile); deleteProfile = nil } + Button("network.cancel", role: .cancel) { deleteProfile = nil } + } + .confirmationDialog("ssh.key.delete.confirm", isPresented: Binding(get: { deleteKey != nil }, set: { if !$0 { deleteKey = nil } }), titleVisibility: .visible, presenting: deleteKey) { key in + Button("ssh.key.delete", role: .destructive) { model.deleteKey(key); deleteKey = nil } + Button("network.cancel", role: .cancel) { deleteKey = nil } + } + } + + private func trustResetMessage(_ key: TrustedHostKey, rejected: TrustedHostKey?) -> String { + var text = "\(key.endpoint)\n\(String(localized: "ssh.host.saved")): \(key.fingerprint)" + if let rejected { text += "\n\(String(localized: "ssh.host.offered")): \(rejected.fingerprint)" } + return text + } + + private func sendKey(_ key: TerminalKey) { + model.key(key, control: control) + control = false + keyboardReset = UUID() + } + + private func profileRow(_ profile: SshProfile) -> some View { + VStack(alignment: .leading, spacing: 8) { + Button { model.connect(profile) } label: { + VStack(alignment: .leading) { + Text(verbatim: profile.name).font(.headline) + Text(verbatim: "\(profile.username)@\(profile.endpoint)").font(.caption).foregroundStyle(.secondary) + } + }.disabled(model.connected) + .accessibilityLabel(Text(verbatim: profile.name + ", " + profile.username + "@" + profile.endpoint)) + .accessibilityIdentifier("ssh.connect.\(profile.id)") + if profile.authentication == .interactive { + Text("ssh.interactive.unsupported").foregroundStyle(.orange).accessibilityIdentifier("ssh.interactive.\(profile.id)") + } + HStack { + Button("ssh.edit") { editing = ProfileEdit(profile: profile) } + .disabled(model.connected).accessibilityIdentifier("ssh.edit.\(profile.id)") + Spacer() + Button { model.moveProfile(id: profile.id, delta: -1) } label: { Image(systemName: "arrow.up").frame(minWidth: 44, minHeight: 44) } + .disabled(!model.canMoveProfile(id: profile.id, delta: -1)) + .accessibilityLabel(String(format: String(localized: "ssh.move.up"), profile.name)) + .accessibilityIdentifier("ssh.move.up.\(profile.id)") + Button { model.moveProfile(id: profile.id, delta: 1) } label: { Image(systemName: "arrow.down").frame(minWidth: 44, minHeight: 44) } + .disabled(!model.canMoveProfile(id: profile.id, delta: 1)) + .accessibilityLabel(String(format: String(localized: "ssh.move.down"), profile.name)) + .accessibilityIdentifier("ssh.move.down.\(profile.id)") + Button(role: .destructive) { deleteProfile = profile } label: { Image(systemName: "trash").frame(minWidth: 44, minHeight: 44) } + .accessibilityLabel("ssh.profile.delete").accessibilityIdentifier("ssh.delete.\(profile.id)") + } + }.buttonStyle(.borderless) + } + + private func requestImport() { + #if DEBUG && targetEnvironment(simulator) + if let fixture = model.uiImportURL { + model.previewImport(fixture); showImportConfirm = model.importPlan != nil; return + } + #endif + showImporter = true + } + + private func isUserCancellation(_ error: Error) -> Bool { + (error as NSError).domain == NSCocoaErrorDomain && (error as NSError).code == NSUserCancelledError + } +} + +private struct SshProfileEditor: View { + private enum Field: Hashable { case name, host, port, username, password } + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: SshViewModel + let profile: SshProfile? + @State private var draft: SshProfileDraft + @State private var password = "" + @State private var failed = false + @State private var showKeyCreator = false + @FocusState private var focusedField: Field? + + init(model: SshViewModel, profile: SshProfile?) { + self.model = model; self.profile = profile + var initial = SshProfileDraft(profile: profile) + if initial.needsKeySelection(keys: model.data?.keys ?? []) { initial.keyRef = "" } + _draft = State(initialValue: initial) + } + var body: some View { + NavigationStack { + Form { + TextField("ssh.name", text: $draft.name).focused($focusedField, equals: .name).accessibilityIdentifier("ssh.editor.name") + TextField("ssh.host", text: $draft.host).focused($focusedField, equals: .host).textInputAutocapitalization(.never).autocorrectionDisabled().accessibilityIdentifier("ssh.editor.host") + TextField("lan.port", text: $draft.port).focused($focusedField, equals: .port).keyboardType(.numberPad).accessibilityIdentifier("ssh.editor.port") + TextField("ssh.user", text: $draft.username).focused($focusedField, equals: .username).textInputAutocapitalization(.never).autocorrectionDisabled() + if profile?.authentication == .interactive { Text("ssh.interactive.unsupported").foregroundStyle(.orange) } + Picker("ssh.authentication", selection: $draft.authenticationChoice) { + if draft.authenticationChoice.isEmpty { Text("ssh.authentication.choose").tag("") } + Text("ssh.password").tag("PASSWORD") + Text("ssh.authentication.key").tag("KEY") + }.pickerStyle(.menu).accessibilityIdentifier("ssh.editor.authentication") + if draft.authentication == .key { + Picker("ssh.authentication.key", selection: $draft.keyRef) { + Text("ssh.key.choose").tag("") + ForEach(model.data?.keys ?? [], id: \.id) { Text(verbatim: $0.name).tag($0.id) } + }.pickerStyle(.menu).accessibilityIdentifier("ssh.editor.key") + if draft.needsKeySelection(keys: model.data?.keys ?? []) { + Text("ssh.key.required.message").foregroundStyle(.orange).accessibilityIdentifier("ssh.editor.key.required") + } + Button("ssh.key.generate") { password = ""; showKeyCreator = true }.accessibilityIdentifier("ssh.editor.create.key") + } else if draft.authentication == .password { + SecureField("ssh.password", text: $password).focused($focusedField, equals: .password).textContentType(.password) + } + Button("ssh.save") { + guard let authentication = draft.authentication else { return } + if model.saveProfile(id: profile?.id, name: draft.name, host: draft.host, port: draft.port, username: draft.username, + keyRef: authentication == .key ? draft.keyRef : nil, password: password, authentication: authentication) { + password = ""; dismiss() + } else { failed = true } + }.disabled(model.busy || draft.authentication == nil || draft.needsKeySelection(keys: model.data?.keys ?? [])) + .accessibilityIdentifier("ssh.editor.save") + if failed { + Text(LocalizedStringKey(model.profileUnavailable ? "ssh.profile.unavailable" : errorKey(model.error ?? .invalid))) + .foregroundStyle(.red).accessibilityIdentifier("ssh.editor.error") + Button("ssh.ok") { failed = false; model.error = nil } + } + } + .accessibilityIdentifier("ssh.editor.form") + .onAppear { model.error = nil; failed = false } + .navigationTitle("ssh.profile") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("network.cancel") { password = ""; dismiss() } } + ToolbarItemGroup(placement: .keyboard) { + Spacer() + Button("ssh.keyboard.done") { focusedField = nil }.accessibilityIdentifier("ssh.editor.keyboard.done") + } + } + .onChange(of: draft.authenticationChoice) { _, _ in password = "" } + .onDisappear { password = "" } + .sheet(isPresented: $showKeyCreator) { + SshKeyCreator(model: model) { id in draft.keyRef = id } + } + } + } +} + +private struct SshKeyCreator: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: SshViewModel + let created: (String) -> Void + @State private var name = "" + var body: some View { + NavigationStack { + Form { + TextField("ssh.key.name", text: $name).accessibilityIdentifier("ssh.creator.name") + Button("ssh.key.generate") { + let previous = Set(model.data?.keys.map(\.id) ?? []) + model.generateKey(name: name) + if let key = model.data?.keys.first(where: { !previous.contains($0.id) }) { created(key.id); dismiss() } + }.disabled(model.busy || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .accessibilityIdentifier("ssh.creator.generate") + if let error = model.error { + Text(LocalizedStringKey(errorKey(error))).foregroundStyle(.red).accessibilityIdentifier("ssh.creator.error") + Button("ssh.ok") { model.error = nil } + } + }.navigationTitle("ssh.key.generate") + .onAppear { model.error = nil } + .toolbar { ToolbarItem(placement: .cancellationAction) { + Button("network.cancel") { dismiss() }.accessibilityIdentifier("ssh.creator.cancel") + } } + } + } +} + +private struct SshImportPreviewView: View { + @Environment(\.dismiss) private var dismiss + @ObservedObject var model: SshViewModel + var body: some View { + NavigationStack { + if let plan = model.importPlan { + List { + Section { + LabeledContent("ssh.import.new", value: String(model.importAddedCount(plan))) + LabeledContent("ssh.import.updated", value: String(plan.updatedProfiles.count)) + LabeledContent("ssh.import.unchanged", value: String(plan.unchangedProfiles.count)) + LabeledContent("ssh.import.skipped", value: String(plan.skipped.count)) + Picker("ssh.import.key", selection: Binding(get: { model.importKeyRef ?? "" }, + set: { model.selectImportKey($0.isEmpty ? nil : $0) })) { + Text("ssh.import.no.key").tag("") + ForEach(model.data?.keys ?? [], id: \.id) { Text(verbatim: $0.name).tag($0.id) } + }.pickerStyle(.menu).accessibilityIdentifier("ssh.import.key") + } + ForEach(model.importPreviews(plan), id: \.after.id) { preview in + Section { + if preview.before == nil { + LabeledContent("ssh.host", value: preview.after.host) + LabeledContent("lan.port", value: String(preview.after.port)) + LabeledContent("ssh.user", value: preview.after.username) + LabeledContent("ssh.authentication", value: sshAuthenticationName(preview.after.authentication.name)) + .accessibilityIdentifier("ssh.import.authentication.\(preview.after.name)") + if !preview.after.startupCommand.isEmpty { LabeledContent("ssh.startup.command", value: preview.after.startupCommand) } + LabeledContent("ssh.keepalive", value: String(preview.after.keepaliveSeconds)) + } + ForEach(preview.changes, id: \.field) { change in + LabeledContent(fieldName(change.field), value: display(change.before, field: change.field) + " → " + display(change.after, field: change.field)) + .accessibilityIdentifier("ssh.import.change.\(change.field.name)") + } + if preview.startupWarning { Text("ssh.import.startup.warning").foregroundStyle(.orange).accessibilityIdentifier("ssh.import.startup.warning") } + if preview.needsKeySelection { Text("ssh.key.required.message").foregroundStyle(.orange).accessibilityIdentifier("ssh.import.key.required") } + if preview.after.authentication == .interactive { Text("ssh.interactive.unsupported").foregroundStyle(.orange) } + if preview.before?.secretRef != nil && preview.after.secretRef == nil { Text("ssh.import.password.detached").foregroundStyle(.orange) } + } header: { Text(verbatim: preview.after.name) } + } + ForEach(Array(plan.skipped.enumerated()), id: \.offset) { _, entry in + Text(verbatim: entry.alias + " — " + skipReason(entry.reason.name)) + } + } + .navigationTitle("ssh.import.preview") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("network.cancel") { model.cancelImport(); dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("ssh.import.apply") { model.confirmImport(); dismiss() } + .disabled(model.busy || (model.importAddedCount(plan) == 0 && plan.updatedProfiles.isEmpty)) + .accessibilityIdentifier("ssh.import.apply") + } + } + } + } + } + private func display(_ value: String, field: IosSshImportField) -> String { + if field == .authentication { return sshAuthenticationName(value) } + return value.isEmpty ? String(localized: "ssh.value.empty") : value + } + private func fieldName(_ field: IosSshImportField) -> LocalizedStringKey { + switch field { + case .host: "ssh.host" + case .port: "lan.port" + case .username: "ssh.user" + case .authentication: "ssh.authentication" + case .startupCommand: "ssh.startup.command" + default: "ssh.keepalive" + } + } + private func skipReason(_ reason: String) -> String { + switch reason { + case "PROXY_JUMP": String(localized: "ssh.skip.proxyjump") + case "PROXY_COMMAND": String(localized: "ssh.skip.proxycommand") + case "MATCH": String(localized: "ssh.skip.match") + case "WILDCARD": String(localized: "ssh.skip.wildcard") + case "MISSING_HOST": String(localized: "ssh.skip.missinghost") + default: String(localized: "ssh.skip.unsupported") + } + } +} diff --git a/iosApp/NetKit/SshViewModel.swift b/iosApp/NetKit/SshViewModel.swift new file mode 100644 index 0000000..e9ae03f --- /dev/null +++ b/iosApp/NetKit/SshViewModel.swift @@ -0,0 +1,447 @@ +import CryptoKit +import Darwin +import Foundation +import NetKitShared +import NIOSSH +import SwiftUI +import UIKit +import UniformTypeIdentifiers + +@MainActor +final class SshViewModel: ObservableObject { + typealias SessionFactory = (SshProfile, SshCredential, SshHostKeyValidator, + @escaping (Data) -> Void, @escaping (SshTransport.State) -> Void) throws -> (SshSession, () -> Void) + enum ExportFailure: Equatable { case duplicateNames([String]), tooLarge, invalid } + struct HostPrompt: Identifiable { + let id = UUID() + let endpoint: String + let algorithm: String + let fingerprint: String + let previousRejected: String? + let repeatedRejected: Bool + let reply: (Bool) -> Void + } + struct ChangedHost { let endpoint: String; let saved: String; let offered: String } + enum ErrorKind: Equatable { case storage, invalid, credentials, keyInUse, connection, algorithm, unsupportedCredential, interactiveUnsupported, hostChanged, hostRejected, timeout, inputOverflow } + @Published var data: SshData? + @Published var error: ErrorKind? + @Published var hostPrompt: HostPrompt? + @Published var changedHost: ChangedHost? + @Published var connected = false + @Published var terminalSnapshot: TerminalSnapshot? + @Published var terminalRevision = 0 + @Published var importPlan: SshImportPlan? + @Published var publicKey: String? + @Published private(set) var busy = false + @Published private(set) var exportData: Data? + @Published var exportFailure: ExportFailure? + @Published var keySelectionRequired: SshProfile? + @Published var profileUnavailable = false + @Published private(set) var importKeyRef: String? + private var pendingImport: SshProfileImport? + private let domain = IosSshDomain() + private let credentialStore: IosSecretStoreAdapter + private var store: SshMetadataStore? + private var transport: SshSession? + private let sessionFactory: SessionFactory + private var terminal = IosTerminal(columns: 80, rows: 24) + private var utf8Pending = Data() + private var sessionID = UUID() + private var activeProfile: SshProfile? + private let lifecycle: IosSshLifecycle + private var backgroundTask: Task? + #if DEBUG && targetEnvironment(simulator) + var uiImportURL: URL? + #endif + + init(nowMillis: @escaping () -> Int64 = { Int64(clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1_000_000) }, + keychain: KeychainSecrets = KeychainSecrets(), directory: URL? = nil, + sessionFactory: SessionFactory? = nil) { + self.sessionFactory = sessionFactory ?? { profile, credential, validator, output, state in + let session = try SshTransport(host: profile.host, port: Int(profile.port), username: profile.username, + credential: credential, validator: validator, output: output, state: state) + return (SshSessionAdapter(transport: session), { session.start() }) + } + credentialStore = IosSecretStoreAdapter(backend: KeychainSecretBackend(keychain: keychain)) + lifecycle = IosSshLifecycle(nowMillis: { KotlinLong(value: nowMillis()) }) + do { + let store = try SshMetadataStore(directory: directory, onFreshInstall: { try keychain.deleteServiceItems() }) + self.store = store; data = store.snapshot() + do { cleanupUnreferenced(try keychain.accountIDs()) } + catch { self.error = .credentials } + } + catch { self.error = .storage } + } + + func saveProfile(id: String?, name: String, host: String, port: String, username: String, + keyRef: String?, password: String, authentication: SshAuthentication? = nil) -> Bool { + guard !busy else { return false } + busy = true; defer { busy = false } + guard let store, let portNumber = Int32(port), (1...65535).contains(portNumber), + password.utf8.count <= 256 * 1024 else { error = .invalid; return false } + let current = store.snapshot() + let previous = current.profiles.first(where: { $0.id == id }) + guard id == nil || previous != nil else { profileUnavailable = true; keySelectionRequired = nil; return false } + let profileID = id ?? UUID().uuidString + let sameEndpoint = previous?.host == host && previous?.port == portNumber && previous?.username == username + let auth: SshAuthentication = authentication ?? (keyRef != nil ? .key : previous?.authentication ?? .password) + guard auth == .password || auth == .key, + auth != .key || current.keys.contains(where: { $0.id == keyRef }), + auth != .password || keyRef == nil else { error = .invalid; return false } + let initialRef = sameEndpoint && auth == .password ? previous?.secretRef : nil + guard let profile = domain.profile(id: profileID, name: name, host: host, port: portNumber, + username: username, authentication: auth, secretRef: initialRef, + keyRef: keyRef, startupCommand: previous?.startupCommand ?? "", + keepaliveSeconds: previous?.keepaliveSeconds ?? 30) else { error = .invalid; return false } + do { + if auth == .password && !password.isEmpty { + let ref = UUID().uuidString + let bytes = toKotlin(Data(password.utf8)) + guard credentialStore.putSecret(id: ref, secret: bytes) == nil else { throw SshMetadataStore.Failure.io } + guard let updated = domain.profile(id: profileID, name: name, host: host, port: portNumber, + username: username, authentication: auth, secretRef: ref, keyRef: nil, + startupCommand: previous?.startupCommand ?? "", keepaliveSeconds: previous?.keepaliveSeconds ?? 30) else { + _ = credentialStore.deleteSecret(id: ref); throw SshMetadataStore.Failure.invalid + } + do { try store.save(profile: profile, withCredential: updated) } + catch { _ = credentialStore.deleteSecret(id: ref); throw error } + } else { + try store.save(profile: profile) + } + data = store.snapshot(); error = nil; keySelectionRequired = nil; profileUnavailable = false + if let old = previous?.secretRef { cleanupUnreferenced([old]) } + return true + } catch { self.error = .storage; data = store.snapshot(); return false } + } + + func generateKey(name: String) { + guard !busy else { return } + busy = true; defer { busy = false } + guard let store, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, name.count <= 100 else { error = .invalid; return } + let key = Curve25519.Signing.PrivateKey() + let id = UUID().uuidString + let publicText = String(openSSHPublicKey: NIOSSHPrivateKey(ed25519Key: key).publicKey) + guard credentialStore.putSecret(id: id, secret: toKotlin(key.rawRepresentation)) == nil else { error = .credentials; return } + do { + try store.save(key: SshKeyInfo(id: id, name: name, publicKey: publicText)) + data = store.snapshot(); publicKey = publicText; error = nil + } catch { _ = credentialStore.deleteSecret(id: id); self.error = .storage } + } + + func connect(_ profile: SshProfile) { + startConnection(profile, replacing: false) + } + + var reconnectProfile: SshProfile? { + guard let activeProfile else { return nil } + return store?.snapshot().profiles.first(where: { $0.id == activeProfile.id }) ?? activeProfile + } + + /// The caller confirms this exact profile, including endpoint and startup command. + func reconnect(_ confirmedProfile: SshProfile) { + guard activeProfile?.id == confirmedProfile.id else { profileUnavailable = true; keySelectionRequired = nil; return } + startConnection(confirmedProfile, replacing: true) + } + + private func startConnection(_ profile: SshProfile, replacing: Bool) { + guard let store, !busy, importPlan == nil, replacing || transport == nil else { return } + let current = store.snapshot() + guard current.profiles.contains(where: { $0.id == profile.id }) else { + profileUnavailable = true; keySelectionRequired = nil; return + } + profileUnavailable = false + if domain.needsKeySelection(profile: profile, data: current) { + keySelectionRequired = profile; error = nil; return + } + keySelectionRequired = nil + guard profile.authentication != .interactive else { error = .interactiveUnsupported; return } + guard profile.authentication == .password || profile.authentication == .key else { + error = .credentials; return + } + let reference = profile.authentication == .key ? profile.keyRef : profile.secretRef + guard let reference else { error = .credentials; return } + if profile.authentication == .key, let key = current.keys.first(where: { $0.id == reference }), + !sshSupportedCredentialKey(key.publicKey) { + error = .unsupportedCredential; return + } + let found = credentialStore.getSecret(id: reference) + guard found.failure == nil, let bytes = found.bytes else { error = .credentials; return } + let raw = Data((0.. SshProfile? { + guard let requested = presented ?? keySelectionRequired else { return nil } + keySelectionRequired = nil + guard let profile = store?.snapshot().profiles.first(where: { $0.id == requested.id }) else { + profileUnavailable = true; return nil + } + return profile + } + + func needsKeySelection(_ profile: SshProfile) -> Bool { + guard let data else { return false } + return domain.needsKeySelection(profile: profile, data: data) + } + + func canMoveProfile(id: String, delta: Int) -> Bool { + guard !busy, importPlan == nil, delta == -1 || delta == 1, + let profiles = data?.profiles, let index = profiles.firstIndex(where: { $0.id == id }) else { return false } + return profiles.indices.contains(index + delta) + } + + func moveProfile(id: String, delta: Int) { + guard canMoveProfile(id: id, delta: delta), let store else { return } + busy = true; defer { busy = false } + do { try store.moveProfile(id: id, delta: Int32(delta)); data = store.snapshot(); error = nil } + catch { self.error = .storage } + } + + @discardableResult + func prepareExport() -> Data? { + guard !busy else { return nil } + busy = true; defer { busy = false } + exportData = nil; exportFailure = nil + guard let store else { error = .storage; return nil } + let result = store.prepareExport() + if let failure = result.failure { + switch failure { + case .duplicateNames: exportFailure = .duplicateNames(result.duplicateNames) + case .tooLarge: exportFailure = .tooLarge + default: exportFailure = .invalid + } + return nil + } + guard let bytes = result.bytes else { exportFailure = .invalid; return nil } + let prepared = Data((0.. Bool { terminal.pasteNeedsConfirmation(text: value) } + + func resetTrust(endpoint: String) { + guard !busy else { return } + busy = true; defer { busy = false } + guard let store else { error = .storage; return } + disconnect() + do { try store.forget(endpoint: endpoint); data = store.snapshot() } + catch { self.error = .storage } + } + + private func cleanupUnreferenced(_ candidates: [String]) { + guard let data else { return } + let inUse = Set(data.profiles.compactMap(\.secretRef) + data.profiles.compactMap(\.keyRef) + data.keys.map(\.id)) + for ref in Set(candidates) where !inUse.contains(ref) { + if credentialStore.deleteSecret(id: ref) != nil { error = .credentials } + } + } + + func deleteProfile(_ profile: SshProfile) { + guard !busy else { return } + busy = true; defer { busy = false } + guard let store else { error = .storage; return } + disconnect() + let previous = store.snapshot().profiles.first(where: { $0.id == profile.id }) + do { try store.deleteProfile(id: profile.id); data = store.snapshot(); error = nil + if keySelectionRequired?.id == profile.id { keySelectionRequired = nil } + if let ref = previous?.secretRef { cleanupUnreferenced([ref]) } + } catch { self.error = .storage } + } + + func deleteKey(_ key: SshKeyInfo) { + guard !busy else { return } + busy = true; defer { busy = false } + guard let store else { error = .storage; return } + guard data?.profiles.contains(where: { $0.keyRef == key.id }) == false else { error = .keyInUse; return } + do { try store.deleteKey(id: key.id); data = store.snapshot(); error = nil; cleanupUnreferenced([key.id]) } + catch { self.error = .storage } + } + + func previewImport(_ url: URL) { + guard !busy else { return } + busy = true; defer { busy = false } + cancelImport() + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + do { + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + let raw = try handle.read(upToCount: 256 * 1024 + 1) ?? Data() + guard let store, let imported = domain.decodeImport(bytes: toKotlin(raw)).imported else { throw SshMetadataStore.Failure.invalid } + let plan = try store.planImport(imported, keyRef: nil) + pendingImport = imported; importPlan = plan; error = nil + } catch { self.error = .invalid } + } + func selectImportKey(_ keyRef: String?) { + guard !busy, let store, let imported = pendingImport else { return } + busy = true; defer { busy = false } + importPlan = nil; importKeyRef = nil + do { importPlan = try store.planImport(imported, keyRef: keyRef); importKeyRef = keyRef; error = nil } + catch { self.error = .invalid } + } + func cancelImport() { importPlan = nil; pendingImport = nil; importKeyRef = nil } + func importAddedCount(_ plan: SshImportPlan) -> Int32 { domain.importAddedCount(plan: plan) } + func confirmImport() { + guard !busy else { return } + busy = true; defer { busy = false } + guard let store, let plan = importPlan else { return } + do { try store.applyImport(plan); data = store.snapshot(); cancelImport(); error = nil + cleanupUnreferenced(domain.importDetachedRefs(plan: plan)) } + catch { self.error = .storage; cancelImport() } + } + + func importPreviews(_ plan: SshImportPlan) -> [IosSshImportPreview] { + domain.importProfilePreviews(plan: plan, data: store?.snapshot() ?? domain.emptyData()) + } + + func importChanges(_ plan: SshImportPlan) -> [IosSshEndpointChange] { domain.importChangedEndpoints(plan: plan) } + + private func toKotlin(_ data: Data) -> KotlinByteArray { + let result = KotlinByteArray(size: Int32(data.count)) + for (index, value) in data.enumerated() { result.set(index: Int32(index), value: Int8(bitPattern: value)) } + return result + } +} diff --git a/iosApp/NetKit/WifiView.swift b/iosApp/NetKit/WifiView.swift new file mode 100644 index 0000000..f7fae41 --- /dev/null +++ b/iosApp/NetKit/WifiView.swift @@ -0,0 +1,29 @@ +import NetworkExtension +import SwiftUI + +struct WifiView: View { + @State private var network: NEHotspotNetwork? + @State private var checked = false + @State private var loading = false + + var body: some View { + Form { + if let network { + LabeledContent("wifi.ssid", value: network.ssid) + LabeledContent("wifi.bssid", value: network.bssid) + } else if checked { + Text("wifi.unavailable") + } + Button("wifi.refresh") { + loading = true + Task { + network = await NEHotspotNetwork.fetchCurrent() + checked = true + loading = false + } + } + .disabled(loading) + } + .navigationTitle("tab.wifi") + } +} diff --git a/iosApp/NetKit/WolPersistence.swift b/iosApp/NetKit/WolPersistence.swift new file mode 100644 index 0000000..45a68c3 --- /dev/null +++ b/iosApp/NetKit/WolPersistence.swift @@ -0,0 +1,77 @@ +import Foundation +import Darwin +import NetKitShared + +/// The codec validates the entire versioned document. Read errors never become an empty store. +final class WolPersistence: NSObject, IosWolPersistence { + private let codec = IosWolCodec() + private let limit = 1_048_576 + private let directoryOverride: URL? + + init(directoryOverride: URL? = nil) { + self.directoryOverride = directoryOverride + super.init() + } + + private func directory() throws -> URL { + if let directoryOverride { return directoryOverride } + guard let root = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { + throw CocoaError(.fileNoSuchFile) + } + return root.appendingPathComponent("NetKit", isDirectory: true) + } + + static func isMissingFile(_ error: NSError) -> Bool { + var current: NSError? = error + var visited = Set() + while let value = current, visited.insert(ObjectIdentifier(value)).inserted { + if value.domain == NSCocoaErrorDomain { + if value.code == NSFileNoSuchFileError || value.code == NSFileReadNoSuchFileError { return true } + // Specific file errors such as permission denied or corruption remain failures; + // generic Cocoa wrappers can still carry the actual error underneath. + if (NSFileReadNoPermissionError...NSFileErrorMaximum).contains(value.code) { return false } + } else if value.domain == NSPOSIXErrorDomain { + return value.code == Int(ENOENT) + } + current = value.userInfo[NSUnderlyingErrorKey] as? NSError + } + return false + } + + func load() -> IosWolLoadResult { + guard let file = try? directory().appendingPathComponent("wol.json") else { + return IosWolLoadResult(devices: [], failure: .io) + } + do { + let handle = try FileHandle(forReadingFrom: file) + defer { try? handle.close() } + let data = try handle.read(upToCount: limit + 1) ?? Data() + guard data.count <= limit else { return IosWolLoadResult(devices: [], failure: .corrupt) } + let bytes = KotlinByteArray(size: Int32(data.count)) + for (index, byte) in data.enumerated() { bytes.set(index: Int32(index), value: Int8(bitPattern: byte)) } + return codec.decode(bytes: bytes) + } catch { + if Self.isMissingFile(error as NSError) { + return IosWolLoadResult(devices: [], failure: nil) + } + return IosWolLoadResult(devices: [], failure: .io) + } + } + + func save(devices: [WolDevice]) -> Bool { + guard let bytes = codec.encode(devices: devices) else { return false } + let data = Data((0.. NetworkIdentity? { + value.map { NetworkIdentity(interfaceIndex: $0.0.index, address: $0.1, mask: $0.2) } + } + + static func sameNetwork(_ lhs: (NWInterface, UInt32, UInt32)?, _ rhs: (NWInterface, UInt32, UInt32)?) -> Bool { + identity(lhs) == identity(rhs) + } + + func activeWifiCIDR() -> String? { + guard let (_, address, mask) = current else { return nil } + return "\(Self.text(address))/\(mask.nonzeroBitCount)" + } + + func currentWifi() -> IosWifiSnapshot? { + guard let (_, address, mask) = current else { return nil } + return IosWifiSnapshot(token: epoch, ipv4: Self.text(address), prefixLength: KotlinInt(value: Int32(mask.nonzeroBitCount))) + } + + func sendUdp(networkToken: String, host: String, port: Int32, payload: KotlinByteArray, + completion: @escaping (SendFailure?) -> Void) -> IosCancellation { + let operation = WolDatagram(completion: completion) + guard networkToken == epoch, let (interface, address, mask) = current else { + operation.finish(.networkLost) + return operation + } + guard let destination = Self.number(host), port > 0, port <= 65535 else { + operation.finish(.io) + return operation + } + // Restricted multicast entitlement is absent. Permit only a unicast host in the + // selected interface's subnet; reject local network and directed broadcast. + guard Self.permittedUnicast(destination, address: address, mask: mask) else { + operation.finish(.noBroadcast) + return operation + } + let parameters = NWParameters.udp + parameters.requiredInterfaceType = .wifi + parameters.requiredInterface = interface + let conn = NWConnection(host: NWEndpoint.Host(host), port: NWEndpoint.Port(rawValue: UInt16(port))!, using: parameters) + let id = UUID() + operations[id] = operation + operation.onEnd = { [weak self] in self?.operations.removeValue(forKey: id) } + let bytes = Data((0.. Void) -> IosCancellation { + let operation = WolProbe(completion: completion) + guard networkToken == epoch, let (interface, address, mask) = current, + let destination = Self.number(host), + Self.permittedUnicast(destination, address: address, mask: mask) else { + operation.finish(.unavailable) + return operation + } + let id = UUID() + operations[id] = operation + operation.onEnd = { [weak self] in self?.operations.removeValue(forKey: id) } + if let port { + let rawPort = port.intValue + guard rawPort > 0, rawPort <= 65535, let endpoint = NWEndpoint.Port(rawValue: UInt16(rawPort)) else { + operation.finish(.unavailable) + return operation + } + let parameters = NWParameters.tcp + parameters.requiredInterfaceType = .wifi + parameters.requiredInterface = interface + operation.startTCP(NWConnection(host: NWEndpoint.Host(host), port: endpoint, using: parameters)) + } else { + operation.startPing(address: host, interfaceName: interface.name) + } + return operation + } + + static func permittedUnicast(_ destination: UInt32, address: UInt32, mask: UInt32) -> Bool { + let firstOctet = destination >> 24 + guard firstOctet != 0, firstOctet != 127, firstOctet < 224 else { return false } + let network = address & mask + guard destination & mask == network else { return false } + if mask.nonzeroBitCount >= 31 { return true } + return destination != network && destination != (network | ~mask) + } + + private static func ipv4(interface: String) -> (UInt32, UInt32)? { + var list: UnsafeMutablePointer? + guard getifaddrs(&list) == 0 else { return nil } + defer { freeifaddrs(list) } + var item = list + while let entry = item { + defer { item = entry.pointee.ifa_next } + guard String(cString: entry.pointee.ifa_name) == interface, + let addr = entry.pointee.ifa_addr, let netmask = entry.pointee.ifa_netmask, + Int32(addr.pointee.sa_family) == AF_INET else { continue } + let value = UnsafeRawPointer(addr).assumingMemoryBound(to: sockaddr_in.self).pointee.sin_addr.s_addr.bigEndian + let mask = UnsafeRawPointer(netmask).assumingMemoryBound(to: sockaddr_in.self).pointee.sin_addr.s_addr.bigEndian + let bits = mask.nonzeroBitCount + let expected: UInt32 = bits == 0 ? 0 : UInt32.max << (32 - bits) + guard mask == expected else { return nil } + return (value, mask) + } + return nil + } + + private static func number(_ text: String) -> UInt32? { + var addr = in_addr() + guard text.withCString({ inet_pton(AF_INET, $0, &addr) }) == 1 else { return nil } + return addr.s_addr.bigEndian + } + + private static func text(_ value: UInt32) -> String { + [24, 16, 8, 0].map { String((value >> $0) & 255) }.joined(separator: ".") + } +} + +final class WolDatagram: NSObject, IosCancellation, WolPending { + var connection: NWConnection? + var onEnd: (() -> Void)? + private var completion: ((SendFailure?) -> Void)? + init(completion: @escaping (SendFailure?) -> Void) { self.completion = completion } + func start(connection: NWConnection, payload: Data) { + self.connection = connection + connection.stateUpdateHandler = { [weak self, weak connection] state in + guard let self, let connection else { return } + switch state { + case .ready: + connection.stateUpdateHandler = nil + connection.send(content: payload, completion: .contentProcessed { [weak self] error in + self?.finish(error == nil ? nil : .io) + }) + case .failed: self.finish(.io) + default: break + } + } + connection.start(queue: .main) + } + func cancel() { + if !Thread.isMainThread { + DispatchQueue.main.async { self.cancel() } + return + } + completion = nil + connection?.cancel() + connection = nil + onEnd?() + onEnd = nil + } + func networkLost() { finish(.networkLost) } + func finish(_ failure: SendFailure?) { + if !Thread.isMainThread { + DispatchQueue.main.async { self.finish(failure) } + return + } + let callback = completion + cancel() + callback?(failure) + } +} + +final class WolProbe: NSObject, IosCancellation, WolPending { + var onEnd: (() -> Void)? + private var completion: ((WakeProbeStatus) -> Void)? + private var connection: NWConnection? + private var ping: IcmpPing? + private var timeout: DispatchWorkItem? + init(completion: @escaping (WakeProbeStatus) -> Void) { self.completion = completion } + + func startTCP(_ connection: NWConnection) { + self.connection = connection + let timeout = DispatchWorkItem { [weak self] in self?.finish(.noResponse) } + self.timeout = timeout + DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: timeout) + connection.stateUpdateHandler = { [weak self] state in + switch state { + case .ready: self?.finish(.responds) + case .waiting(let error): + if case .posix(.ECONNREFUSED) = error { self?.finish(.responds) } + case .failed(let error): + if case .posix(.ECONNREFUSED) = error { self?.finish(.responds) } + else { self?.finish(.unavailable) } + default: break + } + } + connection.start(queue: .main) + } + + func startPing(address: String, interfaceName: String) { + let ping = IcmpPing() + self.ping = ping + ping.start(address: address, interfaceName: interfaceName) { [weak self] result in + switch result { + case .reply: self?.finish(.responds) + case .timeout: self?.finish(.noResponse) + case .invalid: self?.finish(.unavailable) + } + } + } + + func cancel() { + if !Thread.isMainThread { DispatchQueue.main.async { self.cancel() }; return } + completion = nil + timeout?.cancel(); timeout = nil + connection?.cancel(); connection = nil + ping?.cancel(); ping = nil + onEnd?(); onEnd = nil + } + func networkLost() { finish(.unavailable) } + func finish(_ result: WakeProbeStatus) { + if !Thread.isMainThread { DispatchQueue.main.async { self.finish(result) }; return } + let callback = completion + cancel() + callback?(result) + } +} diff --git a/iosApp/NetKit/WolView.swift b/iosApp/NetKit/WolView.swift new file mode 100644 index 0000000..33f8527 --- /dev/null +++ b/iosApp/NetKit/WolView.swift @@ -0,0 +1,105 @@ +import Foundation +import NetKitShared +import SwiftUI + +@MainActor +final class WolViewModel: ObservableObject { + private let platform: WolPlatform + private let storage: WolPersistence + private let bridge: IosWolBridge + private var observation: IosCancellation? + @Published var state: WolUiState + @Published var invalid = false + + init() { + let platform = WolPlatform() + let storage = WolPersistence() + self.platform = platform + self.storage = storage + let bridge = IosWolBridge(platform: platform, persistence: storage, + nowMillis: { KotlinLong(value: Int64(Date().timeIntervalSince1970 * 1000)) }, + newId: { UUID().uuidString }) + self.bridge = bridge + self.state = bridge.currentState() + observation = bridge.observe { [weak self] state in + self?.state = state + } + } + + func add(name: String, mac: String, host: String, port: String, broadcast: Bool) { + guard let number = Int32(port), (1...65535).contains(number) else { invalid = true; return } + let draft = bridge.draft(id: nil, name: name, mac: mac, + targetMode: broadcast ? .limitedBroadcast : .custom, + customTarget: host, port: number) + invalid = !bridge.saveDraft(draft: draft) + } + func wake(_ id: String) { bridge.controller.wake(id: id) } + func cancel() { bridge.controller.cancelWake() } + func delete(_ id: String) { bridge.controller.delete(id: id) } + deinit { observation?.cancel(); bridge.close() } +} + +struct WolView: View { + @Environment(\.scenePhase) private var scenePhase + @StateObject private var model = WolViewModel() + @State private var name = "" + @State private var mac = "" + @State private var host = "" + @State private var port = "9" + @State private var selectedID: String? + @State private var confirm = false + @State private var deleteID: String? + @State private var confirmDelete = false + + var body: some View { + Form { + Text("wol.warning") + if model.state.loadFailed { Text("wol.load.error").foregroundStyle(.red) } + Section("wol.add") { + TextField("wol.name", text: $name) + TextField("wol.mac", text: $mac).textInputAutocapitalization(.never).autocorrectionDisabled() + TextField("wol.host", text: $host).keyboardType(.numbersAndPunctuation) + TextField("lan.port", text: $port).keyboardType(.numberPad) + Button("wol.save") { model.add(name: name, mac: mac, host: host, port: port, broadcast: false) } + .disabled(model.state.loadFailed || model.state.loading || model.state.saving) + if model.invalid { Text("network.invalid").foregroundStyle(.red) } + } + Section("wol.devices") { + if model.state.devices.isEmpty && !model.state.loading && !model.state.loadFailed { Text("wol.empty") } + ForEach(model.state.devices, id: \.id) { device in + HStack { + Button(device.name) { selectedID = device.id; confirm = true } + .disabled(model.state.sendingDeviceId != nil) + Spacer() + Button(role: .destructive) { deleteID = device.id; confirmDelete = true } label: { Image(systemName: "trash") } + .accessibilityLabel("wol.delete") + .disabled(model.state.sendingDeviceId != nil) + } + } + } + if model.state.sendingDeviceId != nil { Button("network.cancel") { model.cancel() } } + if let message = model.state.message { + switch message.name { + case "SENT": Text("wol.sent") + case "NO_WIFI": Text("wol.no.wifi") + case "NO_BROADCAST": Text("wol.broadcast.unavailable") + case "SAVE_FAILED": Text("wol.save.error") + default: Text("network.failed") + } + } + } + .navigationTitle("tab.wol") + .confirmationDialog("lan.consent.title", isPresented: $confirm, titleVisibility: .visible) { + Button("lan.consent.confirm") { if let id = selectedID { model.wake(id) }; selectedID = nil } + Button("network.cancel", role: .cancel) { selectedID = nil } + } message: { Text("wol.warning") } + .confirmationDialog("wol.delete.confirm", isPresented: $confirmDelete, titleVisibility: .visible) { + Button("wol.delete", role: .destructive) { if let id = deleteID { model.delete(id) }; deleteID = nil } + Button("network.cancel", role: .cancel) { deleteID = nil } + } + .onChange(of: scenePhase) { _, phase in + if phase == .background { model.cancel() } + } + .onDisappear { model.cancel() } + } +} diff --git a/iosApp/NetKit/cs.lproj/InfoPlist.strings b/iosApp/NetKit/cs.lproj/InfoPlist.strings new file mode 100644 index 0000000..5306458 --- /dev/null +++ b/iosApp/NetKit/cs.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +"NSLocalNetworkUsageDescription" = "NetKit se připojuje k vámi vybraným zařízením v místní síti."; +"NSLocationWhenInUseUsageDescription" = "Oprávnění k poloze může NetKitu umožnit zjistit aktuální síť Wi-Fi."; diff --git a/iosApp/NetKit/en.lproj/InfoPlist.strings b/iosApp/NetKit/en.lproj/InfoPlist.strings new file mode 100644 index 0000000..a956106 --- /dev/null +++ b/iosApp/NetKit/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +"NSLocalNetworkUsageDescription" = "NetKit connects to devices you choose on your local network."; +"NSLocationWhenInUseUsageDescription" = "Location permission can allow NetKit to identify the current Wi-Fi network."; diff --git a/iosApp/NetKitTests/KeychainSecretsTests.swift b/iosApp/NetKitTests/KeychainSecretsTests.swift new file mode 100644 index 0000000..6c244bc --- /dev/null +++ b/iosApp/NetKitTests/KeychainSecretsTests.swift @@ -0,0 +1,163 @@ +@testable import NetKit +import Foundation +import Security +import NetKitShared +import XCTest + +final class KeychainSecretsTests: XCTestCase { + func testRoundTripUpdateDeleteAndAccessibility() throws { + let service = "cz.netkit.ios.tests." + UUID().uuidString + let store = KeychainSecrets(service: service) + let id = "test-secret" + defer { try? store.delete(id) } + XCTAssertNil(try store.get(id)) + let first = Data(UUID().uuidString.utf8) + let second = Data(UUID().uuidString.utf8) + try store.put(id, secret: first) + XCTAssertEqual(try store.get(id), first) + try store.put(id, secret: second) + XCTAssertEqual(try store.get(id), second) + let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: id, + kSecReturnAttributes as String: true, + kSecMatchLimit as String: kSecMatchLimitOne] + var result: CFTypeRef? + XCTAssertEqual(SecItemCopyMatching(query as CFDictionary, &result), errSecSuccess) + let attributes = try XCTUnwrap(result as? [String: Any]) + XCTAssertEqual(attributes[kSecAttrAccessible as String] as? String, + kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String) + XCTAssertEqual(attributes[kSecAttrSynchronizable as String] as? Bool, false) + try store.delete(id) + XCTAssertNil(try store.get(id)) + } + + func testFreshMetadataClearsOnlyItsServiceAndCorruptMetadataDoesNot() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let own = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + let other = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + let id = UUID().uuidString + let value = Data(UUID().uuidString.utf8) + defer { try? own.delete(id); try? other.delete(id) } + try own.put(id, secret: value); try other.put(id, secret: value) + _ = try SshMetadataStore(directory: root, onFreshInstall: { try own.deleteServiceItems() }) + XCTAssertNil(try own.get(id)); XCTAssertEqual(try other.get(id), value) + try own.put(id, secret: value) + try Data("invalid".utf8).write(to: root.appendingPathComponent("ssh.json")) + XCTAssertThrowsError(try SshMetadataStore(directory: root, onFreshInstall: { try own.deleteServiceItems() })) + XCTAssertEqual(try own.get(id), value) + } + + func testSharedSecretStoreAdapterRoundTrip() { + let keychain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + let adapter = IosSecretStoreAdapter(backend: KeychainSecretBackend(keychain: keychain)) + let random = Array(UUID().uuidString.utf8.prefix(3)) + let input = KotlinByteArray(size: Int32(random.count)) + for (index, value) in random.enumerated() { input.set(index: Int32(index), value: Int8(bitPattern: value)) } + defer { _ = adapter.deleteSecret(id: "temporary") } + XCTAssertNil(adapter.putSecret(id: "temporary", secret: input)) + let read = adapter.getSecret(id: "temporary") + XCTAssertNil(read.failure) + XCTAssertEqual(read.bytes?.size, 3) + XCTAssertEqual(read.bytes?.get(index: 2), Int8(bitPattern: random[2])) + XCTAssertNil(adapter.deleteSecret(id: "temporary")) + XCTAssertNil(adapter.getSecret(id: "temporary").bytes) + } + + func testInvalidReferenceAndOversizeRejected() { + let store = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + XCTAssertThrowsError(try store.put("bad/ref", secret: Data(UUID().uuidString.utf8))) + XCTAssertThrowsError(try store.put("test-secret", secret: Data(repeating: 0, count: 256 * 1024 + 1))) + } + + @MainActor + func testProfileAndKeyDeletionKeepReferencedSecrets() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? chain.deleteServiceItems() } + let model = SshViewModel(keychain: chain, directory: root) + model.generateKey(name: "key") + let key = try XCTUnwrap(model.data?.keys.first) + XCTAssertTrue(model.saveProfile(id: nil, name: "profile", host: "192.0.2.1", port: "22", username: "user", keyRef: key.id, password: "")) + let profile = try XCTUnwrap(model.data?.profiles.first) + XCTAssertNotNil(try chain.get(key.id)) + model.deleteKey(key) + XCTAssertNotNil(model.data?.keys.first) + XCTAssertNotNil(try chain.get(key.id)) + model.deleteProfile(profile) + model.deleteKey(key) + XCTAssertTrue(model.data?.keys.isEmpty == true) + XCTAssertNil(try chain.get(key.id)) + } + + @MainActor + func testReplacingPasswordRemovesDetachedReference() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? chain.deleteServiceItems() } + let model = SshViewModel(keychain: chain, directory: root) + XCTAssertTrue(model.saveProfile(id: nil, name: "profile", host: "192.0.2.1", port: "22", username: "user", keyRef: nil, password: UUID().uuidString)) + let original = try XCTUnwrap(model.data?.profiles.first) + let oldRef = try XCTUnwrap(original.secretRef) + XCTAssertTrue(model.saveProfile(id: original.id, name: "profile", host: "192.0.2.1", port: "22", username: "user", keyRef: nil, password: UUID().uuidString)) + let updated = try XCTUnwrap(model.data?.profiles.first) + XCTAssertNil(try chain.get(oldRef)) + XCTAssertNotNil(try chain.get(try XCTUnwrap(updated.secretRef))) + model.deleteProfile(updated) + XCTAssertNil(try chain.get(try XCTUnwrap(updated.secretRef))) + } + + @MainActor + func testSharedReferenceSurvivesProfileDeletionAndImportShowsChangedEndpoint() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? chain.deleteServiceItems() } + let id = UUID().uuidString + let password = Data(UUID().uuidString.utf8) + let store = try SshMetadataStore(directory: root) + try chain.put(id, secret: password) + let domain = IosSshDomain() + let first = try XCTUnwrap(domain.profile(id: "first", name: "one", host: "192.0.2.1", port: 22, username: "user", authentication: .password, secretRef: id, keyRef: nil, startupCommand: "", keepaliveSeconds: 30)) + let second = try XCTUnwrap(domain.profile(id: "second", name: "two", host: "192.0.2.2", port: 22, username: "user", authentication: .password, secretRef: id, keyRef: nil, startupCommand: "", keepaliveSeconds: 30)) + try store.save(profile: first); try store.save(profile: second) + let model = SshViewModel(keychain: chain, directory: root) + model.deleteProfile(first) + XCTAssertEqual(try chain.get(id), password) + let payload: [String: Any] = ["format": "netkit-ssh-profiles", "schema": 1, + "profiles": [["alias": "two", "host": "198.51.100.1", "port": 2222, "username": "user"]], "skipped": []] + let file = root.appendingPathComponent("import.json") + try JSONSerialization.data(withJSONObject: payload).write(to: file) + model.previewImport(file) + let plan = try XCTUnwrap(model.importPlan) + let change = try XCTUnwrap(model.importChanges(plan).first) + XCTAssertEqual(change.before, "user@[192.0.2.2]:22") + XCTAssertEqual(change.after, "user@[198.51.100.1]:2222") + model.confirmImport() + XCTAssertNil(try chain.get(id)) + XCTAssertNil(model.data?.profiles.first?.secretRef) + } + + @MainActor + func testStartupReconcilesOnlyUnreferencedServiceItems() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + let other = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? chain.deleteServiceItems(); try? other.deleteServiceItems() } + let retained = UUID().uuidString, orphan = UUID().uuidString + let bytes = Data(UUID().uuidString.utf8) + let store = try SshMetadataStore(directory: root) + let profile = try XCTUnwrap(IosSshDomain().profile(id: "profile", name: "profile", host: "192.0.2.1", port: 22, + username: "user", authentication: .password, secretRef: retained, keyRef: nil, startupCommand: "", keepaliveSeconds: 30)) + try store.save(profile: profile) + try chain.put(retained, secret: bytes); try chain.put(orphan, secret: bytes); try other.put(orphan, secret: bytes) + _ = SshViewModel(keychain: chain, directory: root) + XCTAssertEqual(try chain.get(retained), bytes) + XCTAssertNil(try chain.get(orphan)) + XCTAssertEqual(try other.get(orphan), bytes) + } +} diff --git a/iosApp/NetKitTests/LanTests.swift b/iosApp/NetKitTests/LanTests.swift new file mode 100644 index 0000000..17d221d --- /dev/null +++ b/iosApp/NetKitTests/LanTests.swift @@ -0,0 +1,408 @@ +@testable import NetKit +import Combine +import Darwin +import Network +import XCTest +import NetKitShared + +final class LanTests: XCTestCase { + func testScanConcurrencyAndPortLimit() { + let scan = PortScan(host: "127.0.0.1", ports: Array(1...64).map(UInt16.init)) + scan.start { _, _, _ in } + XCTAssertEqual(scan.peakActive, 4) + scan.cancel() + let rejected = PortScan(host: "127.0.0.1", ports: Array(1...65).map(UInt16.init)) + var completed = false + rejected.start { _, result, done in + completed = done + XCTAssertEqual(result, String(localized: "network.invalid")) + } + XCTAssertTrue(completed) + XCTAssertEqual(rejected.peakActive, 0) + } + + func testInputValidationAndCancellationStatus() { + let session = LanSession() + session.pingHost(" not-an-ip ") + XCTAssertFalse(session.running) + XCTAssertEqual(session.status, String(localized: "network.invalid")) + session.dns(host: "example.invalid", server: "not-an-ip") + XCTAssertFalse(session.running) + XCTAssertEqual(session.status, String(localized: "network.invalid")) + session.browse(loopbackOnly: true) + session.cancel() + XCTAssertEqual(session.status, "") + } + + func testConfirmationReasonsUseWifiCIDR() { + let domain = IosNetworkDomain() + let within = domain.confirmationReasons(address: "192.0.2.2", ownCidr: "192.0.2.1/24", portCount: 1) + XCTAssertFalse(within.contains("OUTSIDE_WIFI")) + XCTAssertTrue(within.contains("NON_PRIVATE_ADDRESS")) + let outside = domain.confirmationReasons(address: "198.51.100.1", ownCidr: "192.0.2.1/24", portCount: 1) + XCTAssertTrue(outside.contains("OUTSIDE_WIFI")) + } + + func testPermissionDeniedClassification() { + XCTAssertTrue(LanSession.permissionDenied(.dns(-65570), localNetworkDenied: false)) + XCTAssertTrue(LanSession.permissionDenied(.posix(.EHOSTUNREACH), localNetworkDenied: true)) + XCTAssertFalse(LanSession.permissionDenied(.posix(.EHOSTUNREACH), localNetworkDenied: false)) + XCTAssertFalse(LanSession.permissionDenied(.dns(-65537), localNetworkDenied: false)) + } + + func testScanConsentTracksAllInputsAndLocalizedReasons() throws { + let consent = ScanConsent(host: "192.0.2.1", ports: "22", cidr: "198.51.100.1/24") + XCTAssertNotEqual(consent, ScanConsent(host: "192.0.2.2", ports: "22", cidr: consent.cidr)) + XCTAssertNotEqual(consent, ScanConsent(host: consent.host, ports: "23", cidr: consent.cidr)) + XCTAssertNotEqual(consent, ScanConsent(host: consent.host, ports: consent.ports, cidr: nil)) + for language in ["cs", "en"] { + let path = try XCTUnwrap(Bundle.main.path(forResource: language, ofType: "lproj")) + let bundle = try XCTUnwrap(Bundle(path: path)) + let resolve = { (key: String) in bundle.localizedString(forKey: key, value: nil, table: nil) } + let message = consent.message(resolve: resolve) + for key in ["lan.warning", "lan.reason.outside", "lan.reason.nonprivate"] { + XCTAssertNotEqual(resolve(key), key) + XCTAssertTrue(message.contains(resolve(key)), "Missing \(key) for \(language)") + } + } + } + + func testTCPListenerAndClosedPort() throws { + let parameters = NWParameters.tcp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) + let listener = try NWListener(using: parameters) + let listening = expectation(description: "localhost listener") + listener.newConnectionHandler = { connection in + connection.stateUpdateHandler = { state in + if case .ready = state { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { connection.cancel() } } + } + connection.start(queue: .main) + } + listener.stateUpdateHandler = { if case .ready = $0 { listening.fulfill() } } + listener.start(queue: .main) + // Loaded simulator runners can delay listener readiness; allow 20 s before probing. + wait(for: [listening], timeout: 20) + let openPort = try XCTUnwrap(listener.port?.rawValue) + + let fd = socket(AF_INET, SOCK_STREAM, 0) + guard fd >= 0 else { listener.cancel(); XCTFail("Could not create socket"); return } + var fdOpen = true + defer { if fdOpen { close(fd) }; listener.cancel() } + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + address.sin_addr = in_addr(s_addr: in_addr_t(INADDR_LOOPBACK).bigEndian) + let bound = withUnsafePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout.size)) } + } + guard bound == 0 else { XCTFail("Could not bind socket"); return } + var length = socklen_t(MemoryLayout.size) + let named = withUnsafeMutablePointer(to: &address) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &length) } + } + guard named == 0 else { XCTFail("Could not obtain port"); return } + let closedPort = UInt16(bigEndian: address.sin_port) + // Darwin can drop SYNs for a bound socket that is not listening; release it first. + guard close(fd) == 0 else { fdOpen = false; XCTFail("Could not close socket"); return } + fdOpen = false + XCTAssertNotEqual(openPort, closedPort) + let done = expectation(description: "port scan") + var states: [UInt16: [String]] = [:] + var refusedPorts = Set() + let scan = PortScan(host: "127.0.0.1", ports: [openPort, closedPort]) { port, state in + switch state { + case .waiting(let error), .failed(let error): + if case .posix(let code) = error { + states[port, default: []].append("\(String(reflecting: state)) POSIX=\(code.rawValue)") + if code == .ECONNREFUSED { refusedPorts.insert(port) } + } else { states[port, default: []].append(String(reflecting: state)) } + default: states[port, default: []].append(String(reflecting: state)) + } + } + var results: [UInt16: String] = [:] + scan.start { port, result, complete in + if let port, let result { results[port] = result } + if complete { done.fulfill() } + } + wait(for: [done], timeout: 8) + XCTAssertEqual(results[openPort], String(localized: "lan.open")) + XCTAssertEqual(results[closedPort], String(localized: "lan.closed"), + "NWConnection states: \(states[closedPort] ?? [])") + XCTAssertTrue(refusedPorts.contains(closedPort), "NWConnection states: \(states[closedPort] ?? [])") + } + + func testBonjourStartCanBeCancelled() { + let session = LanSession() + let cancelled = expectation(description: "NWBrowser cancelled") + session.browse(loopbackOnly: true) { state in + if case .cancelled = state { cancelled.fulfill() } + } + session.cancel() + let drained = expectation(description: "callbacks after cancellation") + DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { drained.fulfill() } + wait(for: [cancelled, drained], timeout: 2) + XCTAssertFalse(session.running) + } + + func testDnsLocalMock() throws { + let parameters = NWParameters.udp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) + let listener = try NWListener(using: parameters) + let ready = expectation(description: "DNS mock ready") + listener.stateUpdateHandler = { if case .ready = $0 { ready.fulfill() } } + listener.newConnectionHandler = { connection in + connection.start(queue: .main) + connection.receiveMessage { data, _, _, _ in + guard var response = data, response.count >= 12 else { return } + XCTAssertEqual(response[2] & 0x01, 0x01, "DNS query must request recursion") + response[2] = 0x81; response[3] = 0x80 + response[6] = 0; response[7] = 1 + response.append(contentsOf: [0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 1, 0, 4, 192, 0, 2, 1]) + connection.send(content: response, completion: .contentProcessed { _ in connection.cancel() }) + } + } + listener.start(queue: .main) + defer { listener.cancel() } + wait(for: [ready], timeout: 5) + let port = try XCTUnwrap(listener.port?.rawValue) + let answer = expectation(description: "DNS result") + let session = LanSession() + let observation = session.$results.sink { if $0.contains("192.0.2.1") { answer.fulfill() } } + session.dns(host: "example.invalid", server: "127.0.0.1", serverPort: port) + wait(for: [answer], timeout: 7) + withExtendedLifetime(observation) { } + session.cancel() + } + + func testSharedDnsRejectsWrongID() throws { + let domain = IosNetworkDomain() + let query = try XCTUnwrap(domain.dnsQuery(host: "example.invalid", type: 1, id: 1)) + XCTAssertNil(domain.dnsResponse(packet: query, id: 2, host: "example.invalid", type: 1)) + } +} + +final class WolDatagramTests: XCTestCase { + func testSharedMagicPacketReachesLoopback() throws { + let parameters = NWParameters.udp + parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any) + let listener = try NWListener(using: parameters) + let ready = expectation(description: "UDP listener ready") + let received = expectation(description: "magic packet received") + var actual: Data? + listener.stateUpdateHandler = { if case .ready = $0 { ready.fulfill() } } + listener.newConnectionHandler = { connection in + connection.start(queue: .main) + connection.receiveMessage { data, _, _, _ in + actual = data + received.fulfill() + connection.cancel() + } + } + listener.start(queue: .main) + defer { listener.cancel() } + wait(for: [ready], timeout: 5) + let port = try XCTUnwrap(listener.port) + let mac = try XCTUnwrap(WolDomainKt.parseMac(input: "02:00:00:00:00:01")) + let packet = WolDomainKt.magicPacket(mac: mac) + let data = Data((0..> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16) } + XCTAssertEqual(sum, 0xffff) + var reply = request + reply[0] = 0 + let sent = KotlinByteArray(size: Int32(request.count)) + let received = KotlinByteArray(size: Int32(reply.count)) + for (index, byte) in request.enumerated() { sent.set(index: Int32(index), value: Int8(bitPattern: byte)) } + for (index, byte) in reply.enumerated() { received.set(index: Int32(index), value: Int8(bitPattern: byte)) } + XCTAssertTrue(IosNetworkDomain().icmpReplyMatches(request: sent, reply: received)) + received.set(index: 8, value: 0) + XCTAssertFalse(IosNetworkDomain().icmpReplyMatches(request: sent, reply: received)) + } + + func testLoopbackEcho() { + let ping = IcmpPing() + let done = expectation(description: "loopback ICMP echo") + ping.start(address: "127.0.0.1") { result in + if case .reply(let milliseconds) = result { + XCTAssertGreaterThanOrEqual(milliseconds, 0) + } else { + XCTFail("Loopback did not return an ICMP echo reply") + } + done.fulfill() + } + wait(for: [done], timeout: 7) + } + + func testCancelledBeforeStartDoesNotComplete() { + let ping = IcmpPing() + ping.cancel() + let completed = expectation(description: "cancelled ping does not complete") + completed.isInverted = true + ping.start(address: "127.0.0.1") { _ in completed.fulfill() } + wait(for: [completed], timeout: 0.3) + } +} + +final class WolPersistenceTests: XCTestCase { + func testMissingFileErrorClassification() { + let cocoaMissing = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError) + let cocoaReadMissing = NSError(domain: NSCocoaErrorDomain, code: NSFileReadNoSuchFileError) + let posixMissing = NSError(domain: NSPOSIXErrorDomain, code: Int(ENOENT)) + let nestedCocoa4 = NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, + userInfo: [NSUnderlyingErrorKey: cocoaMissing]) + let nestedCocoa260 = NSError(domain: "fixture.wrapper", code: 1, + userInfo: [NSUnderlyingErrorKey: cocoaReadMissing]) + let nestedPosix = NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, + userInfo: [NSUnderlyingErrorKey: posixMissing]) + let genericCocoaWrapper = NSError(domain: NSCocoaErrorDomain, code: 1, + userInfo: [NSUnderlyingErrorKey: posixMissing]) + for error in [cocoaMissing, cocoaReadMissing, posixMissing, nestedCocoa4, nestedCocoa260, nestedPosix, genericCocoaWrapper] { + XCTAssertTrue(WolPersistence.isMissingFile(error)) + } + let denied = NSError(domain: NSPOSIXErrorDomain, code: Int(EACCES)) + let notDirectory = NSError(domain: NSPOSIXErrorDomain, code: Int(ENOTDIR)) + let ioError = NSError(domain: NSPOSIXErrorDomain, code: Int(EIO)) + let nestedDenied = NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, + userInfo: [NSUnderlyingErrorKey: denied]) + let explicitDenied = NSError(domain: NSCocoaErrorDomain, code: NSFileReadNoPermissionError, + userInfo: [NSUnderlyingErrorKey: posixMissing]) + let nestedIO = NSError(domain: NSCocoaErrorDomain, code: NSFileReadUnknownError, + userInfo: [NSUnderlyingErrorKey: ioError]) + for error in [denied, notDirectory, ioError, nestedDenied, nestedIO, explicitDenied] { + XCTAssertFalse(WolPersistence.isMissingFile(error)) + } + } + + func testEmptyRoundTripAndCorruptionDoesNotReset() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let store = WolPersistence(directoryOverride: directory) + XCTAssertNil(store.load().failure) + XCTAssertTrue(store.save(devices: [])) + XCTAssertNil(store.load().failure) + let file = directory.appendingPathComponent("wol.json") + let invalid = Data("invalid json".utf8) + try invalid.write(to: file, options: .atomic) + XCTAssertNotNil(store.load().failure) + XCTAssertEqual(try Data(contentsOf: file), invalid) + } + + func testMissingFileInExistingDirectoryIsEmpty() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let result = WolPersistence(directoryOverride: directory).load() + XCTAssertNil(result.failure) + XCTAssertTrue(result.devices.isEmpty) + } + + func testProfileRoundTrip() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let store = WolPersistence(directoryOverride: directory) + let device = WolDevice(id: "synthetic-1", name: "Test", mac: "02:00:00:00:00:01", + targetMode: .custom, customTarget: "192.0.2.1", port: 9, + probeHost: "192.0.2.2", probePort: KotlinInt(value: 22), note: "Test", + createdAt: 1000, updatedAt: 2000, repeatCount: 3, repeatIntervalMs: 250, + probeEnabled: true, probeDelaySeconds: 20) + XCTAssertTrue(store.save(devices: [device])) + let result = store.load() + XCTAssertNil(result.failure) + let loaded = try XCTUnwrap(result.devices.first) + XCTAssertEqual(result.devices.count, 1) + XCTAssertEqual(loaded.id, device.id) + XCTAssertEqual(loaded.name, device.name) + XCTAssertEqual(loaded.mac, device.mac) + XCTAssertEqual(loaded.targetMode, device.targetMode) + XCTAssertEqual(loaded.customTarget, device.customTarget) + XCTAssertEqual(loaded.port, device.port) + XCTAssertEqual(loaded.probeHost, device.probeHost) + XCTAssertEqual(loaded.probePort, device.probePort) + XCTAssertEqual(loaded.note, device.note) + XCTAssertEqual(loaded.createdAt, device.createdAt) + XCTAssertEqual(loaded.updatedAt, device.updatedAt) + XCTAssertEqual(loaded.repeatCount, device.repeatCount) + XCTAssertEqual(loaded.repeatIntervalMs, device.repeatIntervalMs) + XCTAssertEqual(loaded.probeEnabled, device.probeEnabled) + XCTAssertEqual(loaded.probeDelaySeconds, device.probeDelaySeconds) + } + + func testOversizeFileIsRejectedWithoutReset() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let file = directory.appendingPathComponent("wol.json") + let oversized = Data(repeating: 0x61, count: 1_048_577) + try oversized.write(to: file) + let store = WolPersistence(directoryOverride: directory) + XCTAssertNotNil(store.load().failure) + XCTAssertEqual(try Data(contentsOf: file), oversized) + } + + func testStoreFailsWhenDirectoryIsAFile() throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let original = Data("unchanged".utf8) + try original.write(to: file) + let store = WolPersistence(directoryOverride: file) + XCTAssertEqual(store.load().failure, .io) + XCTAssertEqual(try Data(contentsOf: file), original) + XCTAssertFalse(store.save(devices: [])) + XCTAssertEqual(try Data(contentsOf: file), original) + } +} + +final class WolAddressPolicyTests: XCTestCase { + func testNetworkIdentityChangesOnlyForInterfaceAddressOrMask() { + let a = WolPlatform.NetworkIdentity(interfaceIndex: 1, address: 0xc0000201, mask: 0xffffff00) + XCTAssertEqual(a, WolPlatform.NetworkIdentity(interfaceIndex: 1, address: 0xc0000201, mask: 0xffffff00)) + XCTAssertNotEqual(a, WolPlatform.NetworkIdentity(interfaceIndex: 2, address: 0xc0000201, mask: 0xffffff00)) + XCTAssertNotEqual(a, WolPlatform.NetworkIdentity(interfaceIndex: 1, address: 0xc0000202, mask: 0xffffff00)) + XCTAssertNotEqual(a, WolPlatform.NetworkIdentity(interfaceIndex: 1, address: 0xc0000201, mask: 0xffff0000)) + } + + func testOnlyLocalUnicastIsAllowed() { + let address: UInt32 = 0xc000020a // 192.0.2.10 + let mask: UInt32 = 0xffffff00 + XCTAssertTrue(WolPlatform.permittedUnicast(0xc000020b, address: address, mask: mask)) + XCTAssertFalse(WolPlatform.permittedUnicast(0xc0000200, address: address, mask: mask)) + XCTAssertFalse(WolPlatform.permittedUnicast(0xc00002ff, address: address, mask: mask)) + XCTAssertFalse(WolPlatform.permittedUnicast(0xc6336401, address: address, mask: mask)) + XCTAssertFalse(WolPlatform.permittedUnicast(0xe0000001, address: address, mask: 0)) + XCTAssertFalse(WolPlatform.permittedUnicast(0xf0000001, address: address, mask: 0)) + XCTAssertFalse(WolPlatform.permittedUnicast(0x7f000001, address: address, mask: 0)) + XCTAssertFalse(WolPlatform.permittedUnicast(0x00000001, address: address, mask: 0)) + XCTAssertTrue(WolPlatform.permittedUnicast(0xc000020b, address: address, mask: 0xfffffffe)) + } +} diff --git a/iosApp/NetKitTests/LocalSshServer.swift b/iosApp/NetKitTests/LocalSshServer.swift new file mode 100644 index 0000000..cb08630 --- /dev/null +++ b/iosApp/NetKitTests/LocalSshServer.swift @@ -0,0 +1,160 @@ +@testable import NetKit +import Foundation +import Darwin +import Crypto +import NIOCore +import NIOPosix +import NIOSSH + +/// Loopback-only integration fixture. Keys and password exist only for this process. +final class LocalSshServer { + enum FixtureError: Error { case missingPort, unsupportedChannel } + let username = "test-user" + let password = UUID().uuidString + UUID().uuidString + let userKey = Curve25519.Signing.PrivateKey() + let hostKey: NIOSSHPrivateKey + private let group: MultiThreadedEventLoopGroup + private let state = ServerState() + private var listener: Channel? + private let stopLock = NSLock() + private var stopped = false + private(set) var port: Int = 0 + + init(hostKey: NIOSSHPrivateKey = NIOSSHPrivateKey(ed25519Key: .init())) { + self.hostKey = hostKey + self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + } + + func start(port requestedPort: Int = 0) async throws { + let allowedKey = NIOSSHPrivateKey(ed25519Key: userKey).publicKey + let authenticationValue = self.password + let username = self.username + let hostKey = self.hostKey + let state = self.state + do { + let channel = try await ServerBootstrap(group: group) + .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) + .childChannelInitializer { channel in + state.add(channel) + let auth = LocalAuthentication(username: username, credential: authenticationValue, allowedKey: allowedKey, state: state) + return channel.pipeline.addHandler(NIOSSHHandler( + role: .server(.init(hostKeys: [hostKey], userAuthDelegate: auth, banner: nil)), + allocator: channel.allocator, + inboundChildChannelInitializer: { child, type in + guard type == .session else { + return child.eventLoop.makeFailedFuture(FixtureError.unsupportedChannel) + } + state.addChild(child) + return child.pipeline.addHandler(LocalTerminal(state: state)) + } + )) + } + .bind(host: "127.0.0.1", port: requestedPort).get() + guard let actualPort = channel.localAddress?.port else { + try await channel.close().get() + throw FixtureError.missingPort + } + listener = channel + port = actualPort + } catch { + try? await shutdownGroup() + throw error + } + } + + private func markStopping() -> Bool { + stopLock.lock(); defer { stopLock.unlock() } + guard !stopped else { return false } + stopped = true + return true + } + func stop() async throws { + guard markStopping() else { return } + if let listener { try await listener.close().get(); self.listener = nil } + for channel in state.channels() where channel.isActive { try? await channel.close().get() } + try await shutdownGroup() + } + func closeSessions() async throws { + for channel in state.children() where channel.isActive { try await channel.close().get() } + } + var ptyRequests: Int { state.ptyCount() } + var shellRequests: Int { state.shellCount() } + var authSuccesses: Int { state.authCount() } + private func shutdownGroup() async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + group.shutdownGracefully { error in + if let error { continuation.resume(throwing: error) } + else { continuation.resume() } + } + } + } +} + +private final class ServerState: @unchecked Sendable { + private let lock = NSLock() + private var connections: [Channel] = [] + private var childConnections: [Channel] = [] + private var ptys = 0 + private var shells = 0 + private var authentications = 0 + func add(_ channel: Channel) { lock.lock(); connections.append(channel); lock.unlock() } + func channels() -> [Channel] { lock.lock(); defer { lock.unlock() }; return connections } + func addChild(_ channel: Channel) { lock.lock(); childConnections.append(channel); lock.unlock() } + func children() -> [Channel] { lock.lock(); defer { lock.unlock() }; return childConnections } + func pty() { lock.lock(); ptys += 1; lock.unlock() } + func shell() { lock.lock(); shells += 1; lock.unlock() } + func auth() { lock.lock(); authentications += 1; lock.unlock() } + func authCount() -> Int { lock.lock(); defer { lock.unlock() }; return authentications } + func ptyCount() -> Int { lock.lock(); defer { lock.unlock() }; return ptys } + func shellCount() -> Int { lock.lock(); defer { lock.unlock() }; return shells } +} + +private final class LocalAuthentication: NIOSSHServerUserAuthenticationDelegate { + let username: String + let expectedValue: String + let allowedKey: NIOSSHPublicKey + let state: ServerState + init(username: String, credential: String, allowedKey: NIOSSHPublicKey, state: ServerState) { + self.username = username; self.expectedValue = credential; self.allowedKey = allowedKey; self.state = state + } + var supportedAuthenticationMethods: NIOSSHAvailableUserAuthenticationMethods { [.password, .publicKey] } + func requestReceived(request: NIOSSHUserAuthenticationRequest, + responsePromise: EventLoopPromise) { + guard request.username == username else { responsePromise.succeed(.failure); return } + let valid: Bool + switch request.request { + case .password(let candidate): valid = candidate.password == expectedValue + case .publicKey(let candidate): valid = candidate.publicKey == allowedKey + default: valid = false + } + if valid { state.auth() } + responsePromise.succeed(valid ? .success : .failure) + } +} + +/// A deterministic echo endpoint; it does not execute local commands. +private final class LocalTerminal: ChannelInboundHandler { + typealias InboundIn = SSHChannelData + typealias OutboundOut = SSHChannelData + private let state: ServerState + init(state: ServerState) { self.state = state } + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { + switch event { + case let request as SSHChannelRequestEvent.PseudoTerminalRequest: + state.pty() + if request.wantReply { context.channel.triggerUserOutboundEvent(ChannelSuccessEvent(), promise: nil) } + case let request as SSHChannelRequestEvent.ShellRequest: + state.shell() + if request.wantReply { context.channel.triggerUserOutboundEvent(ChannelSuccessEvent(), promise: nil) } + default: + context.fireUserInboundEventTriggered(event) + } + } + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + let data = unwrapInboundIn(data) + guard case .channel = data.type, case .byteBuffer = data.data else { + context.close(promise: nil); return + } + context.writeAndFlush(wrapOutboundOut(data), promise: nil) + } +} diff --git a/iosApp/NetKitTests/NetKitTests.swift b/iosApp/NetKitTests/NetKitTests.swift new file mode 100644 index 0000000..cc5ad39 --- /dev/null +++ b/iosApp/NetKitTests/NetKitTests.swift @@ -0,0 +1,26 @@ +@testable import NetKit +import XCTest +import NetKitShared + +final class NetKitTests: XCTestCase { + func testPrivacyUrlsAndOfflineLicenses() throws { + let domain = IosAboutDomain() + XCTAssertEqual(domain.privacyUrl(language: "cs"), "https://www.daniel.losak.cz/netkit/privacy") + XCTAssertEqual(domain.privacyUrl(language: "en"), "https://www.daniel.losak.cz/en/netkit/privacy") + XCTAssertEqual(domain.privacyUrl(language: "de"), "https://www.daniel.losak.cz/en/netkit/privacy") + let url = try XCTUnwrap(Bundle.main.url(forResource: "OpenSourceLicenses", withExtension: "txt")) + let licenses = try String(contentsOf: url, encoding: .utf8) + for component in ["swift-nio-ssh 0.15.1", "swift-nio 2.84.0", "swift-crypto 3.12.3", + "swift-atomics 1.3.0", "swift-collections 1.2.0", "swift-system 1.5.0", + "swift-asn1 1.4.0", "Kotlin 2.2.20", "kotlinx-coroutines 1.10.2", + "kotlinx-serialization 1.9.0", "kotlinx-atomicfu 0.26.1"] { + XCTAssertTrue(licenses.contains(component), component) + } + XCTAssertTrue(licenses.contains("Apache License")) + } + + func testSharedIpv4Parser() { + XCTAssertEqual(WolDomainKt.parseIpv4(input: "192.0.2.1")?.description, "192.0.2.1") + XCTAssertNil(WolDomainKt.parseIpv4(input: "192.0.2.256")) + } +} diff --git a/iosApp/NetKitTests/SpeedTests.swift b/iosApp/NetKitTests/SpeedTests.swift new file mode 100644 index 0000000..4b6e130 --- /dev/null +++ b/iosApp/NetKitTests/SpeedTests.swift @@ -0,0 +1,374 @@ +@testable import NetKit +import XCTest +import Foundation +import NetKitShared + +private final class SpeedMockProtocol: URLProtocol { + private static let lock = NSLock() + private static var posts = 0 + static func reset() { lock.lock(); posts = 0; lock.unlock() } + static func postCount() -> Int { lock.lock(); defer { lock.unlock() }; return posts } + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + if request.url?.path == "/wait" { return } + let isDownload = request.url?.path == "/download" + let body = isDownload ? Data(repeating: 42, count: 1_048_576) : Data() + if request.httpMethod == "POST" { + Self.lock.lock(); Self.posts += 1; Self.lock.unlock() + } + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/octet-stream", "Content-Length": "\(body.count)"])! + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: body) + client?.urlProtocolDidFinishLoading(self) + } + override func stopLoading() {} +} + +final class SpeedTests: XCTestCase { + private func fixture() -> SpeedHTTP { + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [SpeedMockProtocol.self] + return SpeedHTTP(configuration: config) + } + + func testBoundedDownloadAndUpload() async throws { + let http = fixture() + let counter = SpeedCounter() + let base = URL(string: "https://example.invalid")! + try await http.download(URLRequest(url: base.appendingPathComponent("download")), counter: counter) + XCTAssertEqual(counter.snapshot().0, 1_048_576) + SpeedMockProtocol.reset() + var request = URLRequest(url: base.appendingPathComponent("upload")) + request.httpMethod = "POST" + try await http.upload(request, payload: Data(repeating: 42, count: 1024), counter: SpeedCounter()) + XCTAssertEqual(SpeedMockProtocol.postCount(), 1) + do { + _ = try await http.read(URLRequest(url: base.appendingPathComponent("download")), limit: 3) + XCTFail("An oversized response must be rejected") + } catch SpeedHTTP.Failure.responseTooLarge { } + } + + func testSharedServerAndNdtValidation() { + let domain = IosSpeedDomain() + XCTAssertNotNil(domain.libreServer(input: "https://example.invalid/")) + XCTAssertNil(domain.libreServer(input: "http://example.invalid/")) + XCTAssertTrue(domain.ndtTargets(text: "{} (invalid)").isEmpty) + let result = domain.ndtView(text: #"{"AppInfo":{"ElapsedTime":1000000,"NumBytes":1000000}}"#, download: true) + XCTAssertEqual(result?.appMbps?.doubleValue, 8) + } + + func testCancelPendingRead() async throws { + let http = fixture() + let task = Task { try await http.read(URLRequest(url: URL(string: "https://example.invalid/wait")!), limit: 512) } + try await Task.sleep(nanoseconds: 100_000_000) + task.cancel() + do { + _ = try await task.value + XCTFail("The pending read should be cancelled") + } catch let error as URLError where error.code == .cancelled { } + catch is CancellationError { } + catch { XCTFail("Unexpected error: \(error)") } + } +} + +private final class FakeSpeedTransport: SpeedTransport { + private let lock = NSLock() + private var downloads = 0 + private var uploads = 0 + let failDownload: Bool + init(failDownload: Bool = false) { self.failDownload = failDownload } + func counts() -> (Int, Int) { lock.lock(); defer { lock.unlock() }; return (downloads, uploads) } + private func countDownload() { lock.lock(); downloads += 1; lock.unlock() } + private func countUpload() { lock.lock(); uploads += 1; lock.unlock() } + func read(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) { + (Data(), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } + func download(_ request: URLRequest, counter: SpeedCounter) async throws { + countDownload() + if failDownload { throw URLError(.cannotConnectToHost) } + for _ in 0..<10 { try await Task.sleep(nanoseconds: 50_000_000); counter.add(100_000) } + } + func upload(_ request: URLRequest, payload: Data, counter: SpeedCounter) async throws { + countUpload() + for _ in 0..<10 { try await Task.sleep(nanoseconds: 50_000_000); counter.add(100_000) } + } +} + +private final class LimitedUploadTransport: SpeedTransport { + private let lock = NSLock() + private var sizes: [Int] = [] + enum Mode { case limited, always413, otherFailure } + let mode: Mode + init(mode: Mode = .limited) { self.mode = mode } + private func record(_ size: Int) { lock.lock(); sizes.append(size); lock.unlock() } + func attemptedSizes() -> [Int] { lock.lock(); defer { lock.unlock() }; return sizes } + func read(_ request: URLRequest, limit: Int) async throws -> (Data, HTTPURLResponse) { + (Data(), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } + func download(_ request: URLRequest, counter: SpeedCounter) async throws { + try await Task.sleep(nanoseconds: 50_000_000); counter.add(100_000) + } + func upload(_ request: URLRequest, payload: Data, counter: SpeedCounter) async throws { + record(payload.count) + if mode == .otherFailure { throw SpeedHTTP.Failure.invalidResponse } + if mode == .always413 || payload.count > 256 * 1024 { throw SpeedHTTP.Failure.payloadTooLarge } + try await Task.sleep(nanoseconds: 50_000_000); counter.add(Int64(payload.count)) + } +} + +private actor AsyncTestSignal { + private var signaled = false + private var waiter: CheckedContinuation? + func wait() async { + if signaled { return } + await withCheckedContinuation { waiter = $0 } + } + func signal() { + signaled = true + waiter?.resume() + waiter = nil + } +} + +private final class FakeNdtSocket: NdtSocket { + enum End: Error { case broken } + private let lock = NSLock() + private var reads = 0 + private var sends = 0 + private var closed = false + private var normal = false + private var sendFailedBeforeReader = false + private var readerFinished = false + private let sendFailureSignal = AsyncTestSignal() + private var startedAt: TimeInterval = 0 + private var appInfoDelivered = false + let download: Bool + let failAfterData: Bool + let streaming: Bool + let closeDuringUpload: Bool + let failOpen: Bool + let noData: Bool + init(download: Bool, failAfterData: Bool = false, streaming: Bool = false, + closeDuringUpload: Bool = false, failOpen: Bool = false, noData: Bool = false) { + self.download = download; self.failAfterData = failAfterData; self.streaming = streaming + self.closeDuringUpload = closeDuringUpload; self.failOpen = failOpen; self.noData = noData + } + var normalClosure: Bool { lock.lock(); defer { lock.unlock() }; return normal } + func open() async throws { + if failOpen { throw End.broken } + lock.lock(); startedAt = ProcessInfo.processInfo.systemUptime; lock.unlock() + } + private func nextRead() -> Int { lock.lock(); defer { lock.unlock() }; reads += 1; return reads } + private func recordSend() { lock.lock(); sends += 1; lock.unlock() } + func state() -> (Int, Bool) { lock.lock(); defer { lock.unlock() }; return (sends, closed) } + func readCount() -> Int { lock.lock(); defer { lock.unlock() }; return reads } + func wasSendFailureFirst() -> Bool { lock.lock(); defer { lock.unlock() }; return sendFailedBeforeReader } + private func markAppInfoDelivered() { lock.lock(); appInfoDelivered = true; lock.unlock() } + private func considerNormalClose() { + lock.lock(); defer { lock.unlock() } + // open() starts this clock just before the client starts its own; leave a margin over 95%. + if closeDuringUpload && appInfoDelivered && sends > 1 && + ProcessInfo.processInfo.systemUptime - startedAt >= 3 * 0.96 { normal = true } + } + private func markReaderFinished() { lock.lock(); readerFinished = true; lock.unlock() } + private func checkSendFailure() -> Bool { + lock.lock(); defer { lock.unlock() } + if normal { sendFailedBeforeReader = !readerFinished; return true } + return false + } + func receive() async throws -> URLSessionWebSocketTask.Message { + let number = nextRead() + if noData { + try await Task.sleep(nanoseconds: 30_000_000_000) + throw CancellationError() + } + if number == 1 { + if download { return .data(Data(repeating: 42, count: 1_048_576)) } + markAppInfoDelivered() + return .string(#"{"AppInfo":{"ElapsedTime":1000000,"NumBytes":1000000}}"#) + } + if failAfterData { throw End.broken } + if download && streaming { + try await Task.sleep(nanoseconds: 50_000_000) + return .data(Data(repeating: 42, count: 65_536)) + } + if !download && closeDuringUpload { + await sendFailureSignal.wait() + markReaderFinished() + throw End.broken + } + try await Task.sleep(nanoseconds: 30_000_000_000) + throw CancellationError() + } + func send(_ message: URLSessionWebSocketTask.Message) async throws { + recordSend(); try await Task.sleep(nanoseconds: 10_000_000) + considerNormalClose() + if checkSendFailure() { await sendFailureSignal.signal(); throw End.broken } + } + func close() { + lock.lock(); closed = true; lock.unlock() + Task { await sendFailureSignal.signal() } + } +} + +extension SpeedTests { + func testLibreSpeedReducesRejectedUploadToMinimum() async throws { + let transport = LimitedUploadTransport() + let result = try await LibreSpeedClient(http: transport, phaseDuration: 2.0) + .measure(input: "https://example.invalid/") + let sizes = transport.attemptedSizes() + XCTAssertTrue(sizes.contains(8 * 1_048_576)) + XCTAssertTrue(sizes.contains(256 * 1024)) + XCTAssertFalse(sizes.contains { $0 < 256 * 1024 }) + XCTAssertGreaterThan(result.uploadMbps, 0) + } + + func testUploadSizingIgnoresStale413AfterSmallerBodyAccepted() { + let sizing = UploadSizing() + let old = sizing.current() + XCTAssertTrue(sizing.reduce(after: old)) + let smaller = sizing.current() + sizing.markAccepted() + XCTAssertTrue(sizing.reduce(after: old)) + XCTAssertEqual(sizing.current(), smaller) + XCTAssertFalse(sizing.reduce(after: smaller)) + } + + func testPermanent413StopsAtMinimumAndFails() async throws { + let transport = LimitedUploadTransport(mode: .always413) + do { + _ = try await LibreSpeedClient(http: transport, phaseDuration: 2.0).measure(input: "https://example.invalid/") + XCTFail("Permanent 413 must fail the measurement") + } catch SpeedFailure.incomplete { } + let sizes = transport.attemptedSizes() + XCTAssertTrue(sizes.contains(256 * 1024)) + XCTAssertFalse(sizes.contains { $0 < 256 * 1024 }) + XCTAssertLessThanOrEqual(sizes.count, 18) + } + + func testNon413DoesNotRetrySmallerBodies() async throws { + let transport = LimitedUploadTransport(mode: .otherFailure) + do { + _ = try await LibreSpeedClient(http: transport, phaseDuration: 2.0).measure(input: "https://example.invalid/") + XCTFail("A non-413 failure must fail the measurement") + } catch SpeedFailure.incomplete { } + XCTAssertFalse(transport.attemptedSizes().isEmpty) + XCTAssertTrue(transport.attemptedSizes().allSatisfy { $0 == 8 * 1_048_576 }) + } + + func testLibreSpeedRunsBothDirectionsAndFailsClosed() async throws { + let fake = FakeSpeedTransport() + let result = try await LibreSpeedClient(http: fake, phaseDuration: 1.5).measure(input: "https://example.invalid/") + XCTAssertGreaterThan(result.downloadMbps, 0) + XCTAssertGreaterThan(result.uploadMbps, 0) + XCTAssertGreaterThanOrEqual(fake.counts().0, 6) + XCTAssertGreaterThanOrEqual(fake.counts().1, 3) + do { + _ = try await LibreSpeedClient(http: FakeSpeedTransport(failDownload: true), phaseDuration: 1.5) + .measure(input: "https://example.invalid/") + XCTFail("A failed direction must not produce a result") + } catch { } + } + + func testLibreSpeedCancellation() async throws { + let task = Task { try await LibreSpeedClient(http: FakeSpeedTransport(), phaseDuration: 10) + .measure(input: "https://example.invalid/") } + try await Task.sleep(nanoseconds: 100_000_000) + task.cancel() + do { _ = try await task.value; XCTFail("Expected cancellation") } + catch is CancellationError { } + catch { XCTFail("Unexpected error: \(error)") } + } + + func testNdtDownloadWithoutDataIsIncomplete() async throws { + let socket = FakeNdtSocket(download: true, noData: true) + let client = Ndt7Client(duration: 1.5, grace: 0, socketFactory: { _, _ in socket }) + do { + _ = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: true) + XCTFail("A download without data must be incomplete") + } catch SpeedFailure.incomplete { } + XCTAssertTrue(socket.state().1) + } + + func testNdtBurstThenStallReturnsBoundedRate() async throws { + let socket = FakeNdtSocket(download: true) + let client = Ndt7Client(duration: 3, grace: 0, socketFactory: { _, _ in socket }) + let rate = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: true) + XCTAssertTrue(rate.isFinite) + XCTAssertGreaterThanOrEqual(rate, 0) + // One MiB total, divided by at least 1000 ms of measured time. + XCTAssertLessThanOrEqual(rate, 8.388_609) + XCTAssertGreaterThanOrEqual(socket.readCount(), 2) + XCTAssertTrue(socket.state().1) + } + + func testSharedBurstThenStallHasZeroPostWarmupRate() throws { + let domain = IosSpeedDomain() + let trace = domain.createTrace() + for tick in 1...12 { + XCTAssertTrue(trace.add(elapsedMs: Int64(tick * 250), bytes: 1_048_576)) + } + let summary = try XCTUnwrap(domain.summarize(trace: trace)) + XCTAssertEqual(summary.mbps, 0, accuracy: 0.000_001) + } + + func testNdtFlowingDownloadProducesRate() async throws { + let socket = FakeNdtSocket(download: true, streaming: true) + let client = Ndt7Client(duration: 3, grace: 0, socketFactory: { _, _ in socket }) + let rate = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: true) + XCTAssertGreaterThan(rate, 0) + } + + func testNdtUploadUsesServerRate() async throws { + let socket = FakeNdtSocket(download: false) + let client = Ndt7Client(duration: 3, grace: 0, socketFactory: { _, _ in socket }) + let rate = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: false) + XCTAssertEqual(rate, 8) + XCTAssertGreaterThan(socket.state().0, 0) + } + + func testNdtBrokenConnectionFails() async throws { + let socket = FakeNdtSocket(download: true, failAfterData: true) + let client = Ndt7Client(duration: 1.5, grace: 0, socketFactory: { _, _ in socket }) + do { + _ = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: true) + XCTFail("Broken socket must fail") + } catch SpeedFailure.incomplete { } + } + + func testNdtCancellationClosesSocket() async throws { + let socket = FakeNdtSocket(download: true) + let client = Ndt7Client(duration: 10, grace: 0, socketFactory: { _, _ in socket }) + let task = Task { try await client.direction(url: URL(string: "wss://example.invalid/")!, download: true) } + try await Task.sleep(nanoseconds: 100_000_000) + task.cancel() + do { _ = try await task.value; XCTFail("Expected cancellation") } + catch is CancellationError { } + catch { XCTFail("Unexpected error: \(error)") } + XCTAssertTrue(socket.state().1) + } +} + + +extension SpeedTests { + func testNdtUploadNormalCloseAfterSendError() async throws { + let socket = FakeNdtSocket(download: false, closeDuringUpload: true) + let client = Ndt7Client(duration: 3, grace: 0.2, socketFactory: { _, _ in socket }) + let result = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: false) + XCTAssertEqual(result, 8) + XCTAssertTrue(socket.wasSendFailureFirst()) + } + + func testNdtOpenFailureStartsNoTransfer() async throws { + let socket = FakeNdtSocket(download: false, failOpen: true) + let client = Ndt7Client(duration: 1.5, grace: 0, socketFactory: { _, _ in socket }) + do { + _ = try await client.direction(url: URL(string: "wss://example.invalid/")!, download: false) + XCTFail("Failed handshake must fail the direction") + } catch FakeNdtSocket.End.broken { } + XCTAssertEqual(socket.state().0, 0) + XCTAssertTrue(socket.state().1) + } +} diff --git a/iosApp/NetKitTests/SshIntegrationTests.swift b/iosApp/NetKitTests/SshIntegrationTests.swift new file mode 100644 index 0000000..6b1b2ee --- /dev/null +++ b/iosApp/NetKitTests/SshIntegrationTests.swift @@ -0,0 +1,321 @@ +@testable import NetKit +import XCTest +import Foundation +import CryptoKit +import NIOSSH +import NetKitShared + +private final class PendingSshApproval { + private let lock = NSLock() + private var callback: ((Bool) -> Void)? + func set(_ callback: @escaping (Bool) -> Void) { lock.lock(); self.callback = callback; lock.unlock() } + func accept() { lock.lock(); let callback = self.callback; self.callback = nil; lock.unlock(); callback?(true) } +} + +private final class SshTestDiagnostics { + private let lock = NSLock() + private var events: [String] = [] + + func recordState(_ state: SshTransport.State) { + let name: String + switch state { + case .connected: name = "state.connected" + case .closed: name = "state.closed" + case .failed: name = "state.failed" + case .algorithmFailure: name = "state.algorithmFailure" + } + append(name) + } + + func recordUnexpectedPrompt() { append("validator.unexpectedPrompt") } + + func recordFailure(_ failure: SshHostKeyValidator.Failure) { + let name: String + switch failure { + case .invalid: name = "validator.invalid" + case .changed: name = "validator.changed" + case .rejected: name = "validator.rejected" + case .storage: name = "validator.storage" + case .cancelled: name = "validator.cancelled" + case .timeout: name = "validator.timeout" + } + append(name) + } + + private func append(_ event: String) { + lock.lock(); events.append(event); lock.unlock() + } + func snapshot() -> [String] { + lock.lock(); defer { lock.unlock() } + return events + } +} + +final class SshIntegrationTests: XCTestCase { + @MainActor + func testSceneLifecycleDisconnectsAfterInjectedSleepInclusiveDeadline() async throws { + let server = LocalSshServer() + try await server.start() + addTeardownBlock { try await server.stop() } + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? chain.deleteServiceItems() } + var now: Int64 = 1000 + let model = SshViewModel(nowMillis: { now }, keychain: chain, directory: directory) + let credential = server.password + XCTAssertTrue(model.saveProfile(id: nil, name: "profile", host: "127.0.0.1", port: String(server.port), + username: server.username, keyRef: nil, password: credential)) + let profile = try XCTUnwrap(model.data?.profiles.first) + model.connect(profile) + for _ in 0..<150 where model.hostPrompt == nil { try await Task.sleep(nanoseconds: 100_000_000) } + let prompt = try XCTUnwrap(model.hostPrompt) + model.answerHost(id: prompt.id, accept: true) + for _ in 0..<150 where !model.connected { try await Task.sleep(nanoseconds: 100_000_000) } + XCTAssertTrue(model.connected) + model.background() + now += 299_999 + model.foreground() + XCTAssertTrue(model.connected) + model.background() + now += 300_000 + model.foreground() + XCTAssertFalse(model.connected) + } + + private func store() throws -> SshMetadataStore { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + addTeardownBlock { try? FileManager.default.removeItem(at: directory) } + return try SshMetadataStore(directory: directory) + } + + private func roundTripCredential(_ raw: Data) throws -> Data { + let keychain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + let adapter = IosSecretStoreAdapter(backend: KeychainSecretBackend(keychain: keychain)) + let id = UUID().uuidString + addTeardownBlock { _ = adapter.deleteSecret(id: id) } + let input = KotlinByteArray(size: Int32(raw.count)) + for (index, value) in raw.enumerated() { input.set(index: Int32(index), value: Int8(bitPattern: value)) } + guard adapter.putSecret(id: id, secret: input) == nil else { throw SshTransportFailure.invalidCredential } + let result = adapter.getSecret(id: id) + guard result.failure == nil, let bytes = result.bytes else { throw SshTransportFailure.invalidCredential } + return Data((0.. TrustedHostKey { + let key = NIOSSHPrivateKey(ed25519Key: Curve25519.Signing.PrivateKey()).publicKey + let parts = String(openSSHPublicKey: key).split(separator: " ") + let raw = try XCTUnwrap(Data(base64Encoded: String(parts[1]))) + let fingerprint = "SHA256:" + Data(SHA256.hash(data: raw)).base64EncodedString().replacingOccurrences(of: "=", with: "") + return TrustedHostKey(endpoint: "[192.0.2.1]:22", algorithm: String(parts[0]), + publicKey: String(parts[1]), fingerprint: fingerprint) + } + + func testFirstTrustPersistsChangedKeyRejectedAndResetIsExplicit() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let first = try offered() + let changed = try offered() + let store = try SshMetadataStore(directory: directory) + XCTAssertEqual(store.decision(first), .unknown) + try store.trustUnknown(first) + XCTAssertEqual(store.decision(first), .trusted) + XCTAssertEqual(store.decision(changed), .changed) + XCTAssertThrowsError(try store.trustUnknown(changed)) + try store.reject(changed) + let reopened = try SshMetadataStore(directory: directory) + XCTAssertEqual(reopened.decision(first), .trusted) + XCTAssertEqual(reopened.decision(changed), .changed) + try reopened.forget(endpoint: first.endpoint) + XCTAssertEqual(reopened.decision(changed), .unknown) + XCTAssertEqual(reopened.snapshot().rejectedHostKeys.count, 1) + } + + func testCorruptMetadataFailsClosed() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let file = directory.appendingPathComponent("ssh.json") + let contents = Data("invalid".utf8) + try contents.write(to: file) + XCTAssertThrowsError(try SshMetadataStore(directory: directory)) + XCTAssertEqual(try Data(contentsOf: file), contents) + } +} + +/// Profile exchange and connection gating use synthetic metadata and no network transport. +final class SshProfileExchangeTests: XCTestCase { + private let domain = IosSshDomain() + + private func profile(_ id: String = "profile-a", name: String = "Target", authentication: SshAuthentication = .password, + secretRef: String? = nil, keyRef: String? = nil, command: String = "") throws -> SshProfile { + try XCTUnwrap(domain.profile(id: id, name: name, host: "192.0.2.1", port: 22, username: "tester", + authentication: authentication, secretRef: secretRef, keyRef: keyRef, startupCommand: command, keepaliveSeconds: 30)) + } + + private func bytes(_ value: Data) -> KotlinByteArray { + let result = KotlinByteArray(size: Int32(value.count)) + for (index, byte) in value.enumerated() { result.set(index: Int32(index), value: Int8(bitPattern: byte)) } + return result + } + + private func raw(_ value: KotlinByteArray) -> Data { + Data((0.. Data { + var row: [String: Any] = ["alias": "Target", "host": host, "port": port, "username": username] + if schema == 2 { + row["authentication"] = authentication; row["startupCommand"] = command; row["keepaliveSeconds"] = keepalive + } + return try JSONSerialization.data(withJSONObject: ["format": "netkit-ssh-profiles", "schema": schema, + "profiles": [row], "skipped": []]) + } + + private func withStorage(_ body: (URL, KeychainSecrets) throws -> Void) throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root); try? chain.deleteServiceItems() } + try body(root, chain) + } + + func testBridgeExportV2IsOrderedPortableAndDecodable() throws { + try withStorage { root, _ in + let store = try SshMetadataStore(directory: root) + try store.save(profile: profile(secretRef: "credential-a", keyRef: "key-a", command: "show version")) + try store.save(profile: profile("profile-b", name: "Second", authentication: .key)) + try store.save(key: SshKeyInfo(id: "key-a", name: "Key", publicKey: "public")) + let result = store.prepareExport() + XCTAssertNil(result.failure) + let encoded = try XCTUnwrap(result.bytes) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: raw(encoded)) as? [String: Any]) + XCTAssertEqual(json["schema"] as? Int, 2) + XCTAssertEqual(json["format"] as? String, "netkit-ssh-profiles") + let rows = try XCTUnwrap(json["profiles"] as? [[String: Any]]) + XCTAssertEqual(rows.compactMap { $0["alias"] as? String }, ["Target", "Second"]) + for row in rows { + XCTAssertEqual(Set(row.keys), Set(["alias", "host", "port", "username", "authentication", "startupCommand", "keepaliveSeconds"])) + } + XCTAssertEqual(Set(json.keys), Set(["format", "schema", "source", "profiles", "skipped"])) + XCTAssertEqual(domain.decodeImport(bytes: encoded).imported?.profiles.count, 2) + } + } + + @MainActor + func testPreparedExportIsFrozenAndCancelledExplicitly() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + try store.save(profile: profile()) + let model = SshViewModel(keychain: chain, directory: root) + let prepared = try XCTUnwrap(model.prepareExport()) + XCTAssertTrue(model.saveProfile(id: "profile-a", name: "Renamed", host: "192.0.2.2", port: "22", username: "tester", keyRef: nil, password: "")) + XCTAssertEqual(model.exportData, prepared) + XCTAssertNotEqual(model.prepareExport(), prepared) + model.cancelExport() + XCTAssertNil(model.exportData) + } + } + + @MainActor + func testExportDuplicateNamesAndSizeNeverProduceBytes() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + try store.save(profile: profile()) + let model = SshViewModel(keychain: chain, directory: root) + XCTAssertNotNil(model.prepareExport()) + XCTAssertTrue(model.saveProfile(id: nil, name: "Target", host: "192.0.2.2", port: "22", username: "tester", keyRef: nil, password: "")) + XCTAssertNil(model.prepareExport()) + XCTAssertEqual(model.exportFailure, .duplicateNames(["Target"])) + XCTAssertNil(model.exportData) + } + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + for index in 1...65 { + try store.save(profile: profile("p-\(index)", name: "Target \(index)", command: String(repeating: "x", count: 4096))) + } + let model = SshViewModel(keychain: chain, directory: root) + XCTAssertNil(model.prepareExport()) + XCTAssertEqual(model.exportFailure, .tooLarge) + XCTAssertNil(model.exportData) + } + } + + func testBridgeImportAcceptsV1V2LegacyAndRejectsCredentialBackup() throws { + try withStorage { root, _ in + let store = try SshMetadataStore(directory: root) + let legacy: [String: Any] = ["schema": 1, "profiles": [["id": "old-id", "name": "Target", "host": "192.0.2.1", "port": 22, + "username": "tester", "authentication": "KEY", "startupCommand": "", "keepaliveSeconds": 30, + "secretRef": NSNull(), "keyRef": NSNull()]], "keys": [], "hostKeys": [], "rejectedHostKeys": []] + let legacyRaw = try JSONSerialization.data(withJSONObject: legacy) + for input in [try document(schema: 1), try document(), legacyRaw] { + let plan = try store.previewImport(input) + let preview = try XCTUnwrap(domain.importProfilePreviews(plan: plan, data: store.snapshot()).first) + XCTAssertNil(preview.before) + XCTAssertNotEqual(preview.after.id, "old-id") + XCTAssertNil(preview.after.secretRef) + XCTAssertNil(preview.after.keyRef) + } + for field in ["keys", "hostKeys", "rejectedHostKeys"] { + var backup = legacy; backup[field] = [["id": "not-portable"]] + XCTAssertThrowsError(try store.previewImport(JSONSerialization.data(withJSONObject: backup))) + } + } + } + + @MainActor + func testImportKeyChoiceReplansNewProfilesAndWarnings() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + try store.save(key: SshKeyInfo(id: "key-a", name: "Key", publicKey: "public")) + let model = SshViewModel(keychain: chain, directory: root) + let file = root.appendingPathComponent("import.json") + try document(schema: 1).write(to: file) + model.previewImport(file) + var preview = try XCTUnwrap(model.importPreviews(try XCTUnwrap(model.importPlan)).first) + XCTAssertEqual(preview.after.authentication, .password) + model.selectImportKey("key-a") + preview = try XCTUnwrap(model.importPreviews(try XCTUnwrap(model.importPlan)).first) + XCTAssertEqual(preview.after.authentication, .key) + XCTAssertEqual(preview.after.keyRef, "key-a") + XCTAssertFalse(preview.needsKeySelection) + model.selectImportKey(nil) + XCTAssertEqual(model.importPreviews(try XCTUnwrap(model.importPlan)).first?.after.authentication, .password) + try document().write(to: file) + model.previewImport(file) + preview = try XCTUnwrap(model.importPreviews(try XCTUnwrap(model.importPlan)).first) + XCTAssertTrue(preview.needsKeySelection) + XCTAssertTrue(preview.startupWarning) + model.selectImportKey("key-a") + XCTAssertFalse(model.importPreviews(try XCTUnwrap(model.importPlan)).first?.needsKeySelection ?? true) + model.selectImportKey("missing-key") + XCTAssertNil(model.importPlan) + model.selectImportKey(nil) + XCTAssertNotNil(model.importPlan) + model.cancelImport() + XCTAssertNil(model.importPlan) + XCTAssertNil(model.importKeyRef) + } + } + + @MainActor + func testImportPreviewShowsSixChangesAndDeletesPasswordOnlyOnConfirmation() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + let reference = UUID().uuidString + let password = Data(UUID().uuidString.utf8) + try store.save(profile: profile(secretRef: reference)) + try chain.put(reference, secret: password) + let model = SshViewModel(keychain: chain, directory: root) + let file = root.appendingPathComponent("import.json") + try document(host: "192.0.2.2", port: 2222, username: "operator", keepalive: 60).write(to: file) + model.previewImport(file) + let plan = try XCTUnwrap(model.importPlan) + let preview = try XCTUnwrap(model.importPreviews(plan).first) + XCTAssertEqual(preview.changes.map(\.field), [.host, .port, .username, .authentication, .startupCommand, .keepaliveSeconds]) + XCTAssertEqual(preview.changes.map(\.before), ["192.0.2.1", "22", "tester", "PASSWORD", "", "30"]) + XCTAssertEqual(preview.changes.map(\.after), ["192.0.2.2", "2222", "operator", "KEY", "show version", "60"]) + XCTAssertTrue(preview.startupWarning) + XCTAssertTrue(preview.needsKeySelection) + XCTAssertEqual(try chain.get(reference), password) + model.confirmImport() + XCTAssertNil(try chain.get(reference)) + XCTAssertNil(model.data?.profiles.first?.secretRef) + XCTAssertEqual(model.data?.profiles.first?.authentication, .key) + } + } + + @MainActor + func testAuthenticationOnlyImportCleansKeychainAfterPersistAndKeepsItOnFailure() throws { + for failPersistence in [false, true] { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + let reference = UUID().uuidString + let password = Data(UUID().uuidString.utf8) + try store.save(profile: profile(secretRef: reference)) + try chain.put(reference, secret: password) + let model = SshViewModel(keychain: chain, directory: root) + let file = root.appendingPathComponent("import.json") + try document(command: "").write(to: file) + model.previewImport(file) + let preview = try XCTUnwrap(model.importPreviews(try XCTUnwrap(model.importPlan)).first) + XCTAssertEqual(preview.changes.map(\.field), [.authentication]) + if failPersistence { + try FileManager.default.removeItem(at: root) + try Data(UUID().uuidString.utf8).write(to: root) + } + model.confirmImport() + if failPersistence { + XCTAssertEqual(try chain.get(reference), password) + XCTAssertEqual(model.data?.profiles.first?.secretRef, reference) + XCTAssertNotNil(model.error) + } else { + XCTAssertNil(try chain.get(reference)) + XCTAssertNil(try SshMetadataStore(directory: root).snapshot().profiles.first?.secretRef) + } + } + } + } + + @MainActor + func testStaleImportAndInvalidReplacementNeverApplyOldPlanOrDeletePassword() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + let reference = UUID().uuidString + let password = Data(UUID().uuidString.utf8) + try store.save(profile: profile(secretRef: reference)) + try chain.put(reference, secret: password) + let model = SshViewModel(keychain: chain, directory: root) + let file = root.appendingPathComponent("import.json") + try document().write(to: file) + model.previewImport(file) + XCTAssertTrue(model.saveProfile(id: "profile-a", name: "Edited", host: "192.0.2.1", port: "22", username: "tester", keyRef: nil, password: "")) + model.confirmImport() + XCTAssertNotNil(model.error) + XCTAssertEqual(try chain.get(reference), password) + model.previewImport(file) + XCTAssertNotNil(model.importPlan) + try Data("invalid".utf8).write(to: file) + model.previewImport(file) + XCTAssertNil(model.importPlan) + model.confirmImport() + XCTAssertEqual(model.data?.profiles.first?.name, "Edited") + } + } + + @MainActor + func testArrowMovementBoundsPreviewLockAndRestartExportOrder() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + try store.save(profile: profile()) + try store.save(profile: profile("profile-b", name: "Second")) + let model = SshViewModel(keychain: chain, directory: root) + XCTAssertFalse(model.canMoveProfile(id: "profile-a", delta: -1)) + XCTAssertFalse(model.canMoveProfile(id: "profile-b", delta: 1)) + XCTAssertFalse(model.canMoveProfile(id: "profile-a", delta: 2)) + XCTAssertFalse(model.canMoveProfile(id: "missing", delta: 1)) + var operationBlockedMovement = false + let observation = model.$exportData.dropFirst().sink { _ in + operationBlockedMovement = !model.canMoveProfile(id: "profile-a", delta: 1) + model.moveProfile(id: "profile-a", delta: 1) + } + XCTAssertNotNil(model.prepareExport()) + XCTAssertTrue(operationBlockedMovement) + XCTAssertEqual(model.data?.profiles.map(\.id), ["profile-a", "profile-b"]) + observation.cancel() + model.moveProfile(id: "profile-a", delta: -1) + model.moveProfile(id: "profile-b", delta: -1) + XCTAssertEqual(model.data?.profiles.map(\.id), ["profile-b", "profile-a"]) + model.moveProfile(id: "profile-b", delta: 1) + XCTAssertEqual(model.data?.profiles.map(\.id), ["profile-a", "profile-b"]) + model.moveProfile(id: "profile-a", delta: 1) + let reopened = SshViewModel(keychain: chain, directory: root) + XCTAssertEqual(reopened.data?.profiles.map(\.id), ["profile-b", "profile-a"]) + let prepared = try XCTUnwrap(reopened.prepareExport()) + XCTAssertEqual(domain.decodeImport(bytes: bytes(prepared)).imported?.profiles.map(\.alias), ["Second", "Target"]) + let file = root.appendingPathComponent("import.json") + try document(schema: 1).write(to: file) + reopened.previewImport(file) + XCTAssertFalse(reopened.canMoveProfile(id: "profile-b", delta: 1)) + reopened.moveProfile(id: "profile-b", delta: 1) + XCTAssertEqual(reopened.data?.profiles.map(\.id), ["profile-b", "profile-a"]) + } + } + + @MainActor + func testMissingAndDeletedKeyBlockConnectBeforeSessionFactory() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + try store.save(key: SshKeyInfo(id: "other-key", name: "Other", publicKey: "public")) + let missing = try profile(authentication: .key) + let deleted = try profile("profile-b", name: "Deleted key", authentication: .key, keyRef: "deleted-key") + try store.save(profile: missing); try store.save(profile: deleted) + var attempts = 0 + let model = SshViewModel(keychain: chain, directory: root, sessionFactory: { _, _, _, _, _ in + attempts += 1; throw SshTransportFailure.unavailable + }) + for candidate in [missing, deleted] { + model.connect(candidate) + XCTAssertEqual(model.keySelectionRequired?.id, candidate.id) + XCTAssertNil(model.error) + XCTAssertFalse(model.connected) + XCTAssertNil(model.terminalSnapshot) + XCTAssertTrue(model.needsKeySelection(candidate)) + XCTAssertEqual(model.profileForKeySelection()?.id, candidate.id) + XCTAssertEqual(model.profileForKeySelection(candidate)?.id, candidate.id) // Alert state may already be dismissed. + XCTAssertFalse(model.saveProfile(id: candidate.id, name: candidate.name, host: candidate.host, port: "22", username: "tester", keyRef: nil, password: "")) + XCTAssertEqual(model.data?.profiles.first(where: { $0.id == candidate.id })?.authentication, .key) + } + XCTAssertEqual(attempts, 0) + model.generateKey(name: "Replacement") + let key = try XCTUnwrap(model.data?.keys.last) + XCTAssertTrue(model.saveProfile(id: missing.id, name: missing.name, host: missing.host, port: "22", username: "tester", keyRef: key.id, password: "")) + XCTAssertFalse(model.needsKeySelection(try XCTUnwrap(model.data?.profiles.first))) + } + } + + @MainActor + func testDeletedProfileCannotBeOpenedSavedOrConnectedFromPendingPrompt() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + let missing = try profile(authentication: .key) + try store.save(profile: missing) + let model = SshViewModel(keychain: chain, directory: root, sessionFactory: { _, _, _, _, _ in + XCTFail("Deleted profile must not create a transport"); throw SshTransportFailure.unavailable + }) + model.connect(missing) + model.deleteProfile(missing) + XCTAssertNil(model.keySelectionRequired) + model.keySelectionRequired = missing // A delayed alert still holds the old request. + XCTAssertNil(model.profileForKeySelection()) + XCTAssertNil(model.profileForKeySelection(missing)) // The captured alert value is checked against live storage too. + XCTAssertTrue(model.profileUnavailable) + XCTAssertNil(model.keySelectionRequired) + XCTAssertFalse(model.saveProfile(id: missing.id, name: missing.name, host: missing.host, port: "22", username: "tester", keyRef: nil, password: "")) + model.connect(missing) + XCTAssertTrue(model.profileUnavailable) + XCTAssertTrue(try SshMetadataStore(directory: root).snapshot().profiles.isEmpty) + } + } + + @MainActor + func testReconnectChecksMissingKeyAndUsesExactConfirmedProfileWithoutTransport() throws { + try withStorage { root, chain in + let store = try SshMetadataStore(directory: root) + let reference = UUID().uuidString + try store.save(profile: profile(secretRef: reference)) + try chain.put(reference, secret: Data(UUID().uuidString.utf8)) + var attempts: [SshProfile] = [] + let fake = ProfileTestSession() + let model = SshViewModel(keychain: chain, directory: root, sessionFactory: { profile, _, _, _, state in + attempts.append(profile) + return (fake, { state(.closed) }) + }) + model.connect(try XCTUnwrap(model.data?.profiles.first)) + XCTAssertEqual(attempts.count, 1) + let file = root.appendingPathComponent("import.json") + try document(command: "").write(to: file) + model.previewImport(file); model.confirmImport() + let confirmed = try XCTUnwrap(model.reconnectProfile) + XCTAssertEqual(confirmed.authentication, .key) + model.reconnect(confirmed) + XCTAssertEqual(model.keySelectionRequired?.id, "profile-a") + XCTAssertEqual(attempts.count, 1) + XCTAssertTrue(model.saveProfile(id: "profile-a", name: "Target", host: "192.0.2.1", port: "22", + username: "tester", keyRef: nil, password: UUID().uuidString, authentication: .password)) + try document(authentication: "PASSWORD", command: "show version").write(to: file) + model.previewImport(file); model.confirmImport() + let confirmedPassword = try XCTUnwrap(model.reconnectProfile) + try document(authentication: "PASSWORD", command: "show clock", keepalive: 60).write(to: file) + model.previewImport(file); model.confirmImport() + model.reconnect(confirmedPassword) + XCTAssertEqual(attempts.count, 2) + XCTAssertEqual(attempts.last?.host, "192.0.2.1") + XCTAssertEqual(attempts.last?.startupCommand, "show version") + XCTAssertEqual(model.data?.profiles.first?.startupCommand, "show clock") + model.deleteProfile(try XCTUnwrap(model.data?.profiles.first)) + model.reconnect(confirmedPassword) + XCTAssertTrue(model.profileUnavailable) + XCTAssertNil(model.keySelectionRequired) + XCTAssertEqual(attempts.count, 2) + model.disconnect() + } + } +} + +private final class ProfileTestSession: NSObject, SshSession { + func send(text: String) -> Bool { true } + func resize(columns: Int32, rows: Int32) {} + func close() {} +} + +final class SshProfileEditorTests: XCTestCase { + func testInteractiveDraftRequiresExplicitSupportedChoiceAndKeyDraftDoesNotFallBack() throws { + let domain = IosSshDomain() + let interactive = try XCTUnwrap(domain.profile(id: "interactive", name: "Target", host: "192.0.2.1", port: 22, + username: "tester", authentication: .interactive, secretRef: nil, keyRef: nil, startupCommand: "", keepaliveSeconds: 30)) + var draft = SshProfileDraft(profile: interactive) + XCTAssertNil(draft.authentication) + draft.authenticationChoice = "PASSWORD" + XCTAssertEqual(draft.authentication, .password) + draft.authenticationChoice = "KEY" + XCTAssertEqual(draft.authentication, .key) + XCTAssertTrue(draft.needsKeySelection(keys: [SshKeyInfo(id: "other-key", name: "Other", publicKey: "public")])) + draft.keyRef = "other-key" + XCTAssertFalse(draft.needsKeySelection(keys: [SshKeyInfo(id: "other-key", name: "Other", publicKey: "public")])) + let keyProfile = try XCTUnwrap(domain.profile(id: "key-profile", name: "Key target", host: "192.0.2.1", port: 22, + username: "tester", authentication: .key, secretRef: nil, keyRef: "deleted-key", startupCommand: "", keepaliveSeconds: 30)) + let missing = SshProfileDraft(profile: keyProfile) + XCTAssertEqual(missing.authentication, .key) + XCTAssertTrue(missing.needsKeySelection(keys: [])) + } + + @MainActor + func testInteractiveImportShowsSpecificErrorWithoutTransportAndCanBeSavedAsPasswordOrKey() throws { + let choices: [SshAuthentication] = [.password, .key] + for choice in choices { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root); try? chain.deleteServiceItems() } + let store = try SshMetadataStore(directory: root) + let document = Data(""" + {"format":"netkit-ssh-profiles","schema":2,"profiles":[{"alias":"Target","host":"192.0.2.1","port":22,"username":"tester","authentication":"INTERACTIVE","startupCommand":"","keepaliveSeconds":30}],"skipped":[]} + """.utf8) + try store.applyImport(store.previewImport(document)) + var attempts = 0 + let model = SshViewModel(keychain: chain, directory: root, sessionFactory: { _, _, _, _, _ in + attempts += 1; throw SshTransportFailure.unavailable + }) + let imported = try XCTUnwrap(model.data?.profiles.first) + model.connect(imported) + XCTAssertEqual(attempts, 0) + XCTAssertEqual(model.error, .interactiveUnsupported) + XCTAssertNil(model.terminalSnapshot) + XCTAssertNil(model.keySelectionRequired) + model.generateKey(name: "Replacement") + let key = try XCTUnwrap(model.data?.keys.first) + XCTAssertTrue(model.saveProfile(id: imported.id, name: imported.name, host: imported.host, port: "22", username: imported.username, + keyRef: choice == .key ? key.id : nil, password: "", authentication: choice)) + XCTAssertNil(model.error) + XCTAssertEqual(model.data?.profiles.first?.authentication, choice) + XCTAssertEqual(try SshMetadataStore(directory: root).snapshot().profiles.first?.authentication, choice) + } + } + + @MainActor + func testExportDocumentRetainsValidatedSnapshotAndDuplicateNamesAreExplained() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root); try? chain.deleteServiceItems() } + let model = SshViewModel(keychain: chain, directory: root) + XCTAssertTrue(model.saveProfile(id: nil, name: "Alpha", host: "192.0.2.1", port: "22", username: "tester", keyRef: nil, password: "")) + let snapshot = try XCTUnwrap(model.prepareExport()) + let document = SshProfileDocument(contents: snapshot) + XCTAssertTrue(model.saveProfile(id: nil, name: "Beta", host: "192.0.2.2", port: "22", username: "tester", keyRef: nil, password: "")) + model.cancelExport() + XCTAssertEqual(document.contents, snapshot) + let rootObject = try XCTUnwrap(JSONSerialization.jsonObject(with: document.contents) as? [String: Any]) + XCTAssertEqual(rootObject["schema"] as? Int, 2) + XCTAssertEqual((rootObject["profiles"] as? [[String: Any]])?.count, 1) + let description = sshExportFailureMessage(.duplicateNames(["Alpha", "Beta"])) + XCTAssertTrue(description.contains("Alpha")) + XCTAssertTrue(description.contains("Beta")) + } +} + +extension SshProfileEditorTests { + @MainActor + func testProfilePersistenceFailureKeepsSpecificErrorMessage() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + let chain = KeychainSecrets(service: "cz.netkit.ios.tests." + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root); try? chain.deleteServiceItems() } + let model = SshViewModel(keychain: chain, directory: root) + XCTAssertNotNil(model.data) + try FileManager.default.removeItem(at: root) + try Data(UUID().uuidString.utf8).write(to: root) + XCTAssertFalse(model.saveProfile(id: nil, name: "Target", host: "192.0.2.1", port: "22", + username: "tester", keyRef: nil, password: "")) + let failure = try XCTUnwrap(model.error) + XCTAssertEqual(failure, .storage) + XCTAssertEqual(errorKey(failure), "ssh.error.storage") + XCTAssertNotEqual(errorKey(failure), errorKey(.invalid)) + XCTAssertNotEqual(errorKey(.credentials), errorKey(.invalid)) + XCTAssertNotEqual(errorKey(.interactiveUnsupported), errorKey(failure)) + } +} diff --git a/iosApp/NetKitTests/SshTerminalTests.swift b/iosApp/NetKitTests/SshTerminalTests.swift new file mode 100644 index 0000000..43c4829 --- /dev/null +++ b/iosApp/NetKitTests/SshTerminalTests.swift @@ -0,0 +1,47 @@ +@testable import NetKit +import NetKitShared +import XCTest +import UIKit + +final class SshTerminalTests: XCTestCase { + func testStyledOutputCursorAndInputSequences() { + let terminal = IosTerminal(columns: 80, rows: 24) + _ = terminal.feed(text: "\u{1b}[31;1mA\u{1b}[0mB") + let snapshot = terminal.snapshot() + let runs = snapshot.screen[0].runs + XCTAssertEqual(runs.first?.text, "A") + XCTAssertEqual(runs.first?.foreground, 1) + XCTAssertEqual(runs.first?.bold, true) + XCTAssertEqual(snapshot.cursorRow, 0) + XCTAssertEqual(snapshot.cursorColumn, 2) + XCTAssertTrue(snapshot.cursorVisible) + XCTAssertEqual(terminal.keySequence(key: .up, control: false, alt: false, shift: false), "\u{1b}[A") + XCTAssertEqual(terminal.textSequence(text: "c", control: true, alt: false), "\u{03}") + XCTAssertEqual(terminal.safePaste(text: "one\ntwo"), "one two") + XCTAssertTrue(terminal.pasteNeedsConfirmation(text: "one\ntwo")) + } + func testEmptyUnmarkedChangeClearsPendingComposition() { + let terminal = IosTerminal(columns: 80, rows: 24) + terminal.composeSet(value: "abc") + let keyboard = SshKeyboard(inputEpoch: UUID(), onComposition: { text, marked in + if marked { terminal.composeSet(value: text) } else { terminal.composeCommit(value: text) } + }, onKey: { _ in }, onPaste: { _ in }) + let coordinator = keyboard.makeCoordinator() + let input = UITextView() + input.text = "" + coordinator.textViewDidChange(input) + terminal.composeFinish() + XCTAssertEqual(terminal.drainInput(), "") + } + + func testPasteFlushesCompositionBeforeSanitizedInput() throws { + let terminal = IosTerminal(columns: 80, rows: 24) + terminal.composeSet(value: "a") + let (pending, paste) = try XCTUnwrap(SshTerminalInput.preparePaste(terminal: terminal, value: "b\nc")) + XCTAssertEqual(pending, "a") + XCTAssertEqual(paste, "b c") + terminal.composeFinish() + XCTAssertEqual(terminal.drainInput(), "") + } + +} diff --git a/iosApp/NetKitUITests/NetKitUITests.swift b/iosApp/NetKitUITests/NetKitUITests.swift new file mode 100644 index 0000000..2683f4f --- /dev/null +++ b/iosApp/NetKitUITests/NetKitUITests.swift @@ -0,0 +1,408 @@ +import XCTest +import Foundation + +final class NetKitUITests: XCTestCase { + func testEnglishLaunch() throws { + try assertLaunch(language: "en", locale: "en_US", overview: "Overview", about: "About", versionLabel: "Version", privacy: "Privacy policy", licenses: "Open source licenses", content: "License texts") + } + + func testCzechLaunch() throws { + try assertLaunch(language: "cs", locale: "cs_CZ", overview: "Přehled", about: "O aplikaci", versionLabel: "Verze", privacy: "Zásady ochrany soukromí", licenses: "Open source licence", content: "Texty licencí") + } + + func testToolNavigation() { + assertToolNavigation(language: "en", locale: "en_US", tabs: ["Overview", "Devices", "SSH", "WoL"], + tcp: "Probe TCP ports", devicesEmpty: "No results yet.", wifiCheck: "Check current Wi-Fi", + wifiEmpty: "Current Wi-Fi has not been checked yet.", + wifiUnavailable: "Current Wi-Fi details are unavailable. The system requires the appropriate entitlement and access conditions.", + speed: "Connection speed", speedStart: "Start measurement", wolSave: "Save profile", wolEmpty: "No devices yet.") + } + + func testCzechToolNavigation() { + assertToolNavigation(language: "cs", locale: "cs_CZ", tabs: ["Přehled", "Zařízení", "SSH", "WoL"], + tcp: "Prověřit TCP porty", devicesEmpty: "Zatím žádné výsledky.", wifiCheck: "Zjistit aktuální Wi-Fi", + wifiEmpty: "Aktuální Wi-Fi zatím nebyla zjištěna.", + wifiUnavailable: "Údaje o aktuální Wi-Fi nejsou dostupné. Systém vyžaduje příslušné oprávnění a splnění podmínek přístupu.", + speed: "Rychlost připojení", speedStart: "Spustit měření", wolSave: "Uložit profil", wolEmpty: "Zatím žádná zařízení.") + } + + func testSshEmptyState() { + assertSshEmptyState(language: "en", locale: "en_US", addProfile: "Add profile", empty: "No SSH profiles yet.") + } + + func testCzechSshEmptyState() { + assertSshEmptyState(language: "cs", locale: "cs_CZ", addProfile: "Přidat profil", empty: "Zatím žádné SSH profily.") + } + + func testEnglishLanConsentAndWolWarning() { + assertLanConsentAndWolWarning(language: "en", locale: "en_US", devices: "Devices", + host: "Target or name", ports: "Ports", tcp: "Probe TCP ports", cancel: "Cancel", + reason: "The range includes an address outside private, shared or link-local blocks.", + warning: "Use only on networks you own or are authorized to use. NetKit for iOS supports only unicast on the current Wi-Fi network. If a sleeping device is absent from the ARP cache, the packet may not arrive even when sending is reported as successful.") + } + + func testCzechLanConsentAndWolWarning() { + assertLanConsentAndWolWarning(language: "cs", locale: "cs_CZ", devices: "Zařízení", + host: "Cíl nebo název", ports: "Porty", tcp: "Prověřit TCP porty", cancel: "Zrušit", + reason: "Rozsah zahrnuje adresu mimo privátní, sdílené nebo link-local bloky.", + warning: "Používejte jen ve vlastní nebo povolené síti. iOS verze NetKitu podporuje pouze unicast v aktuální Wi-Fi síti. Pokud spící zařízení vypadne z ARP cache, paket nemusí dorazit ani po hlášení o odeslání.") + } + + private func assertLanConsentAndWolWarning(language: String, locale: String, devices: String, + host: String, ports: String, tcp: String, cancel: String, + reason: String, warning: String) { + let app = launch(language: language, locale: locale) + let tabs = app.tabBars.firstMatch.buttons + XCTAssertTrue(tabs[devices].waitForExistence(timeout: 10)) + tabs[devices].tap() + let hostField = app.textFields[host] + XCTAssertTrue(hostField.waitForExistence(timeout: 10)) + hostField.tap() + hostField.typeText("192.0.2.1") + let portField = app.textFields[ports] + portField.tap() + portField.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 2) + "22") + app.buttons[tcp].tap() + let reasonText = app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", reason)).firstMatch + XCTAssertTrue(reasonText.waitForExistence(timeout: 10)) + XCTAssertTrue(reasonText.isHittable) + app.buttons[cancel].tap() + let navigationReady = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + app.keyboards.count == 0 && app.tabBars.firstMatch.isHittable && tabs["WoL"].isHittable + }, object: app) + XCTAssertEqual(XCTWaiter.wait(for: [navigationReady], timeout: 10), .completed) + XCTAssertEqual(app.keyboards.count, 0) + XCTAssertTrue(app.tabBars.firstMatch.isHittable) + XCTAssertTrue(tabs["WoL"].isHittable) + tabs["WoL"].tap() + let warningText = app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", warning)).firstMatch + XCTAssertTrue(warningText.waitForExistence(timeout: 10)) + XCTAssertTrue(warningText.isHittable) + XCTAssertFalse(app.switches["Broadcast"].exists) + } + + private func assertToolNavigation(language: String, locale: String, tabs: [String], tcp: String, + devicesEmpty: String, wifiCheck: String, wifiEmpty: String, wifiUnavailable: String, + speed: String, speedStart: String, wolSave: String, wolEmpty: String) { + let app = launch(language: language, locale: locale) + let buttons = app.tabBars.firstMatch.buttons + XCTAssertTrue(app.tabBars.firstMatch.waitForExistence(timeout: 10)) + XCTAssertEqual(buttons.count, 4) + for (index, label) in tabs.enumerated() { XCTAssertEqual(buttons.element(boundBy: index).label, label) } + XCTAssertTrue(app.staticTexts[wifiEmpty].waitForExistence(timeout: 10)) + let check = app.buttons[wifiCheck] + XCTAssertTrue(check.waitForExistence(timeout: 10)) + check.tap() + XCTAssertTrue(app.staticTexts[wifiUnavailable].waitForExistence(timeout: 10)) + app.buttons[speed].tap() + XCTAssertTrue(app.buttons[speedStart].waitForExistence(timeout: 10)) + app.navigationBars.buttons.element(boundBy: 0).tap() + buttons[tabs[1]].tap() + XCTAssertTrue(app.buttons[tcp].waitForExistence(timeout: 10)) + app.swipeUp() + XCTAssertTrue(app.staticTexts[devicesEmpty].waitForExistence(timeout: 10)) + buttons[tabs[3]].tap() + XCTAssertTrue(app.buttons[wolSave].waitForExistence(timeout: 10)) + app.swipeUp() + XCTAssertTrue(app.staticTexts[wolEmpty].waitForExistence(timeout: 10)) + } + + private func assertSshEmptyState(language: String, locale: String, addProfile: String, empty: String) { + let app = launch(language: language, locale: locale) + app.tabBars.buttons["SSH"].tap() + XCTAssertTrue(app.buttons[addProfile].waitForExistence(timeout: 10)) + XCTAssertTrue(app.staticTexts[empty].exists) + } + + private func launch(language: String, locale: String, scenario: String? = nil, id: String = UUID().uuidString, reset: Bool = true, captureSshExport: Bool = false) -> XCUIApplication { + let app = XCUIApplication() + app.launchArguments += ["-AppleLanguages", "(\(language))", "-AppleLocale", locale] + if let scenario { + if captureSshExport { app.launchArguments.append("-netkit-ui-capture-ssh-export") } + app.launchEnvironment["NETKIT_UI_SSH_ID"] = id + app.launchEnvironment["NETKIT_UI_SSH_SCENARIO"] = scenario + app.launchEnvironment["NETKIT_UI_SSH_RESET"] = reset ? "1" : "0" + } + app.launch() + return app + } + + private func assertLaunch(language: String, locale: String, overview: String, about: String, versionLabel: String, privacy: String, licenses: String, content: String) throws { + let expectedVersion = try XCTUnwrap(Bundle(for: NetKitUITests.self).infoDictionary?["CFBundleShortVersionString"] as? String) + XCTAssertFalse(expectedVersion.isEmpty) + let app = launch(language: language, locale: locale) + XCTAssertTrue(app.tabBars.buttons[overview].waitForExistence(timeout: 10)) + app.buttons[about].tap() + XCTAssertTrue(app.staticTexts[versionLabel].waitForExistence(timeout: 10)) + let version = app.staticTexts["appVersionValue"] + XCTAssertTrue(version.waitForExistence(timeout: 10)) + XCTAssertEqual(version.label, expectedVersion) + XCTAssertTrue(app.links[privacy].exists || app.buttons[privacy].exists) + app.buttons[licenses].tap() + XCTAssertTrue(app.staticTexts[content].waitForExistence(timeout: 10)) + } +} + + +extension NetKitUITests { + func testEnglishSshOrderAndExport() throws { try assertSshOrderAndExport(language: "en", locale: "en_US", up: "Move profile Alpha up", down: "Move profile Alpha down") } + func testCzechSshOrderAndExport() throws { try assertSshOrderAndExport(language: "cs", locale: "cs_CZ", up: "Posunout profil Alpha nahoru", down: "Posunout profil Alpha dolů") } + func testEnglishSshImportPreview() { assertSshImportPreview(language: "en", locale: "en_US", key: "Key", password: "Password", empty: "Empty") } + func testCzechSshImportPreview() { assertSshImportPreview(language: "cs", locale: "cs_CZ", key: "Klíč", password: "Heslo", empty: "Prázdné") } + func testEnglishSshMissingKeyEditor() { assertSshMissingKeyEditor(language: "en", locale: "en_US", edit: "Edit", title: "Select a key") } + func testCzechSshMissingKeyEditor() { assertSshMissingKeyEditor(language: "cs", locale: "cs_CZ", edit: "Upravit", title: "Vyberte klíč") } + func testEnglishSshInteractiveProfile() { assertSshInteractiveProfile(language: "en", locale: "en_US", password: "Password", key: "Key", message: "The iOS version does not support keyboard-interactive. Edit the profile to use a password or key.") } + func testCzechSshInteractiveProfile() { assertSshInteractiveProfile(language: "cs", locale: "cs_CZ", password: "Heslo", key: "Klíč", message: "iOS verze nepodporuje keyboard-interactive, upravte profil na heslo nebo klíč.") } + func testEnglishSshExportValidation() { assertSshExportValidation(language: "en", locale: "en_US", duplicate: "Profiles have duplicate names.", large: "The export exceeds 256 KiB.") } + func testCzechSshExportValidation() { assertSshExportValidation(language: "cs", locale: "cs_CZ", duplicate: "Profily mají duplicitní názvy.", large: "Export překračuje limit 256 KiB.") } + + func testEnglishSshEditorAndKeyErrors() { + assertSshEditorAndKeyErrors(language: "en", locale: "en_US", password: "Password", key: "Key", invalid: "Check the entered values or file.") + } + func testCzechSshEditorAndKeyErrors() { + assertSshEditorAndKeyErrors(language: "cs", locale: "cs_CZ", password: "Heslo", key: "Klíč", invalid: "Zkontrolujte zadané údaje nebo soubor.") + } + + private func assertSshEditorAndKeyErrors(language: String, locale: String, password: String, key: String, invalid: String) { + let app = sshApp(language: language, locale: locale, scenario: "interactive") + reveal(app.buttons["ssh.connect.alpha"], in: app) + app.buttons["ssh.connect.alpha"].tap() // Leave the unsupported-auth error pending when opening the editor. + XCTAssertTrue(app.staticTexts["ssh.error"].waitForExistence(timeout: 10)) + reveal(app.buttons["ssh.edit.alpha"], in: app) + app.buttons["ssh.edit.alpha"].tap() + XCTAssertTrue(app.buttons["ssh.editor.save"].waitForExistence(timeout: 10)) + XCTAssertFalse(app.staticTexts["ssh.editor.error"].exists) + let form = app.collectionViews["ssh.editor.form"] + let authentication = app.buttons["ssh.editor.authentication"] + reveal(authentication, in: app, scrollView: form) + authentication.tap() + app.buttons[password].tap() + let port = app.textFields["ssh.editor.port"] + reveal(port, in: app, upwards: false, scrollView: form) + port.tap(); port.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 2) + "0") + app.buttons["ssh.editor.keyboard.done"].tap() + reveal(app.buttons["ssh.editor.save"], in: app, scrollView: form) + app.buttons["ssh.editor.save"].tap() + let editorError = app.staticTexts["ssh.editor.error"] + reveal(editorError, in: app, scrollView: form) + XCTAssertEqual(editorError.label, invalid) + reveal(authentication, in: app, upwards: false, scrollView: form) + authentication.tap() + app.buttons[key].tap() + let create = app.buttons["ssh.editor.create.key"] + reveal(create, in: app, scrollView: form) + create.tap() // The prior invalid-input error must not appear as a stale key-creation failure. + let name = app.textFields["ssh.creator.name"] + XCTAssertTrue(name.waitForExistence(timeout: 10)) + XCTAssertFalse(app.staticTexts["ssh.creator.error"].exists) + name.tap(); name.typeText(String(repeating: "x", count: 101)) + app.buttons["ssh.creator.generate"].tap() + let keyError = app.staticTexts["ssh.creator.error"] + XCTAssertTrue(keyError.waitForExistence(timeout: 10)) + XCTAssertEqual(keyError.label, invalid) + app.buttons["ssh.creator.cancel"].tap() + XCTAssertTrue(create.waitForExistence(timeout: 10)) + reveal(create, in: app, scrollView: form) + create.tap() + XCTAssertTrue(name.waitForExistence(timeout: 10)) + XCTAssertFalse(keyError.exists, "Opening key creation must clear the previous failure") + app.buttons["ssh.creator.cancel"].tap() + } + + private func sshApp(language: String, locale: String, scenario: String, id: String = UUID().uuidString, reset: Bool = true, captureSshExport: Bool = false) -> XCUIApplication { + let app = launch(language: language, locale: locale, scenario: scenario, id: id, reset: reset, captureSshExport: captureSshExport) + XCTAssertTrue(app.tabBars.buttons["SSH"].waitForExistence(timeout: 10)) + app.tabBars.buttons["SSH"].tap() + XCTAssertTrue(app.buttons["ssh.export"].waitForExistence(timeout: 10)) + return app + } + + private func reveal(_ element: XCUIElement, in app: XCUIApplication, upwards: Bool = true, scrollView: XCUIElement? = nil, file: StaticString = #filePath, line: UInt = #line) { + for _ in 0..<8 { + if element.exists && element.isHittable { return } + let surface = scrollView ?? app + if upwards { surface.swipeUp() } else { surface.swipeDown() } + } + XCTAssertTrue(element.exists && element.isHittable, "Element not visible: \(element)", file: file, line: line) + } + + private func assertSshOrderAndExport(language: String, locale: String, up: String, down: String) throws { + let id = UUID().uuidString + var app = sshApp(language: language, locale: locale, scenario: "profiles", id: id) + let upAlpha = app.buttons["ssh.move.up.alpha"] + let downAlpha = app.buttons["ssh.move.down.alpha"] + reveal(downAlpha, in: app) + XCTAssertEqual(upAlpha.label, up) + XCTAssertEqual(downAlpha.label, down) + XCTAssertFalse(upAlpha.isEnabled) + XCTAssertTrue(downAlpha.isEnabled) + downAlpha.tap() + XCTAssertTrue(upAlpha.isEnabled) + XCTAssertFalse(downAlpha.isEnabled) + app.terminate() + app = sshApp(language: language, locale: locale, scenario: "profiles", id: id, reset: false, captureSshExport: true) + reveal(app.buttons["ssh.move.up.alpha"], in: app) + XCTAssertTrue(app.buttons["ssh.move.up.alpha"].isEnabled) + XCTAssertFalse(app.buttons["ssh.move.down.alpha"].isEnabled) + reveal(app.buttons["ssh.export"], in: app, upwards: false) + app.buttons["ssh.export"].tap() + let captured = app.staticTexts["ssh.ui.export.capture"] + XCTAssertTrue(captured.waitForExistence(timeout: 10), "Export must capture the actual prepared JSON") + let json = try XCTUnwrap(captured.value as? String) + let bytes = try XCTUnwrap(json.data(using: .utf8)) + XCTAssertLessThanOrEqual(bytes.count, 256 * 1024) + let document = try XCTUnwrap(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + XCTAssertEqual(document["format"] as? String, "netkit-ssh-profiles") + XCTAssertEqual(document["schema"] as? Int, 2) + XCTAssertEqual(Set(document.keys), Set(["format", "schema", "source", "profiles", "skipped"])) + XCTAssertEqual((document["skipped"] as? [Any])?.count, 0) + let profiles = try XCTUnwrap(document["profiles"] as? [[String: Any]]) + XCTAssertEqual(profiles.count, 2) + XCTAssertEqual(profiles.compactMap { $0["alias"] as? String }, ["Beta", "Alpha"], "Export must retain the moved order after restart") + let portableFields = Set(["alias", "host", "port", "username", "authentication", "startupCommand", "keepaliveSeconds"]) + for profile in profiles { + XCTAssertEqual(Set(profile.keys), portableFields, "Only portable profile fields may leave the app") + for field in ["id", "secretRef", "keyRef", "keys", "hostKeys", "rejectedHostKeys"] { XCTAssertNil(profile[field], field) } + XCTAssertEqual(profile["host"] as? String, "192.0.2.1") + XCTAssertEqual(profile["authentication"] as? String, "KEY") + } + XCTAssertTrue(app.buttons["ssh.export"].isHittable) + XCTAssertFalse(app.staticTexts["ssh.export.error"].exists) + } + + private func assertSshImportPreview(language: String, locale: String, key: String, password: String, empty: String) { + let app = sshApp(language: language, locale: locale, scenario: "preview") + app.buttons["ssh.import"].tap() + XCTAssertTrue(app.buttons["ssh.import.apply"].waitForExistence(timeout: 10)) + let expected = ["HOST": "192.0.2.1 → 192.0.2.2", "PORT": "22 → 2222", "USERNAME": "tester → operator", + "AUTHENTICATION": password + " → " + key, "STARTUP_COMMAND": empty + " → show version", "KEEPALIVE_SECONDS": "30 → 60"] + for field in ["HOST", "PORT", "USERNAME", "AUTHENTICATION", "STARTUP_COMMAND", "KEEPALIVE_SECONDS"] { + let row = app.descendants(matching: .any).matching(identifier: "ssh.import.change." + field).firstMatch + reveal(row, in: app) + // LabeledContent exposes its title and value either together or as child text elements. + let values = row.staticTexts.allElementsBoundByIndex.map(\.label) + [row.label] + XCTAssertTrue(values.contains { $0.contains(expected[field]!) }, "Missing before/after for " + field) + } + let startup = app.staticTexts.matching(identifier: "ssh.import.startup.warning").firstMatch + reveal(startup, in: app) + let missing = app.staticTexts.matching(identifier: "ssh.import.key.required").firstMatch + reveal(missing, in: app) + app.buttons["ssh.import.apply"].tap() + let alpha = app.buttons["ssh.connect.alpha"] + reveal(alpha, in: app) + XCTAssertTrue(alpha.label.contains("192.0.2.2")) + XCTAssertFalse(app.buttons["ssh.import.apply"].exists) + app.terminate() + let v1 = sshApp(language: language, locale: locale, scenario: "preview-v1") + v1.buttons["ssh.import"].tap() + XCTAssertTrue(v1.buttons["ssh.import.apply"].waitForExistence(timeout: 10)) + let authentication = v1.descendants(matching: .any).matching(identifier: "ssh.import.authentication.Beta").firstMatch + reveal(authentication, in: v1) + XCTAssertTrue((authentication.staticTexts.allElementsBoundByIndex.map(\.label) + [authentication.label]).contains { $0.contains(password) }) + reveal(v1.buttons["ssh.import.key"], in: v1, upwards: false) + v1.buttons["ssh.import.key"].tap() + v1.buttons["Other key"].tap() + reveal(authentication, in: v1) + XCTAssertTrue((authentication.staticTexts.allElementsBoundByIndex.map(\.label) + [authentication.label]).contains { $0.contains(key) }) + } + + private func assertSshMissingKeyEditor(language: String, locale: String, edit: String, title: String) { + let app = sshApp(language: language, locale: locale, scenario: "profiles") + let connect = app.buttons["ssh.connect.alpha"] + reveal(connect, in: app) + connect.tap() + XCTAssertTrue(app.alerts[title].waitForExistence(timeout: 10)) + app.alerts.buttons[edit].tap() + XCTAssertTrue(app.buttons["ssh.editor.save"].waitForExistence(timeout: 10)) + XCTAssertFalse(app.buttons["ssh.editor.save"].isEnabled) + XCTAssertTrue(app.staticTexts["ssh.editor.key.required"].exists) + let name = app.textFields["ssh.editor.name"] + name.tap(); name.typeText(" draft") + let done = app.buttons["ssh.editor.keyboard.done"] + XCTAssertTrue(done.waitForExistence(timeout: 10)) + done.tap() + let keyboardDismissed = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in app.keyboards.count == 0 }, object: app) + XCTAssertEqual(XCTWaiter.wait(for: [keyboardDismissed], timeout: 10), .completed) + let editorForm = app.collectionViews["ssh.editor.form"] + XCTAssertTrue(editorForm.exists) + let create = app.buttons["ssh.editor.create.key"] + reveal(create, in: app, scrollView: editorForm) + create.tap() + let keyName = app.textFields["ssh.creator.name"] + XCTAssertTrue(keyName.waitForExistence(timeout: 10)) + keyName.tap(); keyName.typeText("Replacement") + app.buttons["ssh.creator.generate"].tap() + XCTAssertTrue(app.buttons["ssh.editor.save"].waitForExistence(timeout: 10)) + reveal(app.buttons["ssh.editor.save"], in: app, scrollView: editorForm) + XCTAssertTrue(app.buttons["ssh.editor.save"].isEnabled) + XCTAssertEqual(app.textFields["ssh.editor.name"].value as? String, "Alpha draft") + XCTAssertFalse(app.staticTexts["ssh.editor.key.required"].exists) + app.buttons["ssh.editor.save"].tap() + XCTAssertTrue(app.buttons["ssh.connect.alpha"].waitForExistence(timeout: 10)) + XCTAssertTrue(app.buttons["ssh.connect.alpha"].label.contains("Alpha draft")) + app.terminate() + let retry = sshApp(language: language, locale: locale, scenario: "reconnect") + let reconnect = retry.buttons["ssh.reconnect"] + reveal(reconnect, in: retry) + reconnect.tap() + let reconnectLabel = language == "cs" ? "Znovu připojit" : "Reconnect" + let confirm = retry.sheets.buttons[reconnectLabel] + XCTAssertTrue(confirm.waitForExistence(timeout: 10)) + confirm.tap() + XCTAssertTrue(retry.alerts[title].waitForExistence(timeout: 10)) + retry.alerts.buttons["OK"].tap() + XCTAssertFalse(retry.alerts[title].exists) + } + + private func assertSshInteractiveProfile(language: String, locale: String, password: String, key: String, message: String) { + for choice in [password, key] { + let app = sshApp(language: language, locale: locale, scenario: "interactive") + let warning = app.staticTexts["ssh.interactive.alpha"] + reveal(warning, in: app) + XCTAssertEqual(warning.label, message) + app.buttons["ssh.connect.alpha"].tap() + let error = app.staticTexts["ssh.error"] + reveal(error, in: app, upwards: false) + XCTAssertEqual(error.label, message) + app.buttons.matching(identifier: "OK").firstMatch.tap() + reveal(app.buttons["ssh.edit.alpha"], in: app) + app.buttons["ssh.edit.alpha"].tap() + XCTAssertTrue(app.buttons["ssh.editor.save"].waitForExistence(timeout: 10)) + XCTAssertFalse(app.buttons["ssh.editor.save"].isEnabled) + app.buttons["ssh.editor.authentication"].tap() + app.buttons[choice].tap() + if choice == key { + let editorForm = app.collectionViews["ssh.editor.form"] + XCTAssertTrue(editorForm.exists) + let picker = app.buttons["ssh.editor.key"] + reveal(picker, in: app, scrollView: editorForm) + picker.tap() + let option = app.buttons.matching(NSPredicate(format: "label == %@", "Other key")).firstMatch + XCTAssertTrue(option.waitForExistence(timeout: 10), "The visible key picker must open its menu") + XCTAssertTrue(option.isHittable) + option.tap() + XCTAssertTrue(picker.label.contains("Other key"), "The chosen key must be reflected in the picker") + } + XCTAssertTrue(app.buttons["ssh.editor.save"].isEnabled) + app.buttons["ssh.editor.save"].tap() + XCTAssertTrue(app.buttons["ssh.connect.alpha"].waitForExistence(timeout: 10)) + XCTAssertFalse(app.staticTexts["ssh.interactive.alpha"].exists) + app.terminate() + } + } + + private func assertSshExportValidation(language: String, locale: String, duplicate: String, large: String) { + for scenario in ["duplicates", "large"] { + let app = sshApp(language: language, locale: locale, scenario: scenario) + app.buttons["ssh.export"].tap() + let error = app.staticTexts["ssh.export.error"] + XCTAssertTrue(error.waitForExistence(timeout: 10)) + XCTAssertTrue(error.label.contains(scenario == "duplicates" ? duplicate : large)) + if scenario == "duplicates" { XCTAssertTrue(error.label.contains("Duplicate")) } + XCTAssertFalse(app.textFields.matching(NSPredicate(format: "value CONTAINS[c] %@", "netkit-ssh-profiles")).firstMatch.exists) + app.buttons.matching(identifier: "OK").firstMatch.tap() + XCTAssertFalse(error.exists) + app.terminate() + } + } +} diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts index ef1a088..d123aca 100644 --- a/shared/build.gradle.kts +++ b/shared/build.gradle.kts @@ -1,3 +1,5 @@ +import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework + plugins { alias(libs.plugins.kotlin.serialization) alias(libs.plugins.kotlin.multiplatform) @@ -7,6 +9,20 @@ kotlin { androidTarget() jvm() jvmToolchain(21) + // Keep the existing Linux/Android build free of Apple targets by default. + if (System.getProperty("os.name").startsWith("Mac", ignoreCase = true) || + providers.gradleProperty("netkit.ios").orNull == "true" + ) { + val xcframework = XCFramework("NetKitShared") + listOf(iosArm64(), iosSimulatorArm64()).forEach { target -> + target.binaries.framework { + baseName = "NetKitShared" + isStatic = true + binaryOption("bundleId", "cz.netkit.shared") + xcframework.add(this) + } + } + } sourceSets { commonMain.dependencies { implementation(libs.coroutines.core) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt index 39f01df..1c53561 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt @@ -20,7 +20,19 @@ fun validLanHost(host: String): Boolean { return safePtrName(host) != null } -private val unsafeLanCodePoint = Regex("[\\p{Cc}\\p{Cf}]") +private fun unsafeLanCodePoint(codePoint: Int): Boolean { + if (codePoint <= 0xFFFF) { + val category = codePoint.toChar().category + return category == CharCategory.CONTROL || category == CharCategory.FORMAT + } + // All supplementary Cf ranges from Unicode 17.0.0; Cc is confined to BMP. + // Native Regex Unicode properties do not reliably classify surrogate pairs. + // Verified 2026-10-31: https://www.unicode.org/Public/17.0.0/ucd/extracted/DerivedGeneralCategory.txt + return codePoint == 0x110BD || codePoint == 0x110CD || + codePoint in 0x13430..0x1343F || codePoint in 0x1BCA0..0x1BCA3 || + codePoint in 0x1D173..0x1D17A || codePoint == 0xE0001 || + codePoint in 0xE0020..0xE007F +} /** * Sanitize complete Unicode code points. The limit counts output UTF-16 units; @@ -35,11 +47,13 @@ fun sanitizeLanText(value: String, maximum: Int = 256): String { val first = value[offset] val pair = first in '\uD800'..'\uDBFF' && value.getOrNull(offset + 1)?.let { it in '\uDC00'..'\uDFFF' } == true val width = if (pair) 2 else 1 - val codePoint = value.substring(offset, offset + width) + val codePoint = if (pair) { + 0x10000 + ((first.code - 0xD800) shl 10) + (value[offset + 1].code - 0xDC00) + } else first.code val replacement = when { !pair && first in '\uD800'..'\uDFFF' -> "\uFFFD" - unsafeLanCodePoint.matches(codePoint) -> " " - else -> codePoint + unsafeLanCodePoint(codePoint) -> " " + else -> value.substring(offset, offset + width) } if (length + replacement.length > maximum) break append(replacement) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt index 93ad859..eaff35d 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt @@ -52,7 +52,7 @@ data class SshData(val schema: Int = 1, val profiles: List = emptyLi } && rejectedHostKeys.map { it.endpoint }.distinct().size == rejectedHostKeys.size } -/** Export connection profiles only; local credential references and trust/key metadata stay on device. */ +/** Legacy export sanitizer retained for compatibility tests. Application files use encodeSshProfileExport (v2). */ fun exportSshProfiles(data: SshData): SshData = SshData( profiles = data.profiles.map { it.copy(secretRef = null, keyRef = null) }, ) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt new file mode 100644 index 0000000..8cd2f91 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt @@ -0,0 +1,51 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.json.* + +sealed interface SshProfileExportError { + data class DuplicateNames(val names: List) : SshProfileExportError + data object TooLarge : SshProfileExportError +} +class SshProfileExportException(val reason: SshProfileExportError) : IllegalArgumentException() + +/** Explicit wire allowlist: local identities, credential references and server trust never leave here. */ +fun encodeSshProfileExport(data: SshData): ByteArray { + require(data.valid()) + val duplicates = data.profiles.groupingBy { it.name }.eachCount().filterValues { it > 1 }.keys.toList() + if (duplicates.isNotEmpty()) throw SshProfileExportException(SshProfileExportError.DuplicateNames(duplicates)) + val document = buildJsonObject { + put("format", "netkit-ssh-profiles") + put("schema", 2) + put("source", "netkit-android") + putJsonArray("profiles") { + data.profiles.forEach { profile -> + addJsonObject { + put("alias", profile.name) + put("host", profile.host) + put("port", profile.port) + put("username", profile.username) + put("authentication", profile.authentication.name) + put("startupCommand", profile.startupCommand) + put("keepaliveSeconds", profile.keepaliveSeconds) + } + } + } + putJsonArray("skipped") { } + }.toString().encodeToByteArray() + if (document.size > SSH_PROFILE_IMPORT_LIMIT) throw SshProfileExportException(SshProfileExportError.TooLarge) + // Never report a successful export of a file the importer cannot accept. + decodeSshProfileImport(document) + return document +} + +/** List order is persisted directly. Invalid moves leave the entire data object unchanged. */ +fun moveSshProfile(data: SshData, id: String, delta: Int): SshData { + if (delta != -1 && delta != 1) return data + val index = data.profiles.indexOfFirst { it.id == id } + val target = index + delta + if (index < 0 || target !in data.profiles.indices) return data + return data.copy(profiles = data.profiles.toMutableList().apply { add(target, removeAt(index)) }) +} + +fun SshProfile.needsKeySelection(data: SshData): Boolean = + authentication == SshAuthentication.KEY && data.keys.none { it.id == keyRef } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt index edb7cf8..c38b8d2 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt @@ -5,6 +5,7 @@ import cz.netkit.shared.json.jsonNestingDepth import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.intOrNull @@ -21,7 +22,9 @@ class SshProfileImportException(val reason: SshProfileImportFailure) : IllegalAr enum class SshImportSkipReason { PROXY_JUMP, PROXY_COMMAND, MATCH, WILDCARD, MISSING_HOST, UNSUPPORTED_OPTION } data class SshImportSkipped(val alias: String, val reason: SshImportSkipReason) -data class SshImportProfile(val alias: String, val host: String, val port: Int, val username: String, val group: String? = null) +data class SshImportProfile(val alias: String, val host: String, val port: Int, val username: String, val group: String? = null, + // null means v1: preserve local settings; v2/legacy always carry all three settings. + val authentication: SshAuthentication? = null, val startupCommand: String = "", val keepaliveSeconds: Int = 30) data class SshProfileImport(val profiles: List, val skipped: List, val source: String? = null) /** Group/source/skipped are preview metadata only, never persisted in SshData. */ @@ -42,7 +45,8 @@ class SshImportPlan internal constructor( private fun fail(reason: SshProfileImportFailure): Nothing = throw SshProfileImportException(reason) private fun validAlias(alias: String) = alias.isNotBlank() && alias.length <= 100 && alias.none { it.code < 32 || it.code in 127..159 } -private fun SshImportProfile.profile(id: String) = SshProfile(id, alias, host, port, username) +private fun SshImportProfile.profile(id: String) = SshProfile(id, alias, host, port, username, authentication ?: SshAuthentication.PASSWORD, + startupCommand = startupCommand, keepaliveSeconds = keepaliveSeconds) private fun validateIncoming(incoming: SshProfileImport) { if (incoming.profiles.size > MAX_IMPORT_ROWS || incoming.skipped.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) @@ -71,18 +75,24 @@ fun decodeSshProfileImport(bytes: ByteArray): SshProfileImport { if (jsonNestingDepth(text) > JSON_MAX_DEPTH) fail(SshProfileImportFailure.FORMAT) try { val root = Json.parseToJsonElement(text) as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) + if (!root.containsKey("format")) return decodeLegacyProfiles(root).also(::validateIncoming) root.allowOnly(setOf("format", "schema", "source", "profiles", "skipped")) if (root.string("format") != "netkit-ssh-profiles") fail(SshProfileImportFailure.FORMAT) - if (root.integer("schema", SshProfileImportFailure.SCHEMA) != 1) fail(SshProfileImportFailure.SCHEMA) + val schema = root.integer("schema", SshProfileImportFailure.SCHEMA) + if (schema !in 1..2) fail(SshProfileImportFailure.SCHEMA) val profiles = root.rows("profiles") val skipped = root.rows("skipped") if (profiles.size > MAX_IMPORT_ROWS || skipped.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) return SshProfileImport( profiles.map { element -> val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) - row.allowOnly(setOf("alias", "group", "host", "port", "username")) + row.allowOnly(setOf("alias", "group", "host", "port", "username") + + if (schema == 2) setOf("authentication", "startupCommand", "keepaliveSeconds") else emptySet()) SshImportProfile(row.string("alias"), row.string("host"), - row.integer("port", SshProfileImportFailure.INVALID_PROFILE), row.string("username"), row.optionalString("group")) + row.integer("port", SshProfileImportFailure.INVALID_PROFILE), row.string("username"), row.optionalString("group"), + authentication = if (schema == 2) row.authentication() else null, + startupCommand = if (schema == 2) row.string("startupCommand") else "", + keepaliveSeconds = if (schema == 2) row.integer("keepaliveSeconds", SshProfileImportFailure.INVALID_PROFILE) else 30) }, skipped.map { element -> val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) @@ -97,7 +107,37 @@ fun decodeSshProfileImport(bytes: ByteArray): SshProfileImport { catch (_: IllegalArgumentException) { fail(SshProfileImportFailure.FORMAT) } } -/** Exact alias match. Local settings survive; a changed endpoint detaches its saved password. */ +private fun JsonObject.authentication(): SshAuthentication = + (get("authentication") as? JsonPrimitive)?.takeIf { it.isString }?.content?.let { value -> + SshAuthentication.entries.find { it.name == value } + } ?: fail(SshProfileImportFailure.INVALID_PROFILE) + +/** Only the credential-free export of the old serializer, never a device backup. */ +private fun decodeLegacyProfiles(root: JsonObject): SshProfileImport { + root.allowOnly(setOf("schema", "profiles", "hostKeys", "keys", "rejectedHostKeys")) + if (!root.containsKey("schema")) fail(SshProfileImportFailure.FORMAT) + if (root.integer("schema", SshProfileImportFailure.SCHEMA) != 1) fail(SshProfileImportFailure.SCHEMA) + for (field in listOf("hostKeys", "keys", "rejectedHostKeys")) { + if (root.rows(field).isNotEmpty()) fail(SshProfileImportFailure.FORMAT) + } + val rows = root.rows("profiles") + if (rows.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) + return SshProfileImport(rows.map { element -> + val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) + row.allowOnly(setOf("id", "name", "host", "port", "username", "authentication", + "secretRef", "keyRef", "startupCommand", "keepaliveSeconds")) + for (field in listOf("secretRef", "keyRef")) { + if (row.containsKey(field) && row[field] != JsonNull) fail(SshProfileImportFailure.FORMAT) + } + row.string("id") // Ignore the old identity; the planner generates a new local one. + SshImportProfile(row.string("name"), row.string("host"), + row.integer("port", SshProfileImportFailure.INVALID_PROFILE), row.string("username"), + authentication = row.authentication(), startupCommand = row.string("startupCommand"), + keepaliveSeconds = row.integer("keepaliveSeconds", SshProfileImportFailure.INVALID_PROFILE)) + }, emptyList()) +} + +/** Exact alias match. v1 preserves local settings; v2/legacy replace portable settings; a changed endpoint detaches its saved password. */ fun planSshProfileImport(current: SshData, incoming: SshProfileImport, keyRef: String?, generateId: () -> String): SshImportPlan { if (!current.valid()) fail(SshProfileImportFailure.INVALID_DATA) validateIncoming(incoming) @@ -116,11 +156,18 @@ fun planSshProfileImport(current: SshData, incoming: SshProfileImport, keyRef: S if (!validReference(id)) fail(SshProfileImportFailure.INVALID_REFERENCE) if (!ids.add(id)) fail(SshProfileImportFailure.DUPLICATE_ID) added += SshImportEntry(row, null, row.profile(id).copy( - authentication = if (keyRef == null) SshAuthentication.PASSWORD else SshAuthentication.KEY, keyRef = keyRef)) + authentication = row.authentication ?: if (keyRef == null) SshAuthentication.PASSWORD else SshAuthentication.KEY, + keyRef = keyRef.takeIf { row.authentication == null || row.authentication == SshAuthentication.KEY })) } else { val targetChanged = before.host != row.host || before.port != row.port || before.username != row.username + val authentication = row.authentication ?: before.authentication + val authenticationChanged = authentication != before.authentication val after = before.copy(host = row.host, port = row.port, username = row.username, - secretRef = if (targetChanged) null else before.secretRef) + authentication = authentication, + startupCommand = if (row.authentication == null) before.startupCommand else row.startupCommand, + keepaliveSeconds = if (row.authentication == null) before.keepaliveSeconds else row.keepaliveSeconds, + secretRef = if (targetChanged || authenticationChanged && authentication != SshAuthentication.PASSWORD) null else before.secretRef, + keyRef = if (authenticationChanged && authentication != SshAuthentication.KEY) null else before.keyRef) val entry = SshImportEntry(row, before, after) if (before == after) unchanged += entry else updated += entry } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt index 7f0ebb6..545c49c 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt @@ -2,11 +2,30 @@ package cz.netkit.shared.update /** * Privacy policy shown from About: the web page `/privacy` when the build has a web - * (`/netkit/privacy`, no trailing slash as on the website), otherwise the Markdown source in the - * repository, Czech for a Czech locale and English for any other. + * (`/netkit/privacy`, no trailing slash as on the website; `/en/netkit/privacy` for a non-Czech + * locale, see [localizedWebUrl]), otherwise the Markdown source in the repository, Czech for a Czech + * locale and English for any other. */ fun privacyPolicyUrl(webBaseUrl: String?, sourceUrl: String, language: String): String { - webBaseUrl?.let { return it.trimEnd('/') + "/privacy" } + webBaseUrl?.let { + val base = it.trimEnd('/') + return localizedWebUrl("$base/privacy", base, language) + } val suffix = if (language.lowercase() == "cs") "cs" else "en" return "${sourceUrl.trimEnd('/')}/blob/main/docs/public/privacy-$suffix.md" } + +/** + * English counterpart of a page on the author's web for a non-Czech UI: `/netkit…` becomes + * `/en/netkit…` (the website keeps both paths stable; the Czech page stays binding). Only [url] + * equal to [webBaseUrl] or below it changes; anything else (GitHub, APK) and every URL for a Czech + * locale is returned unchanged. `latest.json` keeps the Czech `pageUrl`; this maps it on display. + */ +fun localizedWebUrl(url: String, webBaseUrl: String?, language: String): String { + if (webBaseUrl == null || language.lowercase() == "cs") return url + val base = webBaseUrl.trimEnd('/') + if (url != base && !url.startsWith("$base/")) return url + val hostStart = base.indexOf("://").takeIf { it >= 0 }?.plus(3) ?: return url + val pathStart = base.indexOf('/', hostStart).takeIf { it >= 0 } ?: return url + return base.substring(0, pathStart) + "/en" + url.substring(pathStart) +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt new file mode 100644 index 0000000..f5d5ccd --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt @@ -0,0 +1,4 @@ +package cz.netkit.shared.ssh + +// Generated by SshLegacyExportFixtureTest using the serializer/helper identical to main f88f920. +internal const val LEGACY_SSH_EXPORT = """{"schema":1,"profiles":[{"id":"old-0","name":"fixture-0","host":"192.0.2.1","port":2222,"username":"tester","authentication":"PASSWORD","secretRef":null,"keyRef":null,"startupCommand":"show version","keepaliveSeconds":60},{"id":"old-1","name":"fixture-1","host":"192.0.2.2","port":2223,"username":"tester","authentication":"KEY","secretRef":null,"keyRef":null,"startupCommand":"show version","keepaliveSeconds":61},{"id":"old-2","name":"fixture-2","host":"192.0.2.3","port":2224,"username":"tester","authentication":"INTERACTIVE","secretRef":null,"keyRef":null,"startupCommand":"show version","keepaliveSeconds":62}],"hostKeys":[],"keys":[],"rejectedHostKeys":[]}""" diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt index 6e63b0c..00fc5b3 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt @@ -23,7 +23,7 @@ class SshPolicyTest { assertFalse(data.copy(profiles = listOf(profile, profile)).valid()) assertFalse(data.copy(schema = 2).valid()) } - @Test fun productionExportRemovesCredentialReferencesAndAllTrustAndKeyMetadata() { + @Test fun legacyExportRemovesCredentialReferencesAndAllTrustAndKeyMetadata() { val profile = SshProfile("profile-1", "Fixture", "host.example", username = "user", secretRef = "local-ref-1", keyRef = "local-key-1", startupCommand = "status") val trusted = TrustedHostKey(profile.endpoint, "ssh-ed25519", "public-data", "SHA256:display") @@ -32,7 +32,7 @@ class SshPolicyTest { rejectedHostKeys = listOf(trusted.copy(publicKey = "rejected-data"))) val exported = exportSshProfiles(source) assertEquals(SshData(profiles = listOf(profile.copy(secretRef = null, keyRef = null))), exported) - // Check the serialized structure used by the production serializer, not a substring in a fixture. + // Check the legacy serialized structure; v2 is covered by SshProfileExchangeTest. val json = Json { encodeDefaults = true } val document = json.parseToJsonElement(json.encodeToString(exported)).jsonObject val connection = document.getValue("profiles").jsonArray.single().jsonObject diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt new file mode 100644 index 0000000..94951c5 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt @@ -0,0 +1,135 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.json.* +import kotlin.test.* + +class SshProfileExchangeTest { + private val profiles = SshAuthentication.entries.mapIndexed { index, auth -> + SshProfile("old-$index", "fixture-$index", "192.0.2.${index + 1}", 2222 + index, "tester", + auth, "secret-$index", "key-$index", "show version", 60 + index) + } + private val source = SshData(profiles = profiles, + keys = listOf(SshKeyInfo("key-1", "fixture", "public")), + hostKeys = listOf(TrustedHostKey("[example.test]:22", "ssh-ed25519", "public", "SHA256:fixture"))) + private fun restore(bytes: ByteArray, current: SshData = SshData(), key: String? = null): SshData { + var id = 0 + return applySshImportPlan(current, planSshProfileImport(current, decodeSshProfileImport(bytes), key) { "new-${id++}" }) + } + private fun failWith(reason: SshProfileImportFailure, text: String) { + assertEquals(reason, assertFailsWith { decodeSshProfileImport(text.encodeToByteArray()) }.reason) + } + private fun wire() = encodeSshProfileExport(source).decodeToString() + + @Test fun roundtripPortableSettingsAndSelectedKeyOnlyForKeyAuthentication() { + val bytes = encodeSshProfileExport(source) + println("SSH_V2_SYNTHETIC_EXPORT=" + bytes.decodeToString()) + val root = Json.parseToJsonElement(bytes.decodeToString()).jsonObject + assertEquals(setOf("format", "schema", "source", "profiles", "skipped"), root.keys) + root.getValue("profiles").jsonArray.forEach { row -> + assertEquals(setOf("alias", "host", "port", "username", "authentication", "startupCommand", "keepaliveSeconds"), row.jsonObject.keys) + } + for (key in listOf(null, "selected")) { + assertEquals(profiles.mapIndexed { index, p -> + p.copy(id = "new-$index", secretRef = null, keyRef = key.takeIf { p.authentication == SshAuthentication.KEY }) + }, restore(bytes, key = key).profiles) + } + assertEquals("secret-0", source.profiles.first().secretRef) + assertTrue(restore(bytes).profiles[1].needsKeySelection(SshData())) + } + + @Test fun legacySerializerFixturePreservesSettingsAndDiscardsIds() { + assertEquals(profiles.mapIndexed { i, p -> p.copy(id = "new-$i", secretRef = null, keyRef = null) }, + restore(LEGACY_SSH_EXPORT.encodeToByteArray()).profiles) + for (field in listOf("hostKeys", "keys", "rejectedHostKeys")) { + failWith(SshProfileImportFailure.FORMAT, LEGACY_SSH_EXPORT.replace("\"$field\":[]", "\"$field\":[{}]")) + } + for (field in listOf("secretRef", "keyRef")) { + for (value in listOf("\"local-ref\"", "0", "{}")) + failWith(SshProfileImportFailure.FORMAT, LEGACY_SSH_EXPORT.replace("\"$field\":null", "\"$field\":$value")) + } + } + + @Test fun updatesReplaceAllPortableSettingsAndPreservePosition() { + val changed = profiles[1].copy(host = "198.51.100.1", port = 2229, username = "other", + authentication = SshAuthentication.INTERACTIVE, startupCommand = "show status", keepaliveSeconds = 0) + val incoming = encodeSshProfileExport(SshData(profiles = listOf(changed, profiles[0].copy(id = "new", name = "new")))) + val result = restore(incoming, source, "selected") + assertEquals(listOf("old-0", "old-1", "old-2", "new-0"), result.profiles.map { it.id }) + assertEquals(changed.copy(secretRef = null, keyRef = null), result.profiles[1]) + assertEquals(source.keys, result.keys) + assertEquals(source.hostKeys, result.hostKeys) + // Settings-only updates do not detach a password; changing endpoint still does (v1 regressions too). + val sameTarget = profiles[0].copy(startupCommand = "show status", keepaliveSeconds = 0) + assertEquals(sameTarget, restore(encodeSshProfileExport(SshData(profiles = listOf(sameTarget))), source).profiles[0]) + } + + @Test fun everyFormatEnforcesSchemaFieldsLimitsAndDepth() { + val v1 = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[],"skipped":[]}""" + for (text in listOf(v1, wire(), LEGACY_SSH_EXPORT)) { + val root = Json.parseToJsonElement(text).jsonObject + failWith(SshProfileImportFailure.SCHEMA, JsonObject(root + ("schema" to JsonPrimitive(99))).toString()) + failWith(SshProfileImportFailure.UNKNOWN_FIELD, JsonObject(root + ("extra" to JsonPrimitive(true))).toString()) + failWith(SshProfileImportFailure.FORMAT, text.dropLast(1) + ",\"extra\":" + "[".repeat(100) + "0" + "]".repeat(100) + "}") + failWith(SshProfileImportFailure.SIZE, text.padEnd(SSH_PROFILE_IMPORT_LIMIT + 1, ' ')) + } + for (text in listOf(wire(), LEGACY_SSH_EXPORT)) { + val root = Json.parseToJsonElement(text).jsonObject + val row = root.getValue("profiles").jsonArray.first().jsonObject + fun altered(field: String, value: JsonElement) = JsonObject(root + + ("profiles" to JsonArray(listOf(JsonObject(row + (field to value)))))).toString() + for (field in listOf("password", "privateKey", "extra")) + failWith(SshProfileImportFailure.UNKNOWN_FIELD, altered(field, JsonPrimitive("forbidden"))) + for (value in listOf(JsonPrimitive("OTHER"), JsonPrimitive(2), JsonNull)) + failWith(SshProfileImportFailure.INVALID_PROFILE, altered("authentication", value)) + for (value in listOf("x".repeat(4097), "show\nstatus", "show\rstatus")) + failWith(SshProfileImportFailure.INVALID_PROFILE, altered("startupCommand", JsonPrimitive(value))) + for (value in listOf(-1, 301)) failWith(SshProfileImportFailure.INVALID_PROFILE, altered("keepaliveSeconds", JsonPrimitive(value))) + failWith(SshProfileImportFailure.LIMIT, JsonObject(root + ("profiles" to JsonArray(List(201) { row }))).toString()) + } + } + + @Test fun movesPreserveEverythingExceptOrderAndExportFollowsIt() { + for ((id, delta) in listOf("old-0" to -1, "old-2" to 1, "absent" to 1, "old-1" to 0, "old-1" to 2, "old-1" to Int.MIN_VALUE)) + assertSame(source, moveSshProfile(source, id, delta)) + } + + @Test fun validMovesAndMissingKeySelection() { + assertEquals(SshData(), moveSshProfile(SshData(), "x", 1)) + val moved = moveSshProfile(source, "old-1", -1) + assertEquals(source.copy(profiles = listOf(profiles[1], profiles[0], profiles[2])), moved) + assertEquals(source, moveSshProfile(moved, "old-1", 1)) + assertEquals(moved.profiles.map { it.name }, restore(encodeSshProfileExport(moved)).profiles.map { it.name }) + assertFalse(profiles[0].needsKeySelection(SshData())) + assertFalse(profiles[1].needsKeySelection(source)) + assertTrue(profiles[1].copy(keyRef = null).needsKeySelection(source)) + assertTrue(profiles[1].copy(keyRef = "absent").needsKeySelection(source)) + } + @Test fun exportRejectsDuplicateNamesAndUtf8SizeWithSpecificReasons() { + val duplicate = source.copy(profiles = listOf(profiles[0], profiles[1].copy(name = profiles[0].name))) + assertTrue(duplicate.valid()) // Saving duplicate names remains allowed. + assertEquals(SshProfileExportError.DuplicateNames(listOf("fixture-0")), + assertFailsWith { encodeSshProfileExport(duplicate) }.reason) + val large = SshData(profiles = (1..70).map { profiles[0].copy(id = "p$it", name = "p$it", startupCommand = "ž".repeat(4096)) }) + assertTrue(large.valid()) + assertEquals(SshProfileExportError.TooLarge, + assertFailsWith { encodeSshProfileExport(large) }.reason) + } + + @Test fun authenticationTransitionsDetachOnlyReferencesUnusedByNewType() { + for (old in SshAuthentication.entries) for (new in SshAuthentication.entries) { + val before = profiles[0].copy(authentication = old) + val data = SshData(profiles = listOf(before)) + val incoming = decodeSshProfileImport(encodeSshProfileExport(SshData(profiles = listOf(before.copy(authentication = new))))) + val plan = planSshProfileImport(data, incoming, null) { error("Existing") } + val after = applySshImportPlan(data, plan).profiles.single() + val expectedSecretRef = before.secretRef.takeUnless { old != new && new != SshAuthentication.PASSWORD } + val expectedKeyRef = before.keyRef.takeUnless { old != new && new != SshAuthentication.KEY } + assertEquals(before.copy(authentication = new, secretRef = expectedSecretRef, keyRef = expectedKeyRef), after) + assertEquals(if (expectedSecretRef == null) listOf(before.secretRef) else emptyList(), plan.detachedSecretRefs) + } + val keyProfile = profiles[1] + val moved = restore(encodeSshProfileExport(SshData(profiles = listOf(keyProfile.copy(host = "198.51.100.8")))), source) + assertEquals(keyProfile.keyRef, moved.profiles[1].keyRef) // Endpoint alone never detaches the key. + } + +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt index 62b1bfa..c753dbe 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt @@ -35,7 +35,7 @@ class SshProfileImportTest { document().replace("\"username\":\"root\"", "\"username\":42"), document().replace("\"profiles\":[${row()}]", "\"profiles\":{}"))) { failure(SshProfileImportFailure.FORMAT) { decode(text) } } - for (schema in listOf("2", "\"1\"", "null", "{}")) { + for (schema in listOf("3", "\"1\"", "null", "{}")) { failure(SshProfileImportFailure.SCHEMA) { decode(document().replace("\"schema\":1", "\"schema\":$schema")) } } val exact = document().padEnd(SSH_PROFILE_IMPORT_LIMIT, ' ') diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt index 76ba34a..298566f 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt @@ -8,7 +8,26 @@ class ProjectLinksTest { @Test fun webPageWhenConfigured() { assertEquals("https://www.example.com/netkit/privacy", privacyPolicyUrl("https://www.example.com/netkit", source, "cs")) - assertEquals("https://www.example.com/netkit/privacy", privacyPolicyUrl("https://www.example.com/netkit/", source, "en")) + assertEquals("https://www.example.com/en/netkit/privacy", privacyPolicyUrl("https://www.example.com/netkit/", source, "en")) + assertEquals("https://www.example.com/en/netkit/privacy", privacyPolicyUrl("https://www.example.com/netkit", source, "sk")) + assertEquals("https://www.example.com/netkit/privacy", privacyPolicyUrl("https://www.example.com/netkit", source, "CS")) + } + + @Test fun webPagesGetEnglishPathOutsideCzech() { + val web = "https://www.example.com/netkit" + assertEquals("https://www.example.com/en/netkit", localizedWebUrl(web, web, "en")) + assertEquals("https://www.example.com/en/netkit/privacy", localizedWebUrl("$web/privacy", "$web/", "de")) + assertEquals(web, localizedWebUrl(web, web, "cs")) + assertEquals(web, localizedWebUrl(web, null, "en")) + } + + @Test fun otherUrlsStayUnchanged() { + val web = "https://www.example.com/netkit" + val apk = "$source/releases/download/v1.0.0/netkit-1.0.0.apk" + assertEquals(apk, localizedWebUrl(apk, web, "en")) + assertEquals("https://www.example.com/netkitx", localizedWebUrl("https://www.example.com/netkitx", web, "en")) + assertEquals("https://www.example.com/other", localizedWebUrl("https://www.example.com/other", web, "en")) + assertEquals("https://www.example.com", localizedWebUrl("https://www.example.com", "https://www.example.com", "en")) } @Test fun repositoryMarkdownByLanguageOtherwise() { diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt new file mode 100644 index 0000000..5d7c735 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt @@ -0,0 +1,12 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.update.privacyPolicyUrl + +/** + * Fixed project links for About; the caller supplies the current language code. + * The Czech base is passed on purpose: [privacyPolicyUrl] maps it to `/en/…` for other languages. + */ +class IosAboutDomain { + fun privacyUrl(language: String): String = + privacyPolicyUrl("https://www.daniel.losak.cz/netkit", "https://github.com/Losminek/netkit", language) +} diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt new file mode 100644 index 0000000..942e478 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt @@ -0,0 +1,46 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.lan.* + +/** Small Objective-C export surface; all wire parsing and validation stay in commonMain. */ +class IosNetworkDomain { + fun ports(input: String): List? = parsePorts(input, maximum = 4096) + + fun confirmationReasons(address: String, ownCidr: String?, portCount: Int): List { + val range = Ipv4Subnet.parse("$address/32") ?: return listOf("INVALID_TARGET") + if (portCount !in 0..4096) return listOf("INVALID_PORT_COUNT") + return targetConfirmationReasons(range, ownCidr?.let(Ipv4Subnet::parse), portCount).map { it.name } + } + + fun dnsQuery(host: String, type: Int, id: Int): ByteArray? { + if (type !in listOf(DNS_TYPE_A, DNS_TYPE_PTR, DNS_TYPE_TXT, DNS_TYPE_SRV) || id !in 0..65535) return null + val name = dnsName(host) ?: return null + // encodeDnsQuery is also used by mDNS; unicast DNS requests recursion explicitly. + return encodeDnsQuery(id, listOf(DnsQuestion(name, type))).also { it[2] = 0x01 } + } + + /** Null means a malformed, mismatched, truncated or unsuccessful response, never an empty success. */ + fun dnsResponse(packet: ByteArray, id: Int, host: String, type: Int): List? { + if (packet.size > 65_535 || id !in 0..65535) return null + val expected = dnsName(host) ?: return null + val message = parseDnsMessage(packet) ?: return null + if (!message.isResponse || message.opcode != 0 || message.rcode != 0 || message.flags and 0x0200 != 0 || message.id != id) return null + val question = message.questions.singleOrNull() ?: return null + if (!question.name.matches(expected.labels) || question.type != type || question.dnsClass != DNS_CLASS_IN) return null + return message.records.filter { it.name.matches(expected.labels) && it.type == type && it.dnsClass == DNS_CLASS_IN }.mapNotNull { record -> + when (val data = record.data) { + is DnsRecordData.A -> data.address + is DnsRecordData.Ptr -> safePtrName(data.target.text) + is DnsRecordData.Txt -> data.entries.joinToString(" ") { sanitizeLanText(it) } + is DnsRecordData.Srv -> "${data.priority} ${data.weight} ${data.port} ${sanitizeLanText(data.target.text)}" + else -> null + } + } + } + + fun icmpReplyMatches(request: ByteArray, reply: ByteArray): Boolean = + matchesIcmpEchoReply(request, reply, reply.size) + + /** NWBrowser supplies a DNS-SD instance label; reuse the shared sanitization and name model. */ + fun mdnsName(raw: String): LanDeviceName? = lanDeviceName(LanNameSource.MDNS, raw) +} diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt new file mode 100644 index 0000000..e067402 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt @@ -0,0 +1,47 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.ssh.SecretStore +import cz.netkit.shared.ssh.SshFailure +import cz.netkit.shared.ssh.validReference + +class IosSecretReadResult(val bytes: ByteArray?, val failure: SshFailure?) + +/** Swift Keychain implementation catches OSStatus/NSError and returns categorized failures only. */ +interface IosSecretBackend { + fun store(id: String, bytes: ByteArray): SshFailure? + fun read(id: String): IosSecretReadResult + fun remove(id: String): SshFailure? +} + +/** The synchronous Swift consumer and shared suspend SecretStore use the same checked backend. */ +class IosSecretStoreAdapter(private val backend: IosSecretBackend) { + fun putSecret(id: String, secret: ByteArray): SshFailure? { + if (!validReference(id) || secret.size > 256 * 1024) return SshFailure.SECRET_UNAVAILABLE + return backend.store(id, secret) + } + fun getSecret(id: String): IosSecretReadResult { + if (!validReference(id)) return IosSecretReadResult(null, SshFailure.SECRET_UNAVAILABLE) + val result = backend.read(id) + if (result.failure != null) return IosSecretReadResult(null, result.failure) + if ((result.bytes?.size ?: 0) > 256 * 1024) return IosSecretReadResult(null, SshFailure.SECRET_UNAVAILABLE) + return result + } + fun deleteSecret(id: String): SshFailure? = if (!validReference(id)) SshFailure.SECRET_UNAVAILABLE else backend.remove(id) + + internal val sharedStore: SecretStore = object : SecretStore { + override suspend fun put(id: String, secret: ByteArray) { + putSecret(id, secret)?.let { throw IosSecretStoreException(it) } + } + override suspend fun get(id: String): ByteArray? { + val result = getSecret(id) + result.failure?.let { throw IosSecretStoreException(it) } + return result.bytes + } + override suspend fun delete(id: String) { + deleteSecret(id)?.let { throw IosSecretStoreException(it) } + } + } +} + +/** Remains inside Kotlin suspend callers; Swift uses explicit result-returning methods above. */ +internal class IosSecretStoreException(val failure: SshFailure) : Exception(failure.name) diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt new file mode 100644 index 0000000..6f10c60 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt @@ -0,0 +1,18 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.speed.* + +/** URLSession owns transport; protocol policy, parsers and measurement math remain shared. */ +class IosSpeedDomain { + fun libreServer(input: String): LibreSpeedServer? = (checkLibreSpeedUrl(input) as? LibreSpeedUrlCheck.Valid)?.server + fun garbageUrl(base: String, nonce: Long): String = LibreSpeedProtocol.garbageUrl(base, nonce) + fun emptyUrl(base: String, nonce: Long): String = LibreSpeedProtocol.emptyUrl(base, nonce) + fun ndtLocateUrl(): String = Ndt7Protocol.LOCATE_URL + fun ndtSubprotocol(): String = Ndt7Protocol.SUBPROTOCOL + fun createMessageSizer(): Ndt7MessageSizer = Ndt7MessageSizer() + fun ndtTargets(text: String): List = parseNdt7Locate(text) + fun ndtView(text: String, download: Boolean): Ndt7ServerView? = parseNdt7Measurement(text)?.let { ndt7ServerView(it, download) } + fun createTrace(): ThroughputTrace = ThroughputTrace() + fun summarize(trace: ThroughputTrace): ThroughputSummary? = summarizeThroughput(trace.samples) + fun latency(samples: List): LatencyStats = latencyStats(samples) +} diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt new file mode 100644 index 0000000..9146592 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt @@ -0,0 +1,172 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.json.JSON_MAX_DEPTH +import cz.netkit.shared.json.jsonNestingDepth +import cz.netkit.shared.ssh.* +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.intOrNull + +enum class IosSshDataFailure { SIZE, UTF8, FORMAT, SCHEMA, INVALID_DATA, CONFLICT } +data class IosSshDataResult(val data: SshData?, val failure: IosSshDataFailure?) +data class IosSshImportResult(val imported: SshProfileImport?, val failure: SshProfileImportFailure?) +data class IosSshPlanResult(val plan: SshImportPlan?, val failure: SshProfileImportFailure?) +data class IosSshImportApplyResult(val data: SshData?, val failure: SshProfileImportFailure?) +data class IosSshEndpointChange(val profileId: String, val before: String, val after: String) +enum class IosSshExportFailure { DUPLICATE_NAMES, TOO_LARGE, INVALID_DATA } +data class IosSshExportResult(val bytes: ByteArray?, val failure: IosSshExportFailure?, val duplicateNames: List = emptyList()) +enum class IosSshImportField { HOST, PORT, USERNAME, AUTHENTICATION, STARTUP_COMMAND, KEEPALIVE_SECONDS } +data class IosSshFieldChange(val field: IosSshImportField, val before: String, val after: String) +data class IosSshImportPreview(val before: SshProfile?, val after: SshProfile, + val changes: List, val startupWarning: Boolean, val needsKeySelection: Boolean) + +/** Synchronous value operations. Swift serializes metadata transactions and writes atomically. */ +class IosSshDomain { + private val json = Json { encodeDefaults = true } + fun emptyData(): SshData = SshData() + + fun profile(id: String, name: String, host: String, port: Int, username: String, + authentication: SshAuthentication, secretRef: String?, keyRef: String?, startupCommand: String, + keepaliveSeconds: Int): SshProfile? = SshProfile(id, name, host, port, username, authentication, + secretRef, keyRef, startupCommand, keepaliveSeconds).takeIf { it.valid() } + + fun decodeData(bytes: ByteArray): IosSshDataResult { + if (bytes.size > 1_048_576) return invalid(IosSshDataFailure.SIZE) + val text = try { bytes.decodeToString(throwOnInvalidSequence = true) } + catch (_: CharacterCodingException) { return invalid(IosSshDataFailure.UTF8) } + if (jsonNestingDepth(text) > JSON_MAX_DEPTH) return invalid(IosSshDataFailure.FORMAT) + return try { + val root = json.parseToJsonElement(text) as? JsonObject ?: return invalid(IosSshDataFailure.FORMAT) + val schema = (root["schema"] as? JsonPrimitive)?.takeUnless { it.isString }?.intOrNull + if (schema != 1) invalid(IosSshDataFailure.SCHEMA) + else checked(json.decodeFromString(SshData.serializer(), text)) + } catch (_: SerializationException) { invalid(IosSshDataFailure.FORMAT) } + catch (_: IllegalArgumentException) { invalid(IosSshDataFailure.FORMAT) } + } + + fun encodeData(data: SshData): ByteArray? = if (!data.valid()) null else + json.encodeToString(SshData.serializer(), data).encodeToByteArray().takeIf { it.size <= 1_048_576 } + + /** Swift must obtain validated, frozen bytes before presenting the file exporter. */ + fun prepareExport(data: SshData): IosSshExportResult = try { + IosSshExportResult(encodeSshProfileExport(data), null) + } catch (error: SshProfileExportException) { + when (val reason = error.reason) { + is SshProfileExportError.DuplicateNames -> IosSshExportResult(null, IosSshExportFailure.DUPLICATE_NAMES, reason.names) + SshProfileExportError.TooLarge -> IosSshExportResult(null, IosSshExportFailure.TOO_LARGE) + } + } catch (_: IllegalArgumentException) { IosSshExportResult(null, IosSshExportFailure.INVALID_DATA) } + + fun moveProfile(data: SshData, id: String, delta: Int): IosSshDataResult = + if (!data.valid()) invalid(IosSshDataFailure.INVALID_DATA) else checked(moveSshProfile(data, id, delta)) + + fun needsKeySelection(profile: SshProfile, data: SshData): Boolean = profile.needsKeySelection(data) + + fun upsertProfile(data: SshData, profile: SshProfile): IosSshDataResult { + if (!data.valid() || !profile.valid()) return invalid(IosSshDataFailure.INVALID_DATA) + val previous = data.profiles.firstOrNull { it.id == profile.id } + val targetChanged = previous != null && (previous.host != profile.host || previous.port != profile.port || previous.username != profile.username) + val saved = if (targetChanged) profile.copy(secretRef = null) else profile + val updated = if (previous == null) data.profiles + saved else data.profiles.map { if (it.id == profile.id) saved else it } + return checked(data.copy(profiles = updated)) + } + + fun upsertKey(data: SshData, key: SshKeyInfo): IosSshDataResult { + if (!data.valid()) return invalid(IosSshDataFailure.INVALID_DATA) + val updated = if (data.keys.none { it.id == key.id }) data.keys + key else data.keys.map { if (it.id == key.id) key else it } + return checked(data.copy(keys = updated)) + } + + /** Metadata only: persist the result before deleting unreferenced Keychain material. */ + fun deleteProfile(data: SshData, id: String): IosSshDataResult { + if (!data.valid()) return invalid(IosSshDataFailure.INVALID_DATA) + if (data.profiles.none { it.id == id }) return invalid(IosSshDataFailure.CONFLICT) + return checked(data.copy(profiles = data.profiles.filterNot { it.id == id })) + } + + /** A key referenced by any profile cannot be removed, regardless of authentication mode. */ + fun deleteKey(data: SshData, id: String): IosSshDataResult { + if (!data.valid()) return invalid(IosSshDataFailure.INVALID_DATA) + if (data.keys.none { it.id == id } || data.profiles.any { it.keyRef == id }) + return invalid(IosSshDataFailure.CONFLICT) + return checked(data.copy(keys = data.keys.filterNot { it.id == id })) + } + + fun hostDecision(data: SshData, offered: TrustedHostKey): HostKeyDecision = + hostKeyDecision(data.hostKeys.firstOrNull { it.endpoint == offered.endpoint }, offered) + + /** Unknown-host confirmation cannot replace a different saved key, including a racing insertion. */ + fun trustUnknown(data: SshData, offered: TrustedHostKey): IosSshDataResult { + if (!data.valid()) return invalid(IosSshDataFailure.INVALID_DATA) + val previous = data.hostKeys.firstOrNull { it.endpoint == offered.endpoint } + if (previous != null && previous != offered) return invalid(IosSshDataFailure.CONFLICT) + return checked(if (previous == null) data.copy(hostKeys = data.hostKeys + offered) else data) + } + + fun recordRejected(data: SshData, offered: TrustedHostKey): IosSshDataResult = if (!data.valid()) invalid(IosSshDataFailure.INVALID_DATA) + else checked(data.copy(rejectedHostKeys = (data.rejectedHostKeys.filterNot { it.endpoint == offered.endpoint } + offered).takeLast(500))) + + /** User-confirmed trust reset retains the last rejected key, as on Android. */ + fun forgetHost(data: SshData, endpoint: String): IosSshDataResult = if (!data.valid()) invalid(IosSshDataFailure.INVALID_DATA) + else checked(data.copy(hostKeys = data.hostKeys.filterNot { it.endpoint == endpoint })) + + fun previousRejected(data: SshData, offered: TrustedHostKey): TrustedHostKey? = + distinctRejectedHostKey(offered, data.rejectedHostKeys.firstOrNull { it.endpoint == offered.endpoint }) + + fun decodeImport(bytes: ByteArray): IosSshImportResult = try { + IosSshImportResult(decodeSshProfileImport(bytes), null) + } catch (error: SshProfileImportException) { IosSshImportResult(null, error.reason) } + + fun planImport(current: SshData, imported: SshProfileImport, keyRef: String?, generateId: () -> String): IosSshPlanResult = try { + IosSshPlanResult(planSshProfileImport(current, imported, keyRef, generateId), null) + } catch (error: SshProfileImportException) { IosSshPlanResult(null, error.reason) } + + fun applyImport(current: SshData, plan: SshImportPlan): IosSshImportApplyResult = try { + IosSshImportApplyResult(applySshImportPlan(current, plan), null) + } catch (error: SshProfileImportException) { IosSshImportApplyResult(null, error.reason) } + + /** Avoid a Cocoa `new`-family getter name at the Swift preview boundary. */ + fun importAddedCount(plan: SshImportPlan): Int = plan.newProfiles.size + + fun importDetachedRefs(plan: SshImportPlan): List = plan.detachedSecretRefs + + /** Values stay unlocalized; Swift supplies CS/EN labels and authentication names. */ + fun importProfilePreviews(plan: SshImportPlan, data: SshData): List = + (plan.newProfiles + plan.updatedProfiles + plan.unchangedProfiles).map { entry -> + val before = entry.before + val after = entry.after + val changes = buildList { + fun change(field: IosSshImportField, old: String, updated: String) { + if (old != updated) add(IosSshFieldChange(field, old, updated)) + } + if (before != null) { + change(IosSshImportField.HOST, before.host, after.host) + change(IosSshImportField.PORT, before.port.toString(), after.port.toString()) + change(IosSshImportField.USERNAME, before.username, after.username) + change(IosSshImportField.AUTHENTICATION, before.authentication.name, after.authentication.name) + change(IosSshImportField.STARTUP_COMMAND, before.startupCommand, after.startupCommand) + change(IosSshImportField.KEEPALIVE_SECONDS, before.keepaliveSeconds.toString(), after.keepaliveSeconds.toString()) + } + } + IosSshImportPreview(before, after, changes, + if (before == null) after.startupCommand.isNotEmpty() else before.startupCommand != after.startupCommand, + after.needsKeySelection(data)) + } + + fun importChangedEndpoints(plan: SshImportPlan): List = + plan.updatedProfiles.mapNotNull { entry -> + val before = entry.before ?: return@mapNotNull null + val after = entry.after + if (before.host == after.host && before.port == after.port && before.username == after.username) null + else IosSshEndpointChange(after.id, "${before.username}@${before.endpoint}", "${after.username}@${after.endpoint}") + } + + fun kexAlgorithms(): List = SshAlgorithms.kex + fun hostKeyAlgorithms(): List = SshAlgorithms.hostKeys + fun cipherAlgorithms(): List = SshAlgorithms.ciphers + fun macAlgorithms(): List = SshAlgorithms.macs + private fun checked(data: SshData): IosSshDataResult = if (data.valid()) IosSshDataResult(data, null) else invalid(IosSshDataFailure.INVALID_DATA) + private fun invalid(failure: IosSshDataFailure) = IosSshDataResult(null, failure) +} diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt new file mode 100644 index 0000000..d3fb586 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt @@ -0,0 +1,50 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.ssh.* + +/** Swift serializes all terminal calls on its main actor; no terminal contents are persisted. */ +class IosTerminal(columns: Int, rows: Int) { + private val buffer = TerminalBuffer(columns, rows) + private val pending = StringBuilder() + private var overflow = false + private val composition = TerminalComposition { edit -> + val encoded = when (edit) { + is TerminalEdit.Text -> edit.value + is TerminalEdit.Key -> terminalKeySequence(edit.value, buffer.snapshot().applicationCursorKeys) + } + if (pending.length + encoded.length > TerminalComposition.MAX_TEXT) overflow = true + else if (!overflow) pending.append(encoded) + } + + fun feed(text: String): String = buffer.feed(text) + fun snapshot(): TerminalSnapshot = buffer.snapshot() + fun resize(columns: Int, rows: Int) { buffer.resize(columns, rows) } + fun keySequence(key: TerminalKey, control: Boolean, alt: Boolean, shift: Boolean): String = + terminalKeySequence(key, buffer.snapshot().applicationCursorKeys, control, alt, shift) + fun textSequence(text: String, control: Boolean, alt: Boolean): String = terminalTextSequence(text, control, alt) + fun safePaste(text: String): String = safeTerminalPaste(text) + fun pasteNeedsConfirmation(text: String): Boolean = cz.netkit.shared.ssh.pasteNeedsConfirmation(text) + fun composeSet(value: String) { composition.set(value) } + fun composeCommit(value: String) { composition.commit(value) } + fun composeFinish() { composition.finish() } + fun composeClear() { composition.clear(); pending.clear(); overflow = false } + fun composeDelete(before: Int, after: Int, codePoints: Boolean): Boolean = composition.delete(before, after, codePoints) + + /** Drain immediately after each editing action. Overflow never returns truncated terminal commands. */ + fun drainInput(): String? { + val result = if (overflow) null else pending.toString() + pending.clear(); overflow = false + return result + } +} + +/** Match the shared monotonic background grace period; Swift supplies uptime including sleep. */ +class IosSshLifecycle(nowMillis: () -> Long) { + private val policy = SshBackgroundPolicy(nowMillis) + fun background() { policy.background() } + fun foreground(): Boolean = policy.foreground() + fun expired(): Boolean = policy.expired() + fun remainingMillis(): Long? = policy.remainingMillis() + fun promptTimeoutMillis(): Long = SshPromptPolicy.PROMPT_TIMEOUT_MILLIS + fun handshakeTimeoutMillis(): Long = SshPromptPolicy.HANDSHAKE_TIMEOUT_MILLIS +} diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt new file mode 100644 index 0000000..36eed3d --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt @@ -0,0 +1,114 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.wol.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.collect + +/** Idempotent cancellation; Swift marshals cancellation onto its transport queue and closes the socket. */ +interface IosCancellation { fun cancel() } + +data class IosWifiSnapshot(val token: String, val ipv4: String?, val prefixLength: Int?) +data class IosWolLoadResult(val devices: List, val failure: StoreFailure?) + +/** Main-thread calls. A changed network token must fail with NETWORK_LOST, never fall back to cellular. */ +interface IosWolPlatform { + fun currentWifi(): IosWifiSnapshot? + fun sendUdp(networkToken: String, host: String, port: Int, payload: ByteArray, completion: (SendFailure?) -> Unit): IosCancellation + fun probe(networkToken: String, host: String, port: Int?, completion: (WakeProbeStatus) -> Unit): IosCancellation +} + +/** Persistent Swift storage reports failure explicitly; it must never replace unreadable data by an empty list. */ +interface IosWolPersistence { + fun load(): IosWolLoadResult + fun save(devices: List): Boolean +} + +private data class IosWifiHandle(val token: String) : WifiNetworkHandle + +/** Owns a MainScope and the existing WolController, rather than reimplementing its send/state machine in Swift. */ +class IosWolBridge internal constructor( + platform: IosWolPlatform, + persistence: IosWolPersistence, + nowMillis: () -> Long, + newId: () -> String, + private val scope: CoroutineScope, +) { + constructor(platform: IosWolPlatform, persistence: IosWolPersistence, nowMillis: () -> Long, newId: () -> String) : + this(platform, persistence, nowMillis, newId, MainScope()) + + val controller = WolController( + store = object : WolDeviceStore { + override suspend fun load(): List { + val result = persistence.load() + result.failure?.let { throw StoreReadException(it) } + return result.devices + } + override suspend fun save(devices: List) { + if (!persistence.save(devices)) throw StoreReadException(StoreFailure.IO) + } + }, + networkInfo = object : NetworkInfoProvider { + override suspend fun currentWifi(): WifiNetworkInfo? = platform.currentWifi()?.takeIf { it.token.isNotBlank() }?.let { + WifiNetworkInfo(IosWifiHandle(it.token), it.ipv4, it.prefixLength) + } + }, + sender = object : PacketSender { + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { + send(platform, (network as IosWifiHandle).token, host, port, payload) + } + }, + prober = object : WakeProber { + override suspend fun probe(network: WifiNetworkHandle, host: String, port: Int?): WakeProbeStatus = + probe(platform, (network as IosWifiHandle).token, host, port) + }, + scope = scope, nowMillis = nowMillis, newId = newId, + ) + + fun currentState(): WolUiState = controller.state.value + + fun observe(onState: (WolUiState) -> Unit): IosCancellation { + val job = scope.launch { controller.state.collect { onState(it) } } + return object : IosCancellation { override fun cancel() { job.cancel() } } + } + + fun draft(id: String?, name: String, mac: String, targetMode: TargetMode, customTarget: String, port: Int): WolDeviceDraft = + WolDeviceDraft(id = id, name = name, mac = mac, targetMode = targetMode, customTarget = customTarget, port = port.toString()) + + fun saveDraft(draft: WolDeviceDraft): Boolean { + if (draft.id == null) controller.add() else controller.edit(requireNotNull(draft.id)) + controller.updateDraft(draft) + if (controller.state.value.draft != draft || !validateDevice(draft).isValid) return false + controller.save() + return true + } + + fun close() { controller.cancelWake(); scope.cancel() } +} + +@OptIn(InternalCoroutinesApi::class) +private suspend fun send(platform: IosWolPlatform, token: String, host: String, port: Int, payload: ByteArray) = + suspendCancellableCoroutine { continuation -> + var operation: IosCancellation? = null + continuation.invokeOnCancellation { operation?.cancel() } + if (!continuation.isActive) return@suspendCancellableCoroutine + operation = platform.sendUdp(token, host, port, payload) { failure -> + val resumed = if (failure == null) continuation.tryResume(Unit) + else continuation.tryResumeWithException(PacketSendException(failure)) + if (resumed != null) continuation.completeResume(resumed) + } + // Also covers cancellation or synchronous completion before sendUdp returned its handle. + if (!continuation.isActive) operation.cancel() + } + +@OptIn(InternalCoroutinesApi::class) +private suspend fun probe(platform: IosWolPlatform, token: String, host: String, port: Int?): WakeProbeStatus = + suspendCancellableCoroutine { continuation -> + var operation: IosCancellation? = null + continuation.invokeOnCancellation { operation?.cancel() } + if (!continuation.isActive) return@suspendCancellableCoroutine + operation = platform.probe(token, host, port) { result -> + val resumed = continuation.tryResume(result) + if (resumed != null) continuation.completeResume(resumed) + } + if (!continuation.isActive) operation.cancel() + } diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt new file mode 100644 index 0000000..452aa40 --- /dev/null +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt @@ -0,0 +1,20 @@ +package cz.netkit.shared.ios + +import cz.netkit.shared.wol.* + +/** Reuses the bounded UTF-8/schema validation of the shared WoL transfer codec. */ +class IosWolCodec { + fun decode(bytes: ByteArray): IosWolLoadResult = try { + IosWolLoadResult(decodeWolImport(bytes), null) + } catch (error: WolImportException) { + IosWolLoadResult(emptyList(), if (error.reason == WolImportFailure.SCHEMA) StoreFailure.UNSUPPORTED_SCHEMA else StoreFailure.CORRUPT) + } catch (_: IllegalArgumentException) { + IosWolLoadResult(emptyList(), StoreFailure.CORRUPT) + } + + fun encode(devices: List): ByteArray? = try { + if (!validateStoredDevices(devices)) null else encodeWolExport(devices) + } catch (_: IllegalArgumentException) { + null + } +} diff --git a/shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt b/shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt new file mode 100644 index 0000000..5911036 --- /dev/null +++ b/shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt @@ -0,0 +1,23 @@ +package cz.netkit.shared + +import cz.netkit.shared.ios.IosAboutDomain +import kotlin.test.Test +import kotlin.test.assertEquals + +class IosAboutDomainTest { + @Test + fun privacyUsesCzechForCzechLanguage() { + val domain = IosAboutDomain() + for (language in listOf("cs", "CS")) { + assertEquals("https://www.daniel.losak.cz/netkit/privacy", domain.privacyUrl(language)) + } + } + + @Test + fun privacyUsesEnglishForEveryOtherLanguage() { + val domain = IosAboutDomain() + for (language in listOf("en", "de", "", "unknown")) { + assertEquals("https://www.daniel.losak.cz/en/netkit/privacy", domain.privacyUrl(language)) + } + } +} diff --git a/shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt b/shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt new file mode 100644 index 0000000..ddf6cfb --- /dev/null +++ b/shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt @@ -0,0 +1,173 @@ +package cz.netkit.shared + +import cz.netkit.shared.ios.* +import cz.netkit.shared.wol.* +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.* +import kotlin.test.* + +@OptIn(ExperimentalCoroutinesApi::class) +class IosBridgeTest { + @Test fun dnsResponseRejectsMismatchedTruncatedOrNonResponsePackets() { + val domain = IosNetworkDomain() + val query = assertNotNull(domain.dnsQuery("localhost", 1, 123)) + assertEquals(1, query[2].toInt()) // Unicast DNS requests recursive resolution. + assertNull(domain.dnsResponse(query, 123, "localhost", 1)) + val response = query.copyOf().also { it[2] = 0x81.toByte(); it[3] = 0x80.toByte() } + assertEquals(emptyList(), domain.dnsResponse(response, 123, "localhost", 1)) + assertNull(domain.dnsResponse(response, 124, "localhost", 1)) + assertNull(domain.dnsResponse(response, 123, "other.local", 1)) + assertNull(domain.dnsResponse(response, 123, "localhost", 12)) + response[2] = 0x83.toByte() + assertNull(domain.dnsResponse(response, 123, "localhost", 1)) + assertNull(domain.dnsResponse(response.copyOf(8), 123, "localhost", 1)) + } + + @Test fun networkBridgeUsesSharedValidationAndIcmpNonceMatching() { + val domain = IosNetworkDomain() + assertEquals(listOf(22, 443), domain.ports("22,443")) + assertNull(domain.ports("65536")) + assertEquals("printer label", domain.mdnsName("printer\u202Elabel")?.value) + val request = ByteArray(16) { it.toByte() }.also { it[0] = 8; it[1] = 0 } + val reply = request.copyOf().also { it[0] = 0 } + assertTrue(domain.icmpReplyMatches(request, reply)) + reply[15] = 0 + assertFalse(domain.icmpReplyMatches(request, reply)) + } + + @Test fun speedBridgeKeepsSharedUrlPolicyAndThroughputMath() { + val domain = IosSpeedDomain() + assertNull(domain.libreServer("http://localhost/")) + assertEquals("https://localhost/", domain.libreServer("localhost")?.baseUrl) + assertEquals(emptyList(), domain.ndtTargets("{}")) + assertNull(domain.ndtView("not-json", true)) + val trace = domain.createTrace() + for (time in 250L..10_000L step 250) assertTrue(trace.add(time, time * 1_000)) + assertEquals(8.0, assertNotNull(domain.summarize(trace)).mbps) + } + + @Test fun wolBridgeRunsExistingControllerAndPassesPinnedNetworkAndMagicPacket() = runTest { + val platform = FakePlatform() + val bridge = bridge(platform, MemoryPersistence(), this) + runCurrent() + bridge.controller.wake("device") + advanceUntilIdle() + val call = assertNotNull(platform.packet) + assertEquals("wifi-test", call.first) + assertEquals("192.0.2.255", platform.host) + assertEquals(102, call.second.size) + assertTrue(call.second.take(6).all { it == 0xff.toByte() }) + assertTrue(bridge.currentState().outcomes.getValue("device").sent) + } + + @Test fun wolCancellationCancelsNativeOperationAndIgnoresLateOrDuplicateCompletion() = runTest { + val platform = FakePlatform(completeImmediately = false) + val bridge = bridge(platform, MemoryPersistence(), this) + runCurrent() + bridge.controller.wake("device") + runCurrent() + bridge.controller.cancelWake() + runCurrent() + assertTrue(platform.cancelled) + platform.callback?.invoke(null) + platform.callback?.invoke(SendFailure.IO) + runCurrent() + assertEquals(SendFailure.CANCELLED, bridge.currentState().outcomes.getValue("device").reason) + } + + @Test fun wolTransportAndPersistenceFailuresAreNotSuccessfulEmptyState() = runTest { + val platform = FakePlatform(failure = SendFailure.NETWORK_LOST) + val bridge = bridge(platform, MemoryPersistence(), this) + runCurrent() + bridge.controller.wake("device") + advanceUntilIdle() + assertEquals(SendFailure.NETWORK_LOST, bridge.currentState().outcomes.getValue("device").reason) + val failed = bridge(platform, MemoryPersistence(loadFailure = StoreFailure.CORRUPT), this) + runCurrent() + assertTrue(failed.currentState().loadFailed) + assertEquals(StoreFailure.CORRUPT, failed.currentState().loadFailure) + } + + @Test fun wolCodecRoundTripsAndRejectsCorruptOrUnsupportedDocuments() { + val codec = IosWolCodec() + val devices = MemoryPersistence().load().devices + val encoded = assertNotNull(codec.encode(devices)) + val decoded = codec.decode(encoded) + assertNull(decoded.failure) + assertEquals(devices, decoded.devices) + assertEquals(StoreFailure.CORRUPT, codec.decode("not-json".encodeToByteArray()).failure) + assertEquals(StoreFailure.CORRUPT, codec.decode(byteArrayOf(0xC3.toByte())).failure) + assertEquals(StoreFailure.UNSUPPORTED_SCHEMA, + codec.decode("{\"schema\":999,\"devices\":[]}".encodeToByteArray()).failure) + assertNull(codec.encode(devices + devices)) // Duplicate IDs must not be persisted. + } + + @Test fun wolBridgeRunsControllerPrecheckAndPreservesAlreadyRespondedResult() = runTest { + val platform = FakePlatform() + val bridge = bridge(platform, MemoryPersistence(probeEnabled = true), this) + runCurrent() + bridge.controller.wake("device") + advanceUntilIdle() + assertEquals(1, platform.probeCalls) + assertEquals("wifi-test", platform.observedNetwork) + assertEquals("192.0.2.42", platform.probeHost) + assertEquals(22, platform.probePort) + assertNotNull(platform.packet) + assertTrue(bridge.currentState().outcomes.getValue("device").sent) + assertEquals(WakeProbeStatus.ALREADY_RESPONDED, bridge.currentState().probes["device"]) + } + + @Test fun wolPrecheckCancellationCancelsPlatformProbeAndIgnoresLateCompletion() = runTest { + val platform = FakePlatform(completeProbeImmediately = false) + val bridge = bridge(platform, MemoryPersistence(probeEnabled = true), this) + runCurrent() + bridge.controller.wake("device") + runCurrent() + assertEquals(1, platform.probeCalls) + assertNull(platform.packet) + bridge.controller.cancelWake() + runCurrent() + assertTrue(platform.probeCancelled) + platform.probeCallback?.invoke(WakeProbeStatus.RESPONDS) + platform.probeCallback?.invoke(WakeProbeStatus.NO_RESPONSE) + runCurrent() + assertNull(platform.packet) + assertEquals(SendFailure.CANCELLED, bridge.currentState().outcomes.getValue("device").reason) + } + + private fun bridge(platform: FakePlatform, store: MemoryPersistence, scope: TestScope) = + IosWolBridge(platform, store, { 1_000L }, { "new-device" }, scope) + + private class MemoryPersistence(private val loadFailure: StoreFailure? = null, probeEnabled: Boolean = false) : IosWolPersistence { + private var devices = listOf(WolDevice("device", "Test device", "02:00:00:00:00:01", TargetMode.AUTO_BROADCAST, + createdAt = 1, updatedAt = 1, repeatCount = 1, probeEnabled = probeEnabled, + probeHost = if (probeEnabled) "192.0.2.42" else null, probePort = if (probeEnabled) 22 else null)) + override fun load() = IosWolLoadResult(devices, loadFailure) + override fun save(devices: List): Boolean { this.devices = devices; return true } + } + + private class FakePlatform(private val completeImmediately: Boolean = true, private val failure: SendFailure? = null, + private val completeProbeImmediately: Boolean = true) : IosWolPlatform { + var packet: Pair? = null + var host: String? = null + var cancelled = false + var callback: ((SendFailure?) -> Unit)? = null + var probeCalls = 0 + var observedNetwork: String? = null + var probeHost: String? = null + var probePort: Int? = null + var probeCancelled = false + var probeCallback: ((WakeProbeStatus) -> Unit)? = null + override fun currentWifi() = IosWifiSnapshot("wifi-test", "192.0.2.42", 24) + override fun sendUdp(networkToken: String, host: String, port: Int, payload: ByteArray, completion: (SendFailure?) -> Unit): IosCancellation { + packet = networkToken to payload; this.host = host; callback = completion + if (completeImmediately) completion(failure) + return object : IosCancellation { override fun cancel() { cancelled = true } } + } + override fun probe(networkToken: String, host: String, port: Int?, completion: (WakeProbeStatus) -> Unit): IosCancellation { + probeCalls++; observedNetwork = networkToken; probeHost = host; probePort = port; probeCallback = completion + if (completeProbeImmediately) completion(WakeProbeStatus.RESPONDS) + return object : IosCancellation { override fun cancel() { probeCancelled = true } } + } + } +} diff --git a/shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt b/shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt new file mode 100644 index 0000000..fc21308 --- /dev/null +++ b/shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt @@ -0,0 +1,20 @@ +package cz.netkit.shared + +import cz.netkit.shared.wol.directedBroadcast +import cz.netkit.shared.wol.parseIpv4 +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** Runs on Kotlin/Native without a socket or platform service. */ +class IosDomainSmokeTest { + @Test + fun ipv4ParserAndBroadcastRunOnNative() { + val address = assertNotNull(parseIpv4("192.0.2.42")) + assertEquals("192.0.2.42", address.toString()) + assertEquals("192.0.2.255", directedBroadcast(address, 24)?.toString()) + assertNull(parseIpv4("192.0.2.256")) + assertNull(directedBroadcast(address, 32)) + } +} diff --git a/shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt b/shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt new file mode 100644 index 0000000..ad0102f --- /dev/null +++ b/shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt @@ -0,0 +1,294 @@ +package cz.netkit.shared + +import cz.netkit.shared.ios.* +import cz.netkit.shared.ssh.* +import kotlinx.coroutines.test.runTest +import kotlin.random.Random +import kotlin.test.* + +class IosSshBridgeTest { + private val domain = IosSshDomain() + private fun profile(host: String = "192.0.2.1", secretRef: String? = null) = assertNotNull(domain.profile( + "profile-a", "Test target", host, 22, "tester", SshAuthentication.PASSWORD, secretRef, null, "", 30)) + private fun key(blob: String) = TrustedHostKey("[192.0.2.1]:22", "ssh-ed25519", blob, "SHA256:$blob") + + @Test fun metadataRoundTripIsBoundedStrictAndVersioned() { + val data = assertNotNull(domain.upsertProfile(domain.emptyData(), profile()).data) + val bytes = assertNotNull(domain.encodeData(data)) + assertEquals(data, domain.decodeData(bytes).data) + assertEquals(IosSshDataFailure.SIZE, domain.decodeData(ByteArray(1_048_577)).failure) + assertEquals(IosSshDataFailure.UTF8, domain.decodeData(byteArrayOf(0xC3.toByte())).failure) + assertEquals(IosSshDataFailure.FORMAT, domain.decodeData("[]".encodeToByteArray()).failure) + assertEquals(IosSshDataFailure.SCHEMA, domain.decodeData("{\"schema\":2}".encodeToByteArray()).failure) + assertEquals(IosSshDataFailure.SCHEMA, domain.decodeData("{\"schema\":\"1\"}".encodeToByteArray()).failure) + assertEquals(IosSshDataFailure.FORMAT, domain.decodeData("{\"schema\":1,\"unexpected\":true}".encodeToByteArray()).failure) + val deep = "{\"schema\":1,\"unexpected\":" + "[".repeat(20) + "0" + "]".repeat(20) + "}" + assertEquals(IosSshDataFailure.FORMAT, domain.decodeData(deep.encodeToByteArray()).failure) + } + + @Test fun tofuCannotReplaceTrustedKeyAndResetRetainsRejectedEvidence() { + val runtimeBlob = Random.nextBytes(32).joinToString("") { it.toUByte().toString(16).padStart(2, '0') } + val offered = key(runtimeBlob) + val changed = key(runtimeBlob + "changed") + assertEquals(HostKeyDecision.UNKNOWN, domain.hostDecision(domain.emptyData(), offered)) + val trusted = assertNotNull(domain.trustUnknown(domain.emptyData(), offered).data) + assertEquals(HostKeyDecision.TRUSTED, domain.hostDecision(trusted, offered)) + assertEquals(HostKeyDecision.CHANGED, domain.hostDecision(trusted, changed)) + assertEquals(IosSshDataFailure.CONFLICT, domain.trustUnknown(trusted, changed).failure) + val rejected = assertNotNull(domain.recordRejected(trusted, changed).data) + val reset = assertNotNull(domain.forgetHost(rejected, offered.endpoint).data) + assertTrue(reset.hostKeys.isEmpty()) + assertEquals(listOf(changed), reset.rejectedHostKeys) + assertNull(domain.previousRejected(reset, changed)) + assertEquals(changed, domain.previousRejected(reset, offered)) + } + + @Test fun profileImportPreviewDetachesCredentialsAndRejectsStalePlan() { + val before = assertNotNull(domain.upsertProfile(domain.emptyData(), profile(secretRef = "credential-a")).data) + val document = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"Test target","host":"192.0.2.2","port":22,"username":"tester"}],"skipped":[]}""" + val incoming = assertNotNull(domain.decodeImport(document.encodeToByteArray()).imported) + val plan = assertNotNull(domain.planImport(before, incoming, null) { "profile-b" }.plan) + assertEquals(listOf("credential-a"), plan.detachedSecretRefs) + val after = assertNotNull(domain.applyImport(before, plan).data) + assertEquals("192.0.2.2", after.profiles.single().host) + assertNull(after.profiles.single().secretRef) + assertEquals(SshProfileImportFailure.STALE_PLAN, domain.applyImport(after, plan).failure) + assertEquals(SshProfileImportFailure.SIZE, domain.decodeImport(ByteArray(SSH_PROFILE_IMPORT_LIMIT + 1)).failure) + val runtimeValue = Random.nextBytes(16).joinToString("") { it.toUByte().toString(16) } + val withCredential = document.replace("\"username\":\"tester\"", "\"username\":\"tester\",\"password\":\"$runtimeValue\"") + assertEquals(SshProfileImportFailure.UNKNOWN_FIELD, domain.decodeImport(withCredential.encodeToByteArray()).failure) + } + + @Test fun terminalPreservesStyledOutputAndSharedKeyEncoding() { + val terminal = IosTerminal(80, 24) + terminal.feed("\u001b[31mred\u001b[0m\u001b[?1h") + assertTrue(terminal.snapshot().screen.first().text.startsWith("red")) + assertEquals(1, terminal.snapshot().screen.first().runs.first().foreground) + assertEquals("\u001bOA", terminal.keySequence(TerminalKey.UP, false, false, false)) + assertEquals("\u0003", terminal.textSequence("c", true, false)) + terminal.resize(999, 999) + assertEquals(100, terminal.snapshot().screen.size) + assertEquals(240, terminal.snapshot().screen.first().text.length) + } + + @Test fun compositionIsBoundedAndPasteCannotInjectControls() { + val terminal = IosTerminal(80, 24) + terminal.composeSet("a😀") + assertTrue(terminal.composeDelete(1, 0, true)) + terminal.composeFinish() + assertEquals("a", terminal.drainInput()) + terminal.composeCommit("text") + terminal.composeCommit("\n") + assertEquals("text\r", terminal.drainInput()) + terminal.composeCommit("x".repeat(16_384)) + terminal.composeCommit("y") + assertNull(terminal.drainInput()) + assertEquals("", terminal.drainInput()) + assertTrue(terminal.pasteNeedsConfirmation("a\n\u001bb")) + assertEquals("a b", terminal.safePaste("a\n\u001bb")) + } + + @Test fun lifecycleUsesSharedMonotonicGraceAndPromptLimits() { + var now = 1_000L + val lifecycle = IosSshLifecycle { now } + lifecycle.background() + assertEquals(300_000L, lifecycle.remainingMillis()) + now += 299_999 + assertFalse(lifecycle.expired()) + now++ + assertTrue(lifecycle.foreground()) + assertNull(lifecycle.remainingMillis()) + assertEquals(180_000L, lifecycle.promptTimeoutMillis()) + assertEquals(600_000L, lifecycle.handshakeTimeoutMillis()) + } + + @Test fun sharedSecretStoreAndSwiftResultsUseSameBackendAndSurfaceFailures() = runTest { + val backend = MemorySecrets() + val adapter = IosSecretStoreAdapter(backend) + val shared: SecretStore = adapter.sharedStore + val material = Random.nextBytes(32) + val secondMaterial = Random.nextBytes(32) + shared.put("credential-a", material) + assertContentEquals(material, adapter.getSecret("credential-a").bytes) + assertContentEquals(material, shared.get("credential-a")) + shared.delete("credential-a") + assertNull(shared.get("credential-a")) + backend.failure = SshFailure.SECRET_UNAVAILABLE + assertEquals(SshFailure.SECRET_UNAVAILABLE, adapter.putSecret("credential-a", secondMaterial)) + assertEquals(SshFailure.SECRET_UNAVAILABLE, assertFailsWith { shared.put("credential-a", secondMaterial) }.failure) + assertFailsWith { shared.get("credential-a") } + assertFailsWith { shared.delete("credential-a") } + assertNull(adapter.getSecret("credential-a").bytes) + } + + @Test fun profileEndpointChangeDetachesSavedPasswordAndKeyMetadataIsValidated() { + val before = assertNotNull(domain.upsertProfile(domain.emptyData(), profile(secretRef = "credential-a")).data) + val changed = assertNotNull(domain.upsertProfile(before, profile("192.0.2.2", "credential-a")).data) + assertNull(changed.profiles.single().secretRef) + val same = assertNotNull(domain.upsertProfile(before, profile(secretRef = "credential-a")).data) + assertEquals("credential-a", same.profiles.single().secretRef) + val publicValue = Random.nextBytes(32).joinToString("") { it.toUByte().toString(16) } + val withKey = assertNotNull(domain.upsertKey(before, SshKeyInfo("key-a", "Test key", publicValue)).data) + assertEquals(1, withKey.keys.size) + assertEquals(IosSshDataFailure.INVALID_DATA, domain.upsertKey(withKey, SshKeyInfo("invalid/id", "Test", publicValue)).failure) + } + + @Test fun deletionPreservesReferencedKeysAndRejectsStaleOrInvalidMetadata() { + val publicValue = Random.nextBytes(32).joinToString("") { it.toUByte().toString(16) } + val original = SshData(profiles = listOf(profile().copy(keyRef = "key-a")), + keys = listOf(SshKeyInfo("key-a", "Test key", publicValue))) + assertEquals(IosSshDataFailure.CONFLICT, domain.deleteKey(original, "key-a").failure) + assertEquals(IosSshDataFailure.CONFLICT, domain.deleteProfile(original, "missing").failure) + val withoutProfile = assertNotNull(domain.deleteProfile(original, "profile-a").data) + assertTrue(withoutProfile.profiles.isEmpty()) + assertEquals(original.keys, withoutProfile.keys) + val withoutKey = assertNotNull(domain.deleteKey(withoutProfile, "key-a").data) + assertTrue(withoutKey.keys.isEmpty()) + assertEquals(IosSshDataFailure.CONFLICT, domain.deleteKey(withoutKey, "key-a").failure) + assertEquals(IosSshDataFailure.INVALID_DATA, domain.deleteProfile(original.copy(schema = 2), "profile-a").failure) + assertEquals(IosSshDataFailure.INVALID_DATA, domain.deleteKey(original.copy(schema = 2), "key-a").failure) + assertEquals("key-a", original.profiles.single().keyRef) + } + + @Test fun importEndpointPreviewIncludesUserAndIpv6AndPreservesKeyReference() { + val originalProfile = profile(secretRef = "credential-a").copy(host = "2001:db8::1", keyRef = "key-a") + val before = SshData(profiles = listOf(originalProfile)) + val incoming = SshProfileImport(listOf(SshImportProfile("Test target", "2001:db8::2", 2222, "operator")), emptyList()) + val plan = assertNotNull(domain.planImport(before, incoming, null) { "profile-b" }.plan) + val change = domain.importChangedEndpoints(plan).single() + assertEquals("profile-a", change.profileId) + assertEquals("tester@[2001:db8::1]:22", change.before) + assertEquals("operator@[2001:db8::2]:2222", change.after) + assertEquals(listOf("credential-a"), domain.importDetachedRefs(plan)) + val applied = assertNotNull(domain.applyImport(before, plan).data) + assertNull(applied.profiles.single().secretRef) + assertEquals("key-a", applied.profiles.single().keyRef) + val edited = assertNotNull(domain.upsertProfile(before, originalProfile.copy(host = "2001:db8::2")).data) + assertEquals("key-a", edited.profiles.single().keyRef) + val unchanged = assertNotNull(domain.planImport(applied, incoming, null) { "profile-b" }.plan) + assertTrue(domain.importChangedEndpoints(unchanged).isEmpty()) + assertTrue(domain.importDetachedRefs(unchanged).isEmpty()) + } + + @Test fun v2ExportIsPortableOrderedAndUsesTypedFailures() { + val first = profile(secretRef = "credential-a").copy(keyRef = "key-a", startupCommand = "show version") + val second = first.copy(id = "profile-b", name = "Second", authentication = SshAuthentication.KEY) + val data = SshData(profiles = listOf(first, second), keys = listOf(SshKeyInfo("key-a", "Key", "public")), + hostKeys = listOf(key("runtime-public"))) + val exported = domain.prepareExport(data) + assertNull(exported.failure) + val bytes = assertNotNull(exported.bytes) + val text = bytes.decodeToString() + assertTrue(text.contains("\"schema\":2")) + for (field in listOf("id", "secretRef", "keyRef", "keys", "hostKeys", "rejectedHostKeys")) + assertFalse(text.contains("\"$field\""), field) + assertEquals(listOf(first.name, second.name), assertNotNull(domain.decodeImport(bytes).imported).profiles.map { it.alias }) + val duplicates = domain.prepareExport(data.copy(profiles = listOf(first, second.copy(name = first.name)))) + assertEquals(IosSshExportFailure.DUPLICATE_NAMES, duplicates.failure) + assertEquals(listOf(first.name), duplicates.duplicateNames) + assertNull(duplicates.bytes) + val large = SshData(profiles = (1..100).map { first.copy(id = "p-$it", name = "Target $it", startupCommand = "x".repeat(4096)) }) + assertEquals(IosSshExportFailure.TOO_LARGE, domain.prepareExport(large).failure) + assertNull(domain.prepareExport(large).bytes) + assertEquals(IosSshExportFailure.INVALID_DATA, domain.prepareExport(data.copy(schema = 2)).failure) + } + + @Test fun profileMovementPreservesMetadataAndRoundTripsInExportOrder() { + val first = profile(secretRef = "credential-a") + val second = first.copy(id = "profile-b", name = "Second") + val original = SshData(profiles = listOf(first, second), hostKeys = listOf(key("public"))) + assertEquals(original, domain.moveProfile(original, first.id, -1).data) + assertEquals(original, domain.moveProfile(original, second.id, 1).data) + assertEquals(original, domain.moveProfile(original, "missing", 1).data) + assertEquals(original, domain.moveProfile(original, first.id, 2).data) + val moved = assertNotNull(domain.moveProfile(original, second.id, -1).data) + assertEquals(listOf(second, first), moved.profiles) + assertEquals(original.hostKeys, moved.hostKeys) + assertEquals(moved, domain.decodeData(assertNotNull(domain.encodeData(moved))).data) + val imported = assertNotNull(domain.decodeImport(assertNotNull(domain.prepareExport(moved).bytes)).imported) + assertEquals(listOf(second.name, first.name), imported.profiles.map { it.alias }) + assertEquals(original, domain.moveProfile(moved, second.id, 1).data) + } + + @Test fun v2PreviewIncludesEveryChangedFieldAndAuthenticationDetachesPassword() { + val current = SshData(profiles = listOf(profile(secretRef = "credential-a"))) + val incoming = SshProfileImport(listOf(SshImportProfile("Test target", "192.0.2.2", 2222, "operator", + authentication = SshAuthentication.KEY, startupCommand = "show version", keepaliveSeconds = 60)), emptyList()) + val plan = assertNotNull(domain.planImport(current, incoming, null) { "unused" }.plan) + val preview = domain.importProfilePreviews(plan, current).single() + assertEquals(IosSshImportField.entries, preview.changes.map { it.field }) + assertEquals(listOf("192.0.2.1", "22", "tester", "PASSWORD", "", "30"), preview.changes.map { it.before }) + assertEquals(listOf("192.0.2.2", "2222", "operator", "KEY", "show version", "60"), preview.changes.map { it.after }) + assertTrue(preview.startupWarning) + assertTrue(preview.needsKeySelection) + val authOnly = incoming.copy(profiles = listOf(incoming.profiles.single().copy(host = "192.0.2.1", port = 22, username = "tester"))) + val authPlan = assertNotNull(domain.planImport(current, authOnly, null) { "unused" }.plan) + assertEquals(listOf("credential-a"), domain.importDetachedRefs(authPlan)) + assertNull(assertNotNull(domain.applyImport(current, authPlan).data).profiles.single().secretRef) + val keyed = SshData(profiles = listOf(profile().copy(authentication = SshAuthentication.KEY, + keyRef = "key-a", startupCommand = "show version")), keys = listOf(SshKeyInfo("key-a", "Key", "public"))) + val passwordRow = SshImportProfile("Test target", "192.0.2.1", 22, "tester", authentication = SshAuthentication.PASSWORD) + val passwordPlan = assertNotNull(domain.planImport(keyed, SshProfileImport(listOf(passwordRow), emptyList()), null) { "unused" }.plan) + val passwordPreview = domain.importProfilePreviews(passwordPlan, keyed).single() + assertNull(passwordPreview.after.keyRef) + assertTrue(passwordPreview.startupWarning) // Clearing a command is still a command change. + assertFalse(passwordPreview.needsKeySelection) + assertTrue(domain.importDetachedRefs(passwordPlan).isEmpty()) + assertEquals(keyed.keys, assertNotNull(domain.applyImport(keyed, passwordPlan).data).keys) + } + + @Test fun v1V2AndLegacyRespectSelectedKeyAndRejectBackupMaterial() { + val row = """{"alias":"Target","host":"192.0.2.1","port":22,"username":"tester"}""" + val v1 = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[$row],"skipped":[]}""" + val v2 = v1.replace("\"schema\":1", "\"schema\":2").replace("\"username\":\"tester\"", + "\"username\":\"tester\",\"authentication\":\"KEY\",\"startupCommand\":\"\",\"keepaliveSeconds\":30") + val legacy = """{"schema":1,"profiles":[{"id":"old-id","name":"Target","host":"192.0.2.1","port":22,"username":"tester","authentication":"KEY","secretRef":null,"keyRef":null,"startupCommand":"","keepaliveSeconds":30}],"keys":[],"hostKeys":[],"rejectedHostKeys":[]}""" + val current = SshData(keys = listOf(SshKeyInfo("key-a", "Key", "public"))) + for (document in listOf(v1, v2, legacy)) { + val incoming = assertNotNull(domain.decodeImport(document.encodeToByteArray()).imported) + val withKey = assertNotNull(domain.planImport(current, incoming, "key-a") { "local-id" }.plan) + val preview = domain.importProfilePreviews(withKey, current).single() + assertNull(preview.before) + assertEquals("local-id", preview.after.id) + assertEquals(SshAuthentication.KEY, preview.after.authentication) + assertFalse(preview.needsKeySelection) + val withoutKey = assertNotNull(domain.planImport(current, incoming, null) { "local-id" }.plan) + val after = domain.importProfilePreviews(withoutKey, current).single() + assertEquals(if (document == v1) SshAuthentication.PASSWORD else SshAuthentication.KEY, after.after.authentication) + assertEquals(document != v1, after.needsKeySelection) + } + for (field in listOf("keys", "hostKeys", "rejectedHostKeys")) { + val backup = legacy.replace("\"$field\":[]", "\"$field\":[{}]") + assertNull(domain.decodeImport(backup.encodeToByteArray()).imported) + } + assertNull(domain.decodeImport(legacy.replace("\"keyRef\":null", "\"keyRef\":\"key-a\"").encodeToByteArray()).imported) + val passwordImport = assertNotNull(domain.decodeImport(v2.replace("\"KEY\"", "\"PASSWORD\"").encodeToByteArray()).imported) + val passwordPlan = assertNotNull(domain.planImport(current, passwordImport, "key-a") { "local-id" }.plan) + val passwordPreview = domain.importProfilePreviews(passwordPlan, current).single() + assertEquals(SshAuthentication.PASSWORD, passwordPreview.after.authentication) + assertNull(passwordPreview.after.keyRef) + } + + @Test fun keySelectionDependsOnAuthenticationAndLiveKeyMetadata() { + val keyProfile = profile().copy(authentication = SshAuthentication.KEY) + val withOtherKey = SshData(keys = listOf(SshKeyInfo("key-b", "Other", "public"))) + assertTrue(domain.needsKeySelection(keyProfile, withOtherKey)) + assertTrue(domain.needsKeySelection(keyProfile.copy(keyRef = "deleted-key"), withOtherKey)) + assertFalse(domain.needsKeySelection(keyProfile.copy(keyRef = "key-b"), withOtherKey)) + assertFalse(domain.needsKeySelection(profile(), withOtherKey)) + } + + private class MemorySecrets : IosSecretBackend { + private val items = mutableMapOf() + var failure: SshFailure? = null + override fun store(id: String, bytes: ByteArray): SshFailure? { + if (failure == null) items[id] = bytes.copyOf() + return failure + } + override fun read(id: String): IosSecretReadResult = IosSecretReadResult(items[id]?.copyOf(), failure) + override fun remove(id: String): SshFailure? { + if (failure == null) items.remove(id) + return failure + } + } +} diff --git a/tools/public_export.manifest b/tools/public_export.manifest index 832a940..ce4cd4b 100644 --- a/tools/public_export.manifest +++ b/tools/public_export.manifest @@ -4,6 +4,7 @@ exclude prace/ exclude prompty/ file .gitattributes .gitattributes file .github/workflows/ci.yml .github/workflows/ci.yml +file .github/workflows/ios.yml .github/workflows/ios.yml file .github/workflows/publish.yml .github/workflows/publish.yml file .github/workflows/release.yml .github/workflows/release.yml file .gitignore .gitignore @@ -17,6 +18,9 @@ file androidApp/src/androidTest/AndroidManifest.xml androidApp/src/androidTest/A file androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitInstrumentation.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitInstrumentation.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitTestApplication.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitTestApplication.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiFreshnessEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiFreshnessEvidence.kt file androidApp/src/dev/res/drawable/ic_launcher_background.xml androidApp/src/dev/res/drawable/ic_launcher_background.xml file androidApp/src/dev/res/values/strings.xml androidApp/src/dev/res/values/strings.xml @@ -174,6 +178,8 @@ file androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedStoreTest.kt androidApp file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshAttemptGateTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshAttemptGateTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshConnectionOutcomeTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshConnectionOutcomeTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshCryptoTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshCryptoTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshRevisionTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshRevisionTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/TerminalInputPrivacyTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/TerminalInputPrivacyTest.kt @@ -232,6 +238,41 @@ file gradle/wrapper/gradle-wrapper.jar gradle/wrapper/gradle-wrapper.jar file gradle/wrapper/gradle-wrapper.properties gradle/wrapper/gradle-wrapper.properties file gradlew gradlew file gradlew.bat gradlew.bat +file iosApp/NetKit.xcodeproj/project.pbxproj iosApp/NetKit.xcodeproj/project.pbxproj +file iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +file iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme +file iosApp/NetKit/IcmpPing.swift iosApp/NetKit/IcmpPing.swift +file iosApp/NetKit/Info.plist iosApp/NetKit/Info.plist +file iosApp/NetKit/KeychainSecrets.swift iosApp/NetKit/KeychainSecrets.swift +file iosApp/NetKit/LanView.swift iosApp/NetKit/LanView.swift +file iosApp/NetKit/Localizable.xcstrings iosApp/NetKit/Localizable.xcstrings +file iosApp/NetKit/NetKitApp.swift iosApp/NetKit/NetKitApp.swift +file iosApp/NetKit/OpenSourceLicenses.txt iosApp/NetKit/OpenSourceLicenses.txt +file iosApp/NetKit/PortScan.swift iosApp/NetKit/PortScan.swift +file iosApp/NetKit/PrivacyInfo.xcprivacy iosApp/NetKit/PrivacyInfo.xcprivacy +file iosApp/NetKit/SpeedView.swift iosApp/NetKit/SpeedView.swift +file iosApp/NetKit/SshHostKeyValidator.swift iosApp/NetKit/SshHostKeyValidator.swift +file iosApp/NetKit/SshKeyboard.swift iosApp/NetKit/SshKeyboard.swift +file iosApp/NetKit/SshMetadataStore.swift iosApp/NetKit/SshMetadataStore.swift +file iosApp/NetKit/SshTerminalRows.swift iosApp/NetKit/SshTerminalRows.swift +file iosApp/NetKit/SshTransport.swift iosApp/NetKit/SshTransport.swift +file iosApp/NetKit/SshView.swift iosApp/NetKit/SshView.swift +file iosApp/NetKit/SshViewModel.swift iosApp/NetKit/SshViewModel.swift +file iosApp/NetKit/WifiView.swift iosApp/NetKit/WifiView.swift +file iosApp/NetKit/WolPersistence.swift iosApp/NetKit/WolPersistence.swift +file iosApp/NetKit/WolPlatform.swift iosApp/NetKit/WolPlatform.swift +file iosApp/NetKit/WolView.swift iosApp/NetKit/WolView.swift +file iosApp/NetKit/cs.lproj/InfoPlist.strings iosApp/NetKit/cs.lproj/InfoPlist.strings +file iosApp/NetKit/en.lproj/InfoPlist.strings iosApp/NetKit/en.lproj/InfoPlist.strings +file iosApp/NetKitTests/KeychainSecretsTests.swift iosApp/NetKitTests/KeychainSecretsTests.swift +file iosApp/NetKitTests/LanTests.swift iosApp/NetKitTests/LanTests.swift +file iosApp/NetKitTests/LocalSshServer.swift iosApp/NetKitTests/LocalSshServer.swift +file iosApp/NetKitTests/NetKitTests.swift iosApp/NetKitTests/NetKitTests.swift +file iosApp/NetKitTests/SpeedTests.swift iosApp/NetKitTests/SpeedTests.swift +file iosApp/NetKitTests/SshIntegrationTests.swift iosApp/NetKitTests/SshIntegrationTests.swift +file iosApp/NetKitTests/SshMetadataStoreTests.swift iosApp/NetKitTests/SshMetadataStoreTests.swift +file iosApp/NetKitTests/SshTerminalTests.swift iosApp/NetKitTests/SshTerminalTests.swift +file iosApp/NetKitUITests/NetKitUITests.swift iosApp/NetKitUITests/NetKitUITests.swift file settings.gradle.kts settings.gradle.kts file shared/build.gradle.kts shared/build.gradle.kts file shared/src/commonMain/kotlin/cz/netkit/shared/NetKit.kt shared/src/commonMain/kotlin/cz/netkit/shared/NetKit.kt @@ -265,6 +306,7 @@ file shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedScale.kt shared/sr file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/PromptReplyGate.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/PromptReplyGate.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshPromptPolicy.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshPromptPolicy.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt @@ -315,7 +357,9 @@ file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedProtocolTest.kt sh file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedScaleTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedScaleTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/PromptReplyGateTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/PromptReplyGateTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPromptPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPromptPolicyTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalBufferTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalBufferTest.kt @@ -341,6 +385,18 @@ file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolDomainTest.kt shared/s file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolImportLimitsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolImportLimitsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolInteractionRevisionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolInteractionRevisionTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolRevisionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolRevisionTest.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt +file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt +file shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt +file shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt +file shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt +file shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt file tools/check_contrast.py tools/check_contrast.py file tools/check_release_version.sh tools/check_release_version.sh file tools/m1_provision.py tools/m1_provision.py diff --git a/tools/public_export.reviewed.tsv b/tools/public_export.reviewed.tsv index 846ba17..aa06acb 100644 --- a/tools/public_export.reviewed.tsv +++ b/tools/public_export.reviewed.tsv @@ -1,23 +1,27 @@ -# Reviewed 2026-10-28 (F2), refreshed 2026-10-31 (F3–F7, independent subagent review): path, SHA256 of entire file, classification. +# Reviewed 2026-10-28 (F2), refreshed 2026-10-31 (F3–F7, independent subagent review): path, SHA256 of entire file, classification.; refreshed 2026-11-01 (1.0.1: SSH profiles v2 and iOS, two independent subagent reviews); 2026-11-01 iOS zadání 30 (independent subagent review + Claude review of R1 diff) # Changes require manual review, including context. Do not auto-refresh. .gitattributes ae58971fd773ee1c787aabb95003ac562a6e70406754341dc00e8bc0469cb661 code .github/workflows/ci.yml bea84d1b09d4a29d21332db81764fedd98f23dc9641b36c8eff8bb98dd29c01f code +.github/workflows/ios.yml e9ce3273927a55d598654467d4bb4fe0b17cc7a65430a263449529f113c96d28 code .github/workflows/publish.yml 8c90ff245bee1ce515b2d41b2e55e48d5b6fab78efa9a3a5f13fe874fe0a3978 code .github/workflows/release.yml 0aa2b4920cc39cb7041060a3dfcb9d3c7e8ab559087c81af57dab0bf1d598995 code .gitignore 415584539eaeda8c23d5848ca8099dcb063f933532ba818643e6f31f9f7da4a8 code -CHANGELOG.md 3c3759426791be4ea7641d4fbe3df78ea64d6f23911c24c425a2703369e3d933 documentation +CHANGELOG.md 8164eea01731d0ec17b0218f8b03c82b8e9d3008a239de57e3b87e547eddde8c documentation CLAUDE.md ccf16e55ed4f4d65a7c1e85fea270246deee8aaae518078320f50d5473340014 documentation LICENSE cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 upstream-license NOTICE 17798ca2c5510ef00d06bb7ef50b8446aefae2e436d501f77c7042114f36bce6 documentation README.cs.md 7a5434d07b140428856f950e19fcac78ff594d8190eae34dcb1a1b60340ca338 documentation README.md 0c871bae56f61f25d15b7b6a268cc93fe46c68be9015dfef74fd7b73478b64ce documentation SECURITY.md fbc26445e76ab9911f4455b19a27b1f1dd20519fcee28904d6417038671d06a2 documentation -androidApp/build.gradle.kts a0d4b96058348dc628c1a41ff7877de4489586e003a34b98791e5077ec144b5a code +androidApp/build.gradle.kts 508fe22728155b7c6020895a8dda161e1fa3e5242a3b369d75106f6556aea398 code androidApp/proguard-rules.pro aded657fad6038d476d8fe0de5c1496356c20da7c9dd18bad9edac81c9cdaf40 code androidApp/src/androidTest/AndroidManifest.xml 787cbff61e052dfab11a246ab278dbfde7a22ce1ba387373f2e1206b80e18b97 code -androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt 2b3f76172d54b01e39f7469d6de95ccd5777b632e63ba2e185c8fa2d50050cf6 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt b1b56cf9fc459991f40ad20578160b51123cf8249c83fd4f5e6a4241dc9b7bed synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitInstrumentation.kt 6a33294d7ff1173bd03e589c1e5a50af3b113e877635c161a0a475ab3558b435 synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitTestApplication.kt a703c6e56b1540851d0af2b9c8b4b5f24c70db0be5a88eb77e6c0084c7da94eb synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt 25a8ca2a8c1b95bdd6e0590f438e2d4a03185fbd8fc0f1b87a2b9d48c8015120 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt 4b8bcec89e1221d1fdadcb98efbbc19f3eb47dcc94078fdc54f330c1185c0965 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt 6d7b4cb96678b2b28712e6c45acc774244b718a3a66233c796683aedbc70d30e synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiFreshnessEvidence.kt 64fccb274984a4a2663afa7fe390bfdd7fcf4f6fa111f5e0eb328fd8c76b7372 synthetic androidApp/src/dev/res/drawable/ic_launcher_background.xml 625231d3902f22287e65d8e2f5423e18a6239e6e120e556042d66bff56c3249f code androidApp/src/dev/res/values/strings.xml 108a1b751c7b8705111ce5c13135c3e4e4a82681212d47a766835a58b90ff995 code @@ -67,20 +71,20 @@ androidApp/src/main/kotlin/cz/netkit/app/ssh/SshConnectionOutcome.kt b4ac003e783 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshDns.kt 2f740a884282940bdbf6b46c704a66c99348520c4bea6b50174cc7c55e8f760b code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshFailureClassifier.kt cc2cacaef4999894bd07547b07471fae7a25bcefa2864fe2fcdede0f59549289 code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshKeys.kt 4708e7b0b29e970ceab3eec0b99993cd4275ce539f687bbc98b66b39bfc038ee code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt c272609f0c85c63295a350df504c1e4ce0521dde75e00368c4104e883fba8774 code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt f6fa22fa902b6ec0f8d3993cd8b11060af6428dd76ba8d036fd90f596b5c1fd7 code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt 7704cdc69472893b41936ad54067b01aa00ea250e4676ebd4ae76c8f4c8827b4 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt c289e379d5b962a9eec5e0bfc49bf6b4b2a32269fa6b59879e72329faa3607bc code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt e304b3e63498644fd89791abcf42dcf427888c9a94c4a37e78b032bfe431acba code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt 9b85c922421917cb72d441d37902ccd33f2187f1d4d727fb884a1f588480faee code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt 3113ee6eb54b2049718cbb79368fd157b3c6205bb486e5ebf9e3e217891a4931 code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt a8260b4f9c9a7bd375ecbd220be35c09cb14941a6e03bf155f7b76fa6576c8e0 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt e719dfabd4c2a61e9741f71cb5af1921c4b494560101c930a55d4aad3fa3c9b0 code androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt ae5d061ff3d90a248642c677cd5d9f2ad32810127f00ed58e0970325bdad50cb code androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt e4aeb04474ab6b8ff42773c2eb9b177fece3c45e2d3ed06f1e6ac506b9a46857 code -androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt 9f4c50df7aad74dba396a792c43ca571dc82fcf4f0632e14e712b1e8d80b7a61 code +androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt fdc465b382ff6b6b4f3772008bea23ec5dc11c856404d268a4f5d35aecb655a0 code androidApp/src/main/kotlin/cz/netkit/app/ui/about/OssLicenses.kt 3659275d66fe1311fd82bafb4fb37be5d0056609a7dbb727ecea5bdd5cbb02ea code androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt 0dc50ed01294e7b942bba2159d69a919d9cde96b7ebc6d6470b1375a4d9b8326 code androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt 3c7aff1ce2c7785e3d87aa5631b1ba033c89535d8556576de6d8c79b2f6986dd code androidApp/src/main/kotlin/cz/netkit/app/ui/motion/Motion.kt 9d4fc200415ea03a0a486e2405a6ee93550835ea3079cfb586d8a6d52629475e code androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt 7d389067b5e70b91334669524904a72dfd572b490267f51a4cd7862211780595 code -androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt 0296bca8164a7f3ed7ab53a6275cad5da6772b51df1bab8dfe5fce1caa0d7a38 code +androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt f3478a034d16c4d22ed6d3f854d2f0547b8862a0cea7b7a32d1047d5d6e62d47 code androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt e81f670ccbff001da2df73251e591039d9937316e62a909e8dae3268711d0c78 code androidApp/src/main/kotlin/cz/netkit/app/update/UpdateViewModel.kt 74d222024a650b858b5d40ec341c9b409a1e76a4d0094c63b7a26b06eafeb691 code androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt e8b4bb619d04caa1f9e3c7e600e6e4873ebb8c255989c1cb47971a82cd3d74c4 code @@ -118,8 +122,8 @@ androidApp/src/main/res/values-en/net.xml c588dc9197b23ee9c7f960878a8a3705f7e3b4 androidApp/src/main/res/values-en/overview.xml 4ea9c29beaef958ff433f6f95a7dc4082a18694d8d4d0b780db1eec684a178b2 code androidApp/src/main/res/values-en/speedtest.xml 7814880fc8464e34764bc871ba0cb1b71ae99bbb06f0b131278884c1f2318e1c code androidApp/src/main/res/values-en/ssh_closure.xml 46589351e503111477035baca6bc19beb9c8bd910b0ce743dc68871e8a9170bd code -androidApp/src/main/res/values-en/ssh_design.xml cfe05995be7747ade35ff44e9b06550bfcbc00184da4e72017596d6a121601bb code -androidApp/src/main/res/values-en/ssh_import.xml 808c2cc97f28e54795a08a847412e3cf0400012560ea2f2e916b1addadcc25f2 code +androidApp/src/main/res/values-en/ssh_design.xml ff098c275a1c9b001119c3b16ffd36773fb06aa0715920201a6f48af525799ba code +androidApp/src/main/res/values-en/ssh_import.xml c3bec543dc25ad8bb5a92b5ccc7f8c4de1a92dfa8693f6cb00bea4398cad14ad code androidApp/src/main/res/values-en/ssh_revision.xml d35234edae2c0af87cfca9c00ba9fe086bb722e44c602a018cd714bb98f3457c code androidApp/src/main/res/values-en/strings.xml e33774b1024ea91e4ae736aaf57301f8103884d09552b9db9e8fc888a6282888 code androidApp/src/main/res/values-en/strings_lan.xml a1e698e3bf65f3001bd6171bab7765bf0f65aff2aa04623d04408c577ed2df38 code @@ -145,8 +149,8 @@ androidApp/src/main/res/values/net.xml 4b8755bc602231170660c60b14d52550a1a1957a0 androidApp/src/main/res/values/overview.xml 05265575c592ad0012237a1286dd90a170ae1cd27cb9e526081880b750835a82 code androidApp/src/main/res/values/speedtest.xml 366bc645c1adb6a89f40c51f50fd17a57668e00a66bdaab88fb49187a7ac94e0 code androidApp/src/main/res/values/ssh_closure.xml 8576c9776d5841b5a69a89116492a72604f94167eb3cbefc255b394a3a55568e code -androidApp/src/main/res/values/ssh_design.xml 5b74eb9eb39f0fce90130ad19b82381164643f4fbdfec24639ba05e0455f6749 code -androidApp/src/main/res/values/ssh_import.xml 17808365c58d0139b9d7a9a250848e0f144561cda2b416576bb6be73587b22d9 code +androidApp/src/main/res/values/ssh_design.xml 8d191f319dab350b724ea53b6c65c9f71df465cc98f7dcd3d23a2dfb2842f971 code +androidApp/src/main/res/values/ssh_import.xml 7545ab6621a7330a495f5ca922bafd31646d59978adec29151056eaf4b62459e code androidApp/src/main/res/values/ssh_revision.xml bd4010b02ae6638e40e4d708d09252a77a5907e48086e34abb43e68c36fcdba6 code androidApp/src/main/res/values/strings.xml b1a29a6d5f32fb06502e8651e1180fe6777ff0cdff6a5a1f87d995ac70529b9f code androidApp/src/main/res/values/strings_lan.xml 3b9a60c77ff521544df36b7e5e9928e07fdec129551508f88184760b950db9d6 code @@ -175,7 +179,9 @@ androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedStoreTest.kt 311fb5f625c6152 androidApp/src/test/kotlin/cz/netkit/app/ssh/SshAttemptGateTest.kt f3b51d9cbfce0187a33e624bc941848be36e028969c88260ae050bd639a9eefa synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshConnectionOutcomeTest.kt ae04876b01fcd431e54c09d93e9644ba7361ed52461b0916ebf23699a2063dc2 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshCryptoTest.kt e1a8ad51003f24b71579e5f08bf4bbd209b4e81de6bf26b797a84e3bf85be705 synthetic -androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt 686e5a7cc01922edefa60b280475b2eaf5672968c281a8303213d08b080ad6cf synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt dad2836d6d67db7b527767e2e62d1e352a47da5a17e50d4d258c03bdeb8eab8f synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt 625dae8f0277eb9d5e52bff421a05f588ac4a2f2b24a3b96e293c730d960842b synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt ae5160583988053536095774eee5bd1159eb0c40c8f6ba75934514eecd1c5cea synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshRevisionTest.kt 4c5366206da2014f418b2b63fc599068167b0d88bb13ecacbff26e6dcdd80f1c synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/TerminalInputPrivacyTest.kt 514828ed0da09233e384e3a23bf6f956c63dafcc47fce33ac8af20a7c3368806 synthetic androidApp/src/test/kotlin/cz/netkit/app/ui/DesignSystemTest.kt 42305f6d6a44eee4b1bb8a2976ddc11d5bbd8c20e9285f4a2276c3e70e916fcb synthetic @@ -189,24 +195,24 @@ androidApp/src/test/kotlin/cz/netkit/app/wol/DeviceSerializerTest.kt bba5b5768ac androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt 46c781a24c05ddc689009955463a53c0fc8b6b517ef7ae791030c7c45545da88 synthetic androidApp/src/test/kotlin/cz/netkit/app/wol/WolNameOrderTest.kt 5d0cbfa6178c7a01bda35c1a561c79dd024e44233cfa4b812c8af2d5cd2db744 synthetic build.gradle.kts 0e2fd81ef9cf014e2988cd1e4dd2c67b00a2e4beacf16cb7ed7b34f6fcc7fef5 code -docs/architektura.md 640880b6969c8b9f8a1764a0be3f87a5ab3448113d3bcfa1fd47caf40d7452a4 documentation -docs/bezpecnost.md d5ed910e94eb2b0646d6fd4264ededc07be6d05f32b4f7ef4cd090c2a0c82034 documentation +docs/architektura.md 601f8ec3ad274e3f6c095e824ac30375c29850a6783cab492ccd8c93e975988e documentation +docs/bezpecnost.md d576373ed26e1234bbe118128a458cb14573be7cb1d5450c6450f315eabce3ca documentation docs/design.md 965b87cbb0e0c5cbf5a7e61a0f5454b380552d33b7a9f869b29f3abf23ab37d1 documentation docs/design/prototyp-m3.html 53ae34b8f99784538c36ef7d006c4e8fc1bf23d9cc79d0718854b90d233a4bab documentation docs/distribuce.md 863b6196cdf06e3b0cfef00f68e59ef94ffcf52f54036d4811a3a189d80fbed4 documentation docs/funkce/lan-scanner.md d73d8e116566765e0176af3a94a7c9b26cc5aa9fc906784a832f243b4265e5fe documentation docs/funkce/mobilni-sit.md 9df9884c1d05a8b89faef5316d7d94269283557047ed640678ab67175e40a809 documentation docs/funkce/speedtest.md 3dc20538d6a023a38a4d347c52bff9ec3131ce8e93b2038068818796c468d280 documentation -docs/funkce/ssh.md d650d0bfa7f6717ea03dcdd6c75d8246ef72664ea96d82fe28f1b44b4569e37a documentation +docs/funkce/ssh.md 5f9a0e18eee073cae5cc49701204ed962bf0c3741fa255a8bd826955854f19aa documentation docs/funkce/wifi-analyzer.md 7784d3afd1c057788a9c7f77f4337e726fe1f65a4f7886f8047ce01575c33948 documentation docs/funkce/wol.md 6c2d407cd573a7f6922869fea9800ce06db44aa4bd1d19e5c1f146a0f084a0b0 documentation -docs/ios.md e0e57bdaf8d4bc0d6028895c4516763133bdfd91f8189415597cbc433f2cb5f4 documentation +docs/ios.md a63181ad0fcd3d32840ddd3ead028432aca16b494d3e79d766b98f2507c927be documentation docs/licenses/bouncycastle-LICENSE.html 6b0a6f8310ad417bdd06d9daaa228cee385d828301e96fda411f7732479651e4 upstream-license docs/licenses/jsch-META-INF_LICENSE.JZlib.txt 9aa93e9bc58ae423a9e6476f608ee8f46063f5679e3bac0bc55f2f4b10d243ee upstream-license docs/licenses/jsch-META-INF_LICENSE.jBCrypt.txt a85927641ed1c8b95a5cef79b127b2392d80e0aa9d8e2d6f3b7b7401c5396af9 upstream-license docs/licenses/jsch-META-INF_LICENSE.txt 9c3537ab0b485b391b887b95fdff761de3dd3273a6931e8a1942dde4d2093cc5 upstream-license docs/licenses/slf4j-api-META-INF_LICENSE.txt 4e7f90c86ab51278228bce153122f1d8df30149d13ce9ef524c8444a84c32dcc upstream-license -docs/plan.md a11fa13f819ea700bc743cf8a48eed99e6140f0ec6dc57bb5caf288b93c64235 documentation +docs/plan.md 4d5cab47f506598f3ef95ea1f16543082ffcedb925d217da94b6a6a6f8c2448c documentation docs/project-license-inventory.tsv 617dc4873a169f681bf2fe315504ff79339fdf9634fe7d8b2439e6716a1188e7 documentation docs/public-export.md 6b18cef46625c3194dcdb687f3932b3191512e149dc6f0500859d0f711b08529 documentation docs/public-license-verification.tsv e0f9a1569831680508edff3956d7d3546015a262c88bca6c5b0dcbe1939fe69d documentation @@ -224,18 +230,53 @@ docs/public/privacy-cs.md 4a7a4230ce294e5de417a5e87f844b55dfc58a2f555b4cdeadac96 docs/public/privacy-en.md 1f1e2130da9078737e23b5ddb48414bffecf9c286bf339b1fa743be38e5e11bb documentation docs/publikace-play.md 16fbba5b0ba587b156b79d9505c76ba5ee504d9f5565163937dddda9368b0cdf documentation docs/revize.md cbfc8342f5dd1902e7e48f78d1d8e2d4f5b8d59d3561b113ffb842d0152fc07d documentation -docs/testovani.md 4a5a23ded9805aa41907c4acdc68a306b666889b3542fd87348b2bfe29835e1c documentation +docs/testovani.md b9ef2f0d79ae4683116835e238b5c3d32794063239376119041f3445cc7f20f6 documentation docs/toolchain.md e2cb54e1d27f0458f0ec95d827a2639ac34f205fdc7321acae7e2451ba508a6f documentation -docs/zavislosti.md 8a602c3655df97d94b294b4dfcceacedd540a8568fc7ca3797760d0e1eff33b0 documentation +docs/zavislosti.md 63b678f41050f053da7f03d69db307af9cccb1e6cd7d52f0036bf495dd5caf8d documentation gradle.properties 3b0360faee84b00fee599a4c9f51bff401e62eeef157369a68c3be16f04df764 code gradle/libs.versions.toml 494d6fcf3ece113c7b68141b9c6f5c6a837ff15f6dfac4ab51c3ee18c1858919 code -gradle/verification-metadata.xml 40f33b6683828b14fc2d641550bf0ac5e8db186dd8085320c0f96345f13fd96a code +gradle/verification-metadata.xml 086407449512aa3998a3cbc87dffbfc9288e8cdc9656c89305cdc18f1556586f code gradle/wrapper/gradle-wrapper.jar 2db75c40782f5e8ba1fc278a5574bab070adccb2d21ca5a6e5ed840888448046 binary gradle/wrapper/gradle-wrapper.properties fe90ff0d9944879f591a8c37b6dbaf5046d1051ccbb6b26b22081692c321f432 code gradlew a3648413b47ef77af21d5ebc36c687c7d103aaef3e17f33de7d4f080a6f300a3 code gradlew.bat 57931b17dd228e5c24dac90e815d0bf82477e831a4618dfab4136f5446b42a9f code +iosApp/NetKit.xcodeproj/project.pbxproj d4fef8aa0803ebab2d4b937d03c4c82709b0f8fa6e18115ab68eba144c44db55 code +iosApp/NetKit.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved 987d586471990043d55908b00b8b8be954171e1986377aa689e2b94bfca85055 code +iosApp/NetKit.xcodeproj/xcshareddata/xcschemes/NetKit.xcscheme 93a6f56f7e23be3b85410202fc8ff1a3e6779d723fdf26076f709d9ac2ac2a8b code +iosApp/NetKit/IcmpPing.swift cdb1173d693fc85470970c66283b9d56cbe77c1ae928ad6799a766608565d0bd code +iosApp/NetKit/Info.plist e107de3c536e8c5e00b1e300413d12e15ab0a898bbb54697f19e0b73fc5dd275 code +iosApp/NetKit/KeychainSecrets.swift 4d0ebc9c6153180df98cb293a0f315daa63adcd751e9aee29bb427faae9080f6 code +iosApp/NetKit/LanView.swift e01d1f308c155066dd065612477135eaa08db28d91339bb19dd10ea03a2248c0 code +iosApp/NetKit/Localizable.xcstrings 23665b87f6c62c2a142afec4ab7f7680fe9bfc8dc0186e6f586a67d09dadff1a code +iosApp/NetKit/NetKitApp.swift e0691df04bb2d2fab73d1c8844dd68b0e33bea5c908ee6acd29d0cdfd3004796 code +iosApp/NetKit/OpenSourceLicenses.txt 997dff8804ae121858c90f5b2323ccf2574b52bcac58ce4d0c5219a6427db1d7 upstream-license +iosApp/NetKit/PortScan.swift fd1d185560d26ba41a62fd6375bbce637c05c9d3ae78de7642ae3007e2821c91 code +iosApp/NetKit/PrivacyInfo.xcprivacy fe3d88cc003bb85f70c517010312e70ed1549c6e2505b00e8add05595c0d1adc code +iosApp/NetKit/SpeedView.swift eaf451e1a2d21f6e83fc4e22ab9a6b5c85bbe006d47d7bf1c46ffaa77ff95696 code +iosApp/NetKit/SshHostKeyValidator.swift 137e9a4e020b4b0973c308d42ed7d684b57d2fc4b5f037cd38d93adf41359e80 code +iosApp/NetKit/SshKeyboard.swift 7bd4098b93134616c1e2931dd7f27414647c91d167a7653f673d677bfcb7ad14 code +iosApp/NetKit/SshMetadataStore.swift f8ec6641542750d6b2134bb64be261bfa974061855fd1126bdbe681774bdc11f code +iosApp/NetKit/SshTerminalRows.swift 2031388ce728601a119c4a8020681ccdd1836d0aae4e0b58aceeb90ddd2c7262 code +iosApp/NetKit/SshTransport.swift 9755b456a8097a631866f3041340beea5ef2e6997fa9a7e0e98999f7e184f702 code +iosApp/NetKit/SshView.swift a8a19bcc94e2235a1cafa2e26ad532d06af01bcac269f0428eee1122919cfd9c code +iosApp/NetKit/SshViewModel.swift c368e1d1444239baafd33ff35c66b7d3e737f06430b8620fc084750242cc6926 code +iosApp/NetKit/WifiView.swift 5ddeaff07586bd54880a4cc5b37f0b07d0f755ccdf1f99b7b7602c4a80318cd2 code +iosApp/NetKit/WolPersistence.swift 2adcb02b69b918d5d04b472bdaaff4d3c38bc66de43f345411f0ac2fadaf77f1 code +iosApp/NetKit/WolPlatform.swift 809eca7110d6002a1273ae780af48d83ec0d8499e669c043ee0a5d0ffd56bfa9 code +iosApp/NetKit/WolView.swift 531ec2bbb48496bd58ebd7e5d06e4488917c1a1c516c95e8c6eea83cb57cac3c code +iosApp/NetKit/cs.lproj/InfoPlist.strings b2f610ef5ac9a70d0e02ef20f01479254d64d972c5ac298681333ca05d1daddc code +iosApp/NetKit/en.lproj/InfoPlist.strings b281a360feac92533c46ce454ad894a1e07ebc6fad96cd742a19a2a808858128 code +iosApp/NetKitTests/KeychainSecretsTests.swift e39948d97c6c1490a9311411a1ca053c3d95c225a255a3091b3d81d65000435d synthetic +iosApp/NetKitTests/LanTests.swift 7c2c8e49a25d158807c81ba236d44cd04bd6eeaf459399790e8ca16f6279076f synthetic +iosApp/NetKitTests/LocalSshServer.swift fdccb9da53ae0e6adcca5493ff3738e60bfc3e5c04a92531e23d4a0bc30c461a synthetic +iosApp/NetKitTests/NetKitTests.swift 9f10730d049ab01855b6d1f02b975a5019673d4afa73df582acf4f7f5a77f5d4 synthetic +iosApp/NetKitTests/SpeedTests.swift e8049864cea86e65d91ea60e05677947d5e90a3a801fb03250f36d1b7d5b63a8 synthetic +iosApp/NetKitTests/SshIntegrationTests.swift eafad8dbe3db4673a0f58958986fbb5393b4dbe0e208f7bcb1436f59addfc2df synthetic +iosApp/NetKitTests/SshMetadataStoreTests.swift e3706716a6dfdf19c3546961768767bbc4d0efae10dfd0d78daf3446687978a1 synthetic +iosApp/NetKitTests/SshTerminalTests.swift ff678ebca66ddaa746a49dd53b1873ad0b80e2aa513bdacbf01552905f195e75 synthetic +iosApp/NetKitUITests/NetKitUITests.swift ad833026b034e1674b773ef168be250f28d5dd53497ddb6d9f15491e1ed447b5 synthetic settings.gradle.kts cfc6539e9e50b14277775f45a5fe0f942d6490665ebdd651a2902b24d618190c code -shared/build.gradle.kts 582f4abe593eab9e9ed749fadee62c46474dfce43b14d805972979c91bf99db0 code +shared/build.gradle.kts 0b971204b006ff95eeb65e432a3d0a913e917c7272b679013c7c327e30c57355 code shared/src/commonMain/kotlin/cz/netkit/shared/NetKit.kt 2ff7b63264316c333a069006f71ce23b9749e2ade6ff2ef7221cdbc86c66758f code shared/src/commonMain/kotlin/cz/netkit/shared/cellular/Cellular.kt e919aee45840d0d97cbaa9676ae2660b85b5c6d5ced4034845c1a223a35cd44c code shared/src/commonMain/kotlin/cz/netkit/shared/chart/ChartViewport.kt 3d10556a45a287f3dcc47986d1b8706e5eea27240cf6b65e7eb11c4a9241ad8d code @@ -247,7 +288,7 @@ shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt dfccd97333467d31f9 shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt 1dcc8a6b21dec83c9db0070b75b4a8917a6d87c01930daac7a0a2a5567070cec code shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt 0a97b9db3f4b876d7d8ba27e943f6121e857f145c575589b23fc491d96fe3e91 code shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanExportLimits.kt d540f2964d6b54b9e63a8822041ebb79202ee07668d1744512bb1d42be08d14e code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt 1424c79eaac688a15d1b780bc7dd9c6f03a41ef8fb2fd3523369b1a100b2e994 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt c61a56aed653decaa99307c0a3efe8091b512e21775c395118d347cf1df57bcb code shared/src/commonMain/kotlin/cz/netkit/shared/lan/MdnsIdentity.kt 5a7c67608ccdf6269be5c84cddf323ca7a876503b057d0a49b86806fb78295e2 code shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt 5be4b02c983039159c13b01a35f479b8853bc4077d129ab0849d2e12822e4367 code shared/src/commonMain/kotlin/cz/netkit/shared/lan/PinnedProbe.kt 4d9411d687ca4d166a09d992754630703ab1b90bccca89eb6dee6fdad8a33ca0 code @@ -266,15 +307,16 @@ shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedMeasure.kt 8ccccdf0d157 shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedScale.kt a979719b322f65c27fe84018822a05d8511a3a1c2252e91f457ecb61dc4a126f code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/PromptReplyGate.kt 2cb4562e34737dacd18921e22992d65f5c05e277a66f4fe2872db24abc18aed4 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt 3f1077e82016e8b20feeb42ad6268b27f71d26bf0a6e1c7bb053c40143c06e4c code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt 94423e500ee9be50970deaa2f93fa6bd88c5b22c50e5711a6aadbdbd2509798d code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt 926b8ff9e78d581b1a23096ae125964458fcdd760086b389213e4da4da9cf96a code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt 56ece94b3cf579bb938dc8c93851fccedc34763b22cb839e9979bd669618b4db code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt dd296082a66b03154d8e70103df871f8d6ad5376d34448472febf9a8fad7f204 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt 722b618207641e4ca183a577b6accb0d88cda31d48259b17ccd6c4b120435036 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshPromptPolicy.kt df67c645fe0443a4fe824e971678438105efbb947f329e61a24f3e46693fee1b code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt 4a9b527efa3aa637fbd16d5c0f8a06543fb38661bcbda52f8dd4c47fa20ce1ba code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalComposition.kt 4a339f543e52e2c9a22df1080cbcb19c4db85b71eac42c96ff220d43ca8c4bf4 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt f6b8fa1029897b347c401d22bf19b7b895cf06a6a8f795a3c0192abe4b139418 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffers.kt 3150baea5e92369386f8dc9bd7989d2990817dbe4c86a100f0243d251f51f0ae code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWritePump.kt 60a86e222f696a297460e9d007c41ef5643f45bc0f3087eae96c5ec5a2f575ef code -shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt 5210b89042921be1a401653a4454f681d04f7848c92d350ff91c2bdc92793c0f code +shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt 12a820c8ea007be1d4d3d744b522fc787d66bd25945bf2acef5375aeb30dbe30 code shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt 4cf17717441451a3f377119c2ff98b9a400a8420795247324ec70cda70999c12 code shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateInfo.kt 029551c8a2ca23c584419aef45f8feae838519c30d138c8f064bddc04f6bba89 code shared/src/commonMain/kotlin/cz/netkit/shared/wifi/BssLoad.kt e522fb7e793b226bea7aa3f2d3ef2b934b22ef0de2e54e19bc3fdeefec1bf453 code @@ -317,15 +359,17 @@ shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedProtocolTest.kt 6caefd8 shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedScaleTest.kt 1cb9081ceeebf56bd3b811a89b26ffb7b2a5a60f64cb8ab6d891d512f4db90cc synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/PromptReplyGateTest.kt 8f3c1230f694551744135df776c165f2a0591cd535f3d3b233e04535a9383c3b synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt 025b1e4d50600d53da9ddd3611145737e33093d5ae406961572908587d7050de synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt aa8552006c9c570ff7814c89f591f74817a35a68926c873ba8bd99b74e007f33 synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt 316c8e1c5d08e787a68b0e29cafad3ce3086d9ff5784f8061f727b78cb6c3f6b synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt ee1ce06de8b74e381d7cce7816e4696e8987ce533d357639df13f0afe2077ac5 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt 0425d82c1ef252cb141348691ec1a75fe66fb2da15566f7a7058ab65f7f5bcd0 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt 5eb383f1b81e116e9c002f3e839525e9821a784a4389eab8c3990ab6b6ed288e synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt 72bdb590d923baf362c03ec2b0b0f7bfa685a288d3fbbaf0890b008577f9ce75 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPromptPolicyTest.kt 8345a4988474ac901a1773ec6f5da3540aea33a971d2caf2593efeb3b3368347 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalBufferTest.kt 6248b4c2d185617f67b34168cc21d42406d8a91c8aa523bd94e58afd90e4b10c synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalCompositionTest.kt c829e4d2b6e29868b639e61a4bd303ed44f1ae9b1c3e71960f3f9ea23d99d13e synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt 1b2b9fc8fcc1bb5f71a795151d42b00d820239fd8e1b3a4cab5a07199aaf5a3a synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffersTest.kt 14e3455ce083a49ca38d0d8ea688f8c138a567d55f25dd179ccdefa04fcf3ef1 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalWritePumpTest.kt 7e81dafea64a33a2085ab642804ea25f2cfd7954d3b47432b8bd334de51db52d synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt d88026637f5026a8851481607784b21f096c3b8612612ef3c29f327630c7b941 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt 88171bd46016b523da43903079da19992127d112eec03318fcdda50127185d76 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateFetchTest.kt d59d2cf411c6e83f25a69a10e103493db7006978c5e22a11ac36b73e8848b4ce synthetic shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateInfoTest.kt cb228f029b1be648fb9029f479c05db96ee0e3460833dfd69b736d5ec1cf7f33 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveChartTimelineTest.kt 7d3393757e79c7e01dc8a2dcfdacf7fdbbb4acc4daec2490894bc02a02728723 synthetic @@ -343,12 +387,24 @@ shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolDomainTest.kt aac8696c71220 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolImportLimitsTest.kt b081118130fb4ae3b13dabd2c2c27a9b7014863d52b35117d35466e50c04dde3 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolInteractionRevisionTest.kt a0738f1f9be31eef54e28fb0d7dca5422d6888fa1745d9c9bc98062a7fe8082c synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolRevisionTest.kt 5815bdb1b68548050ef78acae6b968eecb9ec1a905622397c5b9f6e7d9326079 synthetic +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt d2e95a175c907ff23f448f55f8cd79964d6e815c5c714b1db556aca3d65aa11c public-service +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt 568650d0a2b67d7caf226cd307fcc1c07ca9af5b3e590c9063bc40cbc049afd6 code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt 8c0e7795b089ecd3e6662440ae19081717932cda910e05f7aff0e38b58e5e91b code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt 2e17fc1d808434dbefb1b8ce6868e0d600294e4973cb54afa6c5f5317fad1fcd code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt a667a05edc4a77c1729880c84baddce5a2272b5902c220bd8b438cc192b54f64 code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt 14086e1dada83f13a6bf96bfaf8dd130fdad286e89890986b6833db6120569fe code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt 16580456f96b515c328d21ced102df133957cdc5ebef2b78eaf0e5f1fb496871 code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt 758c6bb92e3a37ebd3755e5ab347408b284af32587bcb56da78cb2318233706a code +shared/src/iosTest/kotlin/cz/netkit/shared/IosAboutDomainTest.kt d28d89b1071c8d01b66f02dea11a5b395426edb3fdf37c3725d23c265566217d synthetic +shared/src/iosTest/kotlin/cz/netkit/shared/IosBridgeTest.kt 665ed6fd7af9b55ab0ad430a91c70ed336595c581f74d1b2a1a1e338722652c4 synthetic +shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt 6ab507180a14097dc88a170a1d5523e53a9b79227854b0f968b5cd5ea8a7c812 synthetic +shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt 34dab11d48483389937917fdeabd8119dd0260ded587596271ec766b201d405c synthetic tools/check_contrast.py 3f22880af40b94f990a6b74d6fe24eab68902b202edeeacb8eadf4593ee09118 code tools/check_release_version.sh 71bdd2e01f862fd123e01f14fbaa380dd5c8e45acf7f4c6627fb87c4b7bae052 code tools/m1_provision.py c116d8c87ad1dcc9995bf7260268b1f368fd58fbc60879216a13e96f8b10e9a0 code tools/make_public_export.sh da89e4e62b4fa20240c2dc436898862e89549b7a8ab41a36ac5f194512ca5fa5 code tools/netkit_ssh_export.py 2458f4be3ad566814a058781fcca327b79d3dbb9436fb5348ac35a2e7f8f7803 code -tools/public_export.manifest 3836eb7e8d596371404e02eded32feff5ef3bcb876f54ed70392688d1ffcb265 code +tools/public_export.manifest ac192bc9c7dd5e9673a034ed0fe97740f1aac83b011f116705ceaf1ac2b8184a code tools/public_export.py e2bb5273ea3b14653ac644558fad2773f154c95a318d4153b3333058c78dfa61 code tools/release_latest_json.py a09e0a0436669e6a03f8e618f52591c6e739692a0aafc4e374a7570a9992ae28 code tools/run_m1_checks.py 63ced59ea0e7da354f3b1946c7af718a710a36aa6438216c96afe3d99c2dc9d0 code @@ -368,4 +424,4 @@ tools/testsrv/m1_fixture.py ac34fb43bb068e8e4d68e837cf8fc7441d696e465e45f764371c tools/testsrv/test_m1_fixture.py 17502aa748762f8325f10c538f9af2a8e20e467066415b4d9b8eb5c95712e47b synthetic tools/testsrv/wol_listener.py 1fb954425dd31a0633d285dcd5f88ee018467f0f15e99af690aea49cc5f21b49 code tools/verify_release_assets.sh c3099f8fbbfc32c192b0fe05149c1358c6e675d02829c0bfbcca5a4f5d3aa998 code -web/netkit/README.md 1dbfa4246327baf7e450834212a8f755d07ceee18e9594f047b7d3a875267cc8 documentation +web/netkit/README.md fc882c2dd03d94699662603921fabfa6b3031042e15586bfb4b4fd740dd91e89 documentation diff --git a/web/netkit/README.md b/web/netkit/README.md index 2bce634..6534a6c 100644 --- a/web/netkit/README.md +++ b/web/netkit/README.md @@ -15,6 +15,7 @@ kopii, ze které se stránka nerenderuje, a `latest.json` se teď tvoří u rele | `/netkit` | stránka projektu (Stáhnout, ověření, instalace, soukromí) | lidé; `pageUrl` v `latest.json` | | `/netkit/privacy` | zásady ochrany soukromí, **závazné znění** (předloha oddílů 1–9 `docs/public/privacy-cs.md`) | odkaz v aplikaci (O aplikaci), obchod Play | | `/netkit/latest.json` | kopie `latest.json` z posledního release | aplikace, nejvýš 1× za 24 h | +| `/en/netkit`, `/en/netkit/privacy` | anglická stránka a informativní překlad zásad (od 2026-10-31, web je drží stabilní) | aplikace mimo češtinu (O aplikaci, tlačítko Stáhnout); `pageUrl` v `latest.json` zůstává `/netkit` | `SITE_URL` je `https://www.daniel.losak.cz` (od 2026-10-31). `/netkit` je přesně `netkitWebBase` v `gradle.properties`. Změna domény nebo cesty po vydání znamená, že starší instalace najdou aktualizace už jen přes zálohu na GitHubu (D22). Proto adresu