diff --git a/.github/workflows/pr-test.yml b/.github/workflows/pr-test.yml index 4ae237a9..4c4cd7c0 100644 --- a/.github/workflows/pr-test.yml +++ b/.github/workflows/pr-test.yml @@ -246,6 +246,84 @@ jobs: working-directory: app run: flutter test test/services/cli/ + # Decides whether the macOS-runner `ios` job is worth its ~45 minutes: a PR + # that only changes documentation (tool/ios_ci_needed.sh) skips it. The + # checkout is the PR merge commit, so HEAD^1 is the base branch tip. + changes: + runs-on: ubuntu-latest + outputs: + ios: ${{ steps.diff.outputs.ios }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 2 + + - name: Changed files + id: diff + run: | + ios=$( (git diff --name-only HEAD^1 HEAD || true) | bash tool/ios_ci_needed.sh) + echo "ios=$ios" + echo "ios=$ios" >> "$GITHUB_OUTPUT" + + # iOS: unit tests that touch Darwin paths, a simulator build, the release + # build with the bundle exclusion check (no desktop-only code or ATS opt-out + # in the .app), and a launch smoke test on a booted simulator. No signing and + # no secrets: --no-codesign. Skipped for documentation-only PRs. + ios: + needs: changes + if: needs.changes.outputs.ios == 'true' + runs-on: macos-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 + with: + channel: stable + flutter-version: ${{ env.FLUTTER_VERSION }} + + - name: Install dependencies + working-directory: app + run: flutter pub get + + - name: Test (mobile, platform, util) + working-directory: app + run: flutter test test/mobile test/platform test/util + + - name: Build for simulator + working-directory: app + run: flutter build ios --simulator --no-codesign + + - name: Build release and check the bundle + working-directory: app + run: | + flutter build ios --release --no-codesign + bash ../tool/check_ios_bundle.sh build/ios/iphoneos/Runner.app + + - name: Boot an iPhone simulator + id: sim + run: | + udid=$(xcrun simctl list devices available --json | python3 -c ' + import json, sys + rts = json.load(sys.stdin)["devices"] + def ver(k): + tail = k.rsplit("iOS-", 1)[-1] + return tuple(int(x) for x in tail.split("-") if x.isdigit()) + for k in sorted((k for k in rts if "iOS-" in k), key=ver, reverse=True): + phones = [d for d in rts[k] if d["name"].startswith("iPhone")] + if phones: + print(phones[0]["udid"]) + break + ') + [ -n "$udid" ] || { echo "no iPhone simulator available"; exit 1; } + xcrun simctl boot "$udid" + xcrun simctl bootstatus "$udid" -b + echo "udid=$udid" >> "$GITHUB_OUTPUT" + + - name: Simulator smoke test + working-directory: app + run: flutter test integration_test/ios_smoke_test.dart -d "${{ steps.sim.outputs.udid }}" + # Aggregate gate. master's branch protection requires a check literally named # "test", so that name has to survive the split — this job carries it, and it # is red unless every job above is green. `always()` matters: without it the @@ -253,16 +331,25 @@ jobs: # forever instead of failing. test: name: test - needs: [app, ui, bridge, android, cli, windows-cli] + needs: [app, ui, bridge, android, cli, windows-cli, ios, changes] if: always() runs-on: ubuntu-latest steps: - name: Check job results + env: + IOS_NEEDED: ${{ needs.changes.outputs.ios }} run: | - echo "app=${{ needs.app.result }} ui=${{ needs.ui.result }} bridge=${{ needs.bridge.result }} android=${{ needs.android.result }} cli=${{ needs.cli.result }} windows-cli=${{ needs.windows-cli.result }}" + echo "app=${{ needs.app.result }} ui=${{ needs.ui.result }} bridge=${{ needs.bridge.result }} android=${{ needs.android.result }} cli=${{ needs.cli.result }} windows-cli=${{ needs.windows-cli.result }} ios=${{ needs.ios.result }} changes=${{ needs.changes.result }}" + [ "${{ needs.changes.result }}" = "success" ] || exit 1 [ "${{ needs.app.result }}" = "success" ] || exit 1 [ "${{ needs.ui.result }}" = "success" ] || exit 1 [ "${{ needs.bridge.result }}" = "success" ] || exit 1 [ "${{ needs.android.result }}" = "success" ] || exit 1 [ "${{ needs.cli.result }}" = "success" ] || exit 1 [ "${{ needs.windows-cli.result }}" = "success" ] || exit 1 + # Skipped only when the changes job said documentation-only. + if [ "$IOS_NEEDED" = "false" ]; then + [ "${{ needs.ios.result }}" = "skipped" ] || exit 1 + else + [ "${{ needs.ios.result }}" = "success" ] || exit 1 + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a67105b1..d7b02202 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -585,6 +585,204 @@ jobs: YourSSH-${{ steps.version.outputs.version }}-Android.apk YourSSH-${{ steps.version.outputs.version }}-Android-symbols.zip + # ── iOS ──────────────────────────────────────────────────────────────────── + # Goes to TestFlight, not to the GitHub release page, so `release` does not + # need this job. The mobile UI is SSH-only: no Rust native libraries. + build-ios: + needs: test + runs-on: macos-latest + # Signing and upload run only when all secrets exist (forks and + # unconfigured repos still get an unsigned, bundle-checked build). Secrets: + # IOS_DISTRIBUTION_P12_BASE64 base64 of the exported Apple + # Distribution certificate + private key + # IOS_DISTRIBUTION_P12_PASSWORD password set when exporting the .p12 + # IOS_PROVISIONING_PROFILE_BASE64 base64 of the App Store provisioning + # profile named "YourSSH App Store" + # ASC_KEY_ID / ASC_ISSUER_ID App Store Connect API key id / issuer + # ASC_API_KEY_P8_BASE64 base64 of that key's AuthKey_*.p8 + env: + IOS_SIGNING: ${{ secrets.IOS_DISTRIBUTION_P12_BASE64 != '' && secrets.IOS_PROVISIONING_PROFILE_BASE64 != '' && secrets.ASC_KEY_ID != '' && secrets.ASC_ISSUER_ID != '' && secrets.ASC_API_KEY_P8_BASE64 != '' }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2 + with: + channel: stable + flutter-version: ${{ env.FLUTTER_VERSION }} + + - name: Install dependencies + working-directory: app + run: flutter pub get + + - name: Extract version + id: version + run: | + VERSION=$(grep '^version:' app/pubspec.yaml | sed 's/^version:[[:space:]]*//' | cut -d'+' -f1) + echo "version=$VERSION" >> $GITHUB_OUTPUT + + # ── Unsigned path (secrets missing) ── + - name: Build iOS (unsigned) + if: env.IOS_SIGNING != 'true' + working-directory: app + run: flutter build ios --release --no-codesign --split-debug-info=build/symbols + + - name: Check bundle (unsigned) + if: env.IOS_SIGNING != 'true' + run: bash tool/check_ios_bundle.sh app/build/ios/iphoneos/Runner.app + + - name: Zip unsigned app + if: env.IOS_SIGNING != 'true' + run: | + ditto -c -k --sequesterRsrc --keepParent app/build/ios/iphoneos/Runner.app \ + "YourSSH-${{ steps.version.outputs.version }}-iOS-unsigned.zip" + + # ── Signed path ── + - name: Import Apple Distribution certificate + if: env.IOS_SIGNING == 'true' + env: + CERT_P12_BASE64: ${{ secrets.IOS_DISTRIBUTION_P12_BASE64 }} + CERT_PASSWORD: ${{ secrets.IOS_DISTRIBUTION_P12_PASSWORD }} + run: | + KEYCHAIN="$RUNNER_TEMP/signing.keychain-db" + KEYCHAIN_PASSWORD="$(openssl rand -hex 24)" + echo "::add-mask::$KEYCHAIN_PASSWORD" + echo "$CERT_P12_BASE64" | base64 --decode > "$RUNNER_TEMP/cert.p12" + chmod 600 "$RUNNER_TEMP/cert.p12" + security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN" + # Exported right away so the always() cleanup deletes the keychain + # even when the import below fails (e.g. wrong .p12 password). + echo "SIGN_KEYCHAIN=$KEYCHAIN" >> "$GITHUB_ENV" + security set-keychain-settings -lut 21600 "$KEYCHAIN" + security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN" + security import "$RUNNER_TEMP/cert.p12" -k "$KEYCHAIN" -P "$CERT_PASSWORD" -T /usr/bin/codesign + rm -f "$RUNNER_TEMP/cert.p12" + security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN" > /dev/null + # Prepend the signing keychain to the search list (word splitting of + # the existing list is intended; runner keychain paths have no spaces). + # shellcheck disable=SC2046 + security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | tr -d '"') + IDENTITY=$(security find-identity -v -p codesigning "$KEYCHAIN" | awk '/Apple Distribution/ {print $2; exit}') + if [ -z "$IDENTITY" ]; then + echo "::error::The .p12 holds no Apple Distribution identity" + exit 1 + fi + + # Fails early with a clear message when the profile is not the one the + # Runner target's Release settings and ExportOptions.plist expect. Never + # prints profile contents. + - name: Install provisioning profile + if: env.IOS_SIGNING == 'true' + env: + PROFILE_BASE64: ${{ secrets.IOS_PROVISIONING_PROFILE_BASE64 }} + run: | + EXPECTED_NAME="YourSSH App Store" + EXPECTED_TEAM="84T567KMYD" + EXPECTED_APPID="84T567KMYD.com.thangnm.yourssh" + echo "$PROFILE_BASE64" | base64 --decode > "$RUNNER_TEMP/profile.mobileprovision" + chmod 600 "$RUNNER_TEMP/profile.mobileprovision" + security cms -D -i "$RUNNER_TEMP/profile.mobileprovision" > "$RUNNER_TEMP/profile.plist" + PB=/usr/libexec/PlistBuddy + NAME=$($PB -c 'Print :Name' "$RUNNER_TEMP/profile.plist" 2>/dev/null || true) + TEAMS=$($PB -c 'Print :TeamIdentifier' "$RUNNER_TEMP/profile.plist" 2>/dev/null || true) + APPID=$($PB -c 'Print :Entitlements:application-identifier' "$RUNNER_TEMP/profile.plist" 2>/dev/null || true) + UUID=$($PB -c 'Print :UUID' "$RUNNER_TEMP/profile.plist" 2>/dev/null || true) + rm -f "$RUNNER_TEMP/profile.plist" + FAILED=0 + if [ "$NAME" != "$EXPECTED_NAME" ]; then + echo "::error::Provisioning profile Name must be '$EXPECTED_NAME'" + FAILED=1 + fi + if ! printf '%s\n' "$TEAMS" | grep -qw "$EXPECTED_TEAM"; then + echo "::error::Provisioning profile TeamIdentifier must contain $EXPECTED_TEAM" + FAILED=1 + fi + if [ "$APPID" != "$EXPECTED_APPID" ]; then + echo "::error::Provisioning profile application-identifier must be $EXPECTED_APPID" + FAILED=1 + fi + if [ -z "$UUID" ]; then + echo "::error::Provisioning profile has no UUID" + FAILED=1 + fi + if [ "$FAILED" -ne 0 ]; then + rm -f "$RUNNER_TEMP/profile.mobileprovision" + exit 1 + fi + PROFILES_DIR="$HOME/Library/MobileDevice/Provisioning Profiles" + mkdir -p "$PROFILES_DIR" + mv "$RUNNER_TEMP/profile.mobileprovision" "$PROFILES_DIR/$UUID.mobileprovision" + echo "IOS_PROFILE_PATH=$PROFILES_DIR/$UUID.mobileprovision" >> "$GITHUB_ENV" + + # Manual signing is set in the Runner target's Release settings only; a + # command-line override would also hit the SPM/CocoaPods targets. + - name: Build signed IPA + if: env.IOS_SIGNING == 'true' + working-directory: app + run: | + # run_number repeats on "Re-run failed jobs"; the attempt keeps the + # build number monotonic (App Store Connect rejects duplicates). + BUILD_NUMBER=$(( ${{ github.run_number }} * 100 + ${{ github.run_attempt }} )) + flutter build ipa --release \ + --export-options-plist=ios/ExportOptions.plist \ + --build-number="$BUILD_NUMBER" \ + --split-debug-info=build/symbols + + - name: Check bundle (signed) + if: env.IOS_SIGNING == 'true' + run: bash tool/check_ios_bundle.sh app/build/ios/archive/Runner.xcarchive/Products/Applications/Runner.app + + - name: Name the IPA and zip debug symbols + if: env.IOS_SIGNING == 'true' + run: | + IPA=$(find app/build/ios/ipa -name '*.ipa' -maxdepth 1 | head -1) + mv "$IPA" "YourSSH-${{ steps.version.outputs.version }}-iOS.ipa" + cd app/build/symbols + zip -r "$GITHUB_WORKSPACE/YourSSH-${{ steps.version.outputs.version }}-iOS-symbols.zip" . + + - name: Upload to TestFlight + if: env.IOS_SIGNING == 'true' + env: + ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }} + ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }} + ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }} + run: | + KEY_DIR="$RUNNER_TEMP/private_keys" + mkdir -p "$KEY_DIR" + echo "$ASC_API_KEY_P8_BASE64" | base64 --decode > "$KEY_DIR/AuthKey_$ASC_KEY_ID.p8" + chmod 600 "$KEY_DIR/AuthKey_$ASC_KEY_ID.p8" + IPA="YourSSH-${{ steps.version.outputs.version }}-iOS.ipa" + if [ ! -f "$IPA" ]; then + echo "::error::$IPA is missing" + exit 1 + fi + API_PRIVATE_KEYS_DIR="$KEY_DIR" xcrun altool --upload-app -f "$IPA" -t ios \ + --apiKey "$ASC_KEY_ID" --apiIssuer "$ASC_ISSUER_ID" + + - name: Remove signing material + if: always() + run: | + if [ -n "$SIGN_KEYCHAIN" ]; then security delete-keychain "$SIGN_KEYCHAIN" || true; fi + if [ -n "$IOS_PROFILE_PATH" ]; then rm -f "$IOS_PROFILE_PATH"; fi + rm -f "$RUNNER_TEMP/profile.mobileprovision" "$RUNNER_TEMP/profile.plist" "$RUNNER_TEMP/cert.p12" + rm -rf "$RUNNER_TEMP/private_keys" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: env.IOS_SIGNING != 'true' + with: + name: ios + if-no-files-found: error + path: YourSSH-${{ steps.version.outputs.version }}-iOS-unsigned.zip + + # always(): a failed TestFlight upload still leaves the IPA to debug. + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: always() && env.IOS_SIGNING == 'true' + with: + name: ios + if-no-files-found: ignore + path: | + YourSSH-${{ steps.version.outputs.version }}-iOS.ipa + YourSSH-${{ steps.version.outputs.version }}-iOS-symbols.zip + release: runs-on: ubuntu-latest needs: [build-macos, build-windows, build-linux, build-android] diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cc44413..e57a80a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added +- **iOS (iPhone) build, distributed through TestFlight** — the mobile app now runs on iPhone. Hosts, SSH terminal, SFTP and the Keychain screens work as on Android. Secrets live in the iOS Keychain (this-device-only, no plaintext fallback) and imported keys are kept in app storage excluded from backup. The app lock covers the whole app and uses Face ID; the connection is kept for a short grace period in the background and reconnects on return. `yourssh://connect/` links work, and `ssh://` links are an opt-in setting that never connects to an unknown target. Local shell, RDP and VNC are desktop-only. Not on the App Store yet. + +### Fixed +- RDP and VNC hosts show a "desktop only" notice on mobile instead of failing to connect. +- Imported SSH keys are copied into app storage, so they keep working after the source file moves or the picker's temporary copy is removed. + ## [0.4.1] — 2026-11-13 Security and polish fixes found while writing the documentation (now at https://yoursshlabs.com). diff --git a/CLAUDE.md b/CLAUDE.md index 00535d27..45e49779 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,7 +84,7 @@ cd app && flutter test integration_test/vnc_screenshots_test.dart -d macos ## Architecture -The active codebase is `app/` — a Flutter app targeting macOS, Windows, and Linux. The in-app RDP client is implemented as the `packages/yourssh_rdp` Rust crate bridged via `flutter_rust_bridge` v2; the old `core/` Swift-bridge Rust library has been removed. +The active codebase is `app/` — a Flutter app targeting macOS, Windows, and Linux, plus Android and iOS through `app/lib/mobile`. The in-app RDP client is implemented as the `packages/yourssh_rdp` Rust crate bridged via `flutter_rust_bridge` v2; the old `core/` Swift-bridge Rust library has been removed. **Monorepo layout:** - `app/` — the Flutter app @@ -199,6 +199,17 @@ Flutter UI (widgets/screens) **Code editor:** `CodeEditorScreen` renders a Monaco editor via `webview_flutter` using the bundled `assets/monaco_editor.html`. +## iOS + +The iPhone build shares `app/lib/mobile` with Android. Platform gates live in `app/lib/platform/runtime_platform.dart` (`isIOSPlatform`, `supportsRemoteDesktop`, `supportsSubprocesses`, `mobileDefaultTmux`). There is no simulator runtime on the owner's Mac: launching is CI-only (pr-test `ios` job) or manual; locally run `cd app && flutter build ios --simulator --no-codesign` and `flutter build ios --release --no-codesign`. + +- **Runner**: UIScene runner (`SceneDelegate.swift`); `YourSshNative` (`app/ios/Runner/YourSshNative.swift`) is registered from `didInitializeImplicitFlutterEngine` and held strongly. Channels: `yourssh/url`, `yourssh/ssh_url`, `yourssh/background`, `yourssh/files`. +- **Lifecycle**: `MobileLifecycleCoordinator` runs grace / pause / resume with epochs; `SshSession.paused` / `acceptsInput` make input to a non-connected session fail visibly. +- **Secrets**: `StorageService.iosKeychainOptions` (`first_unlock_this_device`, not synchronizable); no plaintext prefs fallback on iOS. `AppPaths` puts keys in Application Support, excluded from backup. +- **Links**: `yourssh://` goes through `CliServer` + `UrlChannel`; `ssh://` is an opt-in iOS-only setting, never connects to an unknown target and is deferred while `mobileAppLocked` is true. +- **Compliance**: `PrivacyInfo.xcprivacy` (UserDefaults CA92.1, FileTimestamp C617.1, DiskSpace E174.1), `ITSAppUsesNonExemptEncryption = YES`, no `NSAppTransportSecurity` key. +- **CI**: `tool/check_ios_bundle.sh ` rejects QuickJS / RDP / VNC / flutter_pty artifacts, the `pty_forkpty` symbol and any `NSAppTransportSecurity` key; the pr-test `ios` job runs unit tests, simulator and release builds, the bundle check and a simulator smoke test (a `changes` job skips it when `tool/ios_ci_needed.sh` finds only documentation changes: `*.md`, `docs/`, `screenshots/`, `.claude/`). The two iOS `Package.resolved` files (`app/ios/Runner.xcworkspace/…` and `app/ios/Runner.xcodeproj/project.xcworkspace/…`) are committed so the signed build pins file_picker's branch-tracked SwiftPM dependencies (DKCamera, DKPhotoGallery); the macOS ones stay untracked. release.yml `build-ios` builds a signed IPA and uploads to TestFlight (needs secrets `IOS_DISTRIBUTION_P12_BASE64`, `IOS_DISTRIBUTION_P12_PASSWORD`, `IOS_PROVISIONING_PROFILE_BASE64`, `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_API_KEY_P8_BASE64`; the App Store profile must be named `YourSSH App Store`; `app/ios/ExportOptions.plist`); the IPA is not attached to the GitHub release. + ## Plugin system Two plugin types coexist: diff --git a/README.md b/README.md index ae55229d..a10565ef 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ YourSSH also checks for new releases on launch and from **Settings → Updates** | Linux (Debian/Ubuntu — x86_64) | `yourssh_x.x.x_amd64.deb` | | Linux (Debian/Ubuntu — ARM64) | `yourssh_x.x.x_arm64.deb` | | Android (development preview) | `YourSSH-x.x.x-Android.apk` | +| iOS | iPhone — beta through TestFlight | ### macOS — Homebrew @@ -321,6 +322,7 @@ Not yet: packaged CLI binary and an "Install command-line tool" button; `sftp`/` | macOS | 10.14 Mojave | | Windows | Windows 10 (64-bit) | | Linux | Ubuntu 20.04+ / any GTK3-compatible distro | +| iOS | iOS 16 (iPhone) | | Flutter SDK | 3.12.0+ | | Dart SDK | 3.12.0+ | diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml index 5e3d14cc..eb039b81 100644 --- a/app/analysis_options.yaml +++ b/app/analysis_options.yaml @@ -20,6 +20,7 @@ analyzer: - windows/** - macos/** - linux/** + - ios/** linter: # The lint rules applied to this project can be customized in the diff --git a/app/integration_test/ios_smoke_test.dart b/app/integration_test/ios_smoke_test.dart new file mode 100644 index 00000000..ee0d83f2 --- /dev/null +++ b/app/integration_test/ios_smoke_test.dart @@ -0,0 +1,48 @@ +// iOS simulator smoke test, run by the `ios` job in pr-test.yml: +// flutter test integration_test/ios_smoke_test.dart -d +// +// Boots the real mobile app with the app lock off, adds a host through +// HostProvider (no network is touched) and checks the card shows on the hosts +// tab, then opens Settings. Covers launch, bootstrap and tab navigation only; +// see the task report for what stays manual. +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/mobile/mobile_app.dart'; +import 'package:yourssh/mobile/screens/mobile_settings_screen.dart'; +import 'package:yourssh/mobile/security/app_lock_gate.dart'; +import 'package:yourssh/mobile/widgets/host_card.dart'; +import 'package:yourssh/mobile/widgets/mobile_tab_bar.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/providers/host_provider.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('launches, lists an added host and opens Settings', + (tester) async { + SharedPreferences.setMockInitialValues({kAppLockPrefKey: false}); + + await tester.pumpWidget(const YourSSHMobileApp()); + await tester.pumpAndSettle(const Duration(seconds: 2)); + expect(find.byType(MobileTabBar), findsOneWidget); + + final ctx = tester.element(find.byType(MobileTabBar)); + await ctx.read().addHost(Host( + label: 'smoke-host', + host: '203.0.113.7', + username: 'smoke', + )); + await tester.pumpAndSettle(); + + expect(find.byType(HostCard), findsOneWidget); + expect(find.text('smoke-host'), findsOneWidget); + + await tester.tap(find.descendant( + of: find.byType(MobileTabBar), matching: find.text('Settings'))); + await tester.pumpAndSettle(); + expect(find.byType(MobileSettingsScreen), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/ios/.gitignore b/app/ios/.gitignore new file mode 100644 index 00000000..7a7f9873 --- /dev/null +++ b/app/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/app/ios/ExportOptions.plist b/app/ios/ExportOptions.plist new file mode 100644 index 00000000..50288084 --- /dev/null +++ b/app/ios/ExportOptions.plist @@ -0,0 +1,19 @@ + + + + + method + app-store-connect + teamID + 84T567KMYD + signingStyle + manual + provisioningProfiles + + com.thangnm.yourssh + YourSSH App Store + + uploadSymbols + + + diff --git a/app/ios/Flutter/AppFrameworkInfo.plist b/app/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 00000000..391a902b --- /dev/null +++ b/app/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/app/ios/Flutter/Debug.xcconfig b/app/ios/Flutter/Debug.xcconfig new file mode 100644 index 00000000..ec97fc6f --- /dev/null +++ b/app/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/app/ios/Flutter/Release.xcconfig b/app/ios/Flutter/Release.xcconfig new file mode 100644 index 00000000..c4855bfe --- /dev/null +++ b/app/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/app/ios/Podfile b/app/ios/Podfile new file mode 100644 index 00000000..fad4db75 --- /dev/null +++ b/app/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +platform :ios, '16.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/app/ios/Podfile.lock b/app/ios/Podfile.lock new file mode 100644 index 00000000..ac335ea4 --- /dev/null +++ b/app/ios/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - Flutter (1.0.0) + - flutter_secure_storage (6.0.0): + - Flutter + +DEPENDENCIES: + - Flutter (from `Flutter`) + - flutter_secure_storage (from `.symlinks/plugins/flutter_secure_storage/ios`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + flutter_secure_storage: + :path: ".symlinks/plugins/flutter_secure_storage/ios" + +SPEC CHECKSUMS: + Flutter: 71a624a5bc0c04062bf19101d501e466baf2fb47 + flutter_secure_storage: 1ed9476fba7e7a782b22888f956cce43e2c62f13 + +PODFILE CHECKSUM: 1857a7cdb7dfafe45f2b0e9a9af44644190f7506 + +COCOAPODS: 1.17.0 diff --git a/app/ios/Runner.xcodeproj/project.pbxproj b/app/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 00000000..2ddcd090 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,773 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + A1B2C3D41FA0000100000001 /* YourSshNative.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D41FA0000100000002 /* YourSshNative.swift */; }; + AE04BDAF9DD97576AF1D44D7 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D7AAE4DBF509F46C5AB19F7B /* Pods_Runner.framework */; }; + E12C5A6656658567A24824DD /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4B092B1767D5AFEFE6F9F1C6 /* Pods_RunnerTests.framework */; }; + A1B2C3D41FA0000200000001 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = A1B2C3D41FA0000200000002 /* PrivacyInfo.xcprivacy */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 2440D290E56EC52F19500428 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 400831138A16188B271C3D18 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + 4B092B1767D5AFEFE6F9F1C6 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 8B9C534F49E8728E9A22B5DC /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A1B2C3D41FA0000100000002 /* YourSshNative.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YourSshNative.swift; sourceTree = ""; }; + B3BCAC9C92ABA192350E7C1B /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + C08A9CAF5079D4BDFF8C57D6 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + D7AAE4DBF509F46C5AB19F7B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + DB8541CBDECFF7BCE426A0EB /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + A1B2C3D41FA0000200000002 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 7E6F51C5377A96E8D7F0F86B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E12C5A6656658567A24824DD /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + AE04BDAF9DD97576AF1D44D7 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2FAF4A83A0A22C78D3E9BCE7 /* Pods */ = { + isa = PBXGroup; + children = ( + B3BCAC9C92ABA192350E7C1B /* Pods-Runner.debug.xcconfig */, + 8B9C534F49E8728E9A22B5DC /* Pods-Runner.release.xcconfig */, + 2440D290E56EC52F19500428 /* Pods-Runner.profile.xcconfig */, + C08A9CAF5079D4BDFF8C57D6 /* Pods-RunnerTests.debug.xcconfig */, + 400831138A16188B271C3D18 /* Pods-RunnerTests.release.xcconfig */, + DB8541CBDECFF7BCE426A0EB /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 5B8B68ADECD4528EDCE7B11A /* Frameworks */ = { + isa = PBXGroup; + children = ( + D7AAE4DBF509F46C5AB19F7B /* Pods_Runner.framework */, + 4B092B1767D5AFEFE6F9F1C6 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 2FAF4A83A0A22C78D3E9BCE7 /* Pods */, + 5B8B68ADECD4528EDCE7B11A /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + A1B2C3D41FA0000200000002 /* PrivacyInfo.xcprivacy */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + A1B2C3D41FA0000100000002 /* YourSshNative.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 61192FD2137FF38068278EE1 /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 7E6F51C5377A96E8D7F0F86B /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 2A9467CE0647325BB768624D /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 677EA557FB4AB53F4BBEDA2E /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + A1B2C3D41FA0000200000001 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 2A9467CE0647325BB768624D /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 61192FD2137FF38068278EE1 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 677EA557FB4AB53F4BBEDA2E /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + A1B2C3D41FA0000100000001 /* YourSshNative.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = 1; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 84T567KMYD; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C08A9CAF5079D4BDFF8C57D6 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 400831138A16188B271C3D18 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DB8541CBDECFF7BCE426A0EB /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + TARGETED_DEVICE_FAMILY = 1; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = 1; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 84T567KMYD; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "Apple Distribution"; + CODE_SIGN_STYLE = Manual; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 84T567KMYD; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = "YourSSH App Store"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..919434a6 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..74429989 --- /dev/null +++ b/app/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,67 @@ +{ + "pins" : [ + { + "identity" : "csqlite", + "kind" : "remoteSourceControl", + "location" : "https://github.com/simolus3/CSQLite.git", + "state" : { + "revision" : "1ee46d19a4f451a7aa64ffc64fc99b4748131e62" + } + }, + { + "identity" : "dkcamera", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKCamera", + "state" : { + "branch" : "master", + "revision" : "5c691d11014b910aff69f960475d70e65d9dcc96" + } + }, + { + "identity" : "dkimagepickercontroller", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKImagePickerController", + "state" : { + "branch" : "4.3.9", + "revision" : "0bdfeacefa308545adde07bef86e349186335915" + } + }, + { + "identity" : "dkphotogallery", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKPhotoGallery", + "state" : { + "branch" : "master", + "revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d" + } + }, + { + "identity" : "sdwebimage", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SDWebImage/SDWebImage", + "state" : { + "revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0", + "version" : "5.21.7" + } + }, + { + "identity" : "swiftygif", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kirualex/SwiftyGif.git", + "state" : { + "revision" : "4430cbc148baa3907651d40562d96325426f409a", + "version" : "5.4.5" + } + }, + { + "identity" : "tocropviewcontroller", + "kind" : "remoteSourceControl", + "location" : "https://github.com/TimOliver/TOCropViewController", + "state" : { + "revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e", + "version" : "2.8.0" + } + } + ], + "version" : 2 +} diff --git a/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 00000000..c3fedb29 --- /dev/null +++ b/app/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner.xcworkspace/contents.xcworkspacedata b/app/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000..21a3cc14 --- /dev/null +++ b/app/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 00000000..f9b0d7c5 --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/app/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/app/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 00000000..74429989 --- /dev/null +++ b/app/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,67 @@ +{ + "pins" : [ + { + "identity" : "csqlite", + "kind" : "remoteSourceControl", + "location" : "https://github.com/simolus3/CSQLite.git", + "state" : { + "revision" : "1ee46d19a4f451a7aa64ffc64fc99b4748131e62" + } + }, + { + "identity" : "dkcamera", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKCamera", + "state" : { + "branch" : "master", + "revision" : "5c691d11014b910aff69f960475d70e65d9dcc96" + } + }, + { + "identity" : "dkimagepickercontroller", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKImagePickerController", + "state" : { + "branch" : "4.3.9", + "revision" : "0bdfeacefa308545adde07bef86e349186335915" + } + }, + { + "identity" : "dkphotogallery", + "kind" : "remoteSourceControl", + "location" : "https://github.com/zhangao0086/DKPhotoGallery", + "state" : { + "branch" : "master", + "revision" : "311c1bc7a94f1538f82773a79c84374b12a2ef3d" + } + }, + { + "identity" : "sdwebimage", + "kind" : "remoteSourceControl", + "location" : "https://github.com/SDWebImage/SDWebImage", + "state" : { + "revision" : "2de3a496eaf6df9a1312862adcfd54acd73c39c0", + "version" : "5.21.7" + } + }, + { + "identity" : "swiftygif", + "kind" : "remoteSourceControl", + "location" : "https://github.com/kirualex/SwiftyGif.git", + "state" : { + "revision" : "4430cbc148baa3907651d40562d96325426f409a", + "version" : "5.4.5" + } + }, + { + "identity" : "tocropviewcontroller", + "kind" : "remoteSourceControl", + "location" : "https://github.com/TimOliver/TOCropViewController", + "state" : { + "revision" : "d4a6d8100f4b886fdbc8ae399bf144ff3e9afb7e", + "version" : "2.8.0" + } + } + ], + "version" : 2 +} diff --git a/app/ios/Runner/AppDelegate.swift b/app/ios/Runner/AppDelegate.swift new file mode 100644 index 00000000..a0c5a9ad --- /dev/null +++ b/app/ios/Runner/AppDelegate.swift @@ -0,0 +1,18 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + YourSshNative.register( + with: engineBridge.pluginRegistry.registrar(forPlugin: "YourSshNative")!) + } +} diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..22bf61d7 --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,14 @@ +{ + "images" : [ + { + "filename" : "app_icon_1024.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 00000000..93abef2b Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 00000000..0bedcf2f --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 00000000..9da19eac Binary files /dev/null and b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 00000000..89c2725b --- /dev/null +++ b/app/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/app/ios/Runner/Base.lproj/LaunchScreen.storyboard b/app/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000..f2e259c7 --- /dev/null +++ b/app/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner/Base.lproj/Main.storyboard b/app/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 00000000..f3c28516 --- /dev/null +++ b/app/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/ios/Runner/Info.plist b/app/ios/Runner/Info.plist new file mode 100644 index 00000000..229ccea3 --- /dev/null +++ b/app/ios/Runner/Info.plist @@ -0,0 +1,106 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + YourSSH + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + yourssh + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + CFBundleURLTypes + + + CFBundleTypeRole + Viewer + CFBundleURLName + YourSSH URL + CFBundleURLSchemes + + yourssh + + + + CFBundleTypeRole + Viewer + CFBundleURLName + SSH URL + CFBundleURLSchemes + + ssh + + + + FlutterDeepLinkingEnabled + + ITSAppUsesNonExemptEncryption + + NSCameraUsageDescription + Scan the QR code YourSSH shows on your computer to import hosts. + NSAppleMusicUsageDescription + YourSSH only reads your media library if you pick an audio file to upload to a server. + NSFaceIDUsageDescription + YourSSH uses Face ID to unlock the app and protect your saved hosts and keys. + NSPhotoLibraryUsageDescription + YourSSH only accesses your photos and videos when you pick one to upload to a server. + NSLocationWhenInUseUsageDescription + YourSSH does not track your location. iOS may ask for this when the app reads Wi-Fi network details to share a file over your local network. + NSLocalNetworkUsageDescription + YourSSH connects to SSH servers and to your computer on the local network to import or share hosts. + LSSupportsOpeningDocumentsInPlace + + LSRequiresIPhoneOS + + UIFileSharingEnabled + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/app/ios/Runner/PrivacyInfo.xcprivacy b/app/ios/Runner/PrivacyInfo.xcprivacy new file mode 100644 index 00000000..c08efed1 --- /dev/null +++ b/app/ios/Runner/PrivacyInfo.xcprivacy @@ -0,0 +1,39 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryDiskSpace + NSPrivacyAccessedAPITypeReasons + + E174.1 + + + + + diff --git a/app/ios/Runner/Runner-Bridging-Header.h b/app/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 00000000..308a2a56 --- /dev/null +++ b/app/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/app/ios/Runner/SceneDelegate.swift b/app/ios/Runner/SceneDelegate.swift new file mode 100644 index 00000000..b9ce8ea2 --- /dev/null +++ b/app/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/app/ios/Runner/YourSshNative.swift b/app/ios/Runner/YourSshNative.swift new file mode 100644 index 00000000..f818416c --- /dev/null +++ b/app/ios/Runner/YourSshNative.swift @@ -0,0 +1,163 @@ +import Flutter +import UIKit + +/// Native entry point for YourSSH on iOS. Method channels (Keychain access, +/// app lock, file import, ...) are added here by later tasks; for now it only +/// registers itself for UIScene lifecycle callbacks. +final class YourSshNative: NSObject, FlutterPlugin, FlutterSceneLifeCycleDelegate { + private var backgroundTasks: [Int: UIBackgroundTaskIdentifier] = [:] + + /// A link channel with the macOS contract (MainFlutterWindow.swift): Dart + /// calls `ready`, native calls `open(String)`. URLs arriving before `ready` + /// (a cold launch) are queued, newest 8 kept. + private final class LinkChannel { + let channel: FlutterMethodChannel + private var dartReady = false + private var pending: [String] = [] + + init(_ channel: FlutterMethodChannel) { self.channel = channel } + + func ready() { + dartReady = true + let queued = pending + pending.removeAll() + for url in queued { channel.invokeMethod("open", arguments: url) } + } + + func deliver(_ url: String) { + if dartReady { + channel.invokeMethod("open", arguments: url) + } else { + pending.append(url) + if pending.count > 8 { pending.removeFirst(pending.count - 8) } + } + } + } + + private var yoursshLinks: LinkChannel? + private var sshLinks: LinkChannel? + + static func register(with registrar: FlutterPluginRegistrar) { + let instance = YourSshNative() + // Ownership: nothing else keeps `instance` alive. Flutter holds scene + // lifecycle delegates in a WEAK array, so without a strong reference it + // would be deallocated as soon as this function returns (and every channel + // call would then fail). `publish` retains it for the registrar's lifetime + // and `addMethodCallDelegate` makes the channel retain it as its handler. + registrar.publish(instance) + registrar.addSceneDelegate(instance) + + // yourssh/background: begin -> {"id": Int, "remainingMs": Int} (-1 when the + // OS reports no finite allowance), null when refused; end(id). + let background = FlutterMethodChannel( + name: "yourssh/background", binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(instance, channel: background) + + // yourssh/files: excludeFromBackup(path) -> null. Marks a file or directory + // as not to be included in iCloud / iTunes backups. + let files = FlutterMethodChannel( + name: "yourssh/files", binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(instance, channel: files) + + // yourssh/url (yourssh://) and yourssh/ssh_url (ssh://): Dart -> native + // `ready`; native -> Dart `open`. + let url = FlutterMethodChannel( + name: "yourssh/url", binaryMessenger: registrar.messenger()) + let sshUrl = FlutterMethodChannel( + name: "yourssh/ssh_url", binaryMessenger: registrar.messenger()) + instance.yoursshLinks = LinkChannel(url) + instance.sshLinks = LinkChannel(sshUrl) + // One handler per channel (the delegate's `handle` cannot tell which + // channel a call came from). The closures keep their LinkChannel alive. + for link in [instance.yoursshLinks!, instance.sshLinks!] { + link.channel.setMethodCallHandler { call, result in + if call.method == "ready" { + link.ready() + result(nil) + } else { + result(FlutterMethodNotImplemented) + } + } + } + } + + // MARK: Links + + /// Cold start: the launching URL arrives in the connection options. + func scene( + _ scene: UIScene, willConnectTo session: UISceneSession, + options connectionOptions: UIScene.ConnectionOptions? + ) -> Bool { + guard let contexts = connectionOptions?.urlContexts else { return false } + return routeLinks(contexts) + } + + /// Warm start: the app is already running. + func scene(_ scene: UIScene, openURLContexts URLContexts: Set) -> Bool { + return routeLinks(URLContexts) + } + + /// Returns true when a link was ours. Claiming it keeps Flutter from also + /// treating the URL as a navigation route. + private func routeLinks(_ contexts: Set) -> Bool { + var handled = false + for context in contexts { + let url = context.url.absoluteString + switch context.url.scheme?.lowercased() { + case "yourssh": yoursshLinks?.deliver(url); handled = true + case "ssh": sshLinks?.deliver(url); handled = true + default: break + } + } + return handled + } + + func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "begin": beginBackgroundTask(result) + case "end": + if let id = call.arguments as? Int { endBackgroundTask(id) } + result(nil) + case "excludeFromBackup": excludeFromBackup(call.arguments, result) + default: result(FlutterMethodNotImplemented) + } + } + + private func beginBackgroundTask(_ result: @escaping FlutterResult) { + var taskId = UIBackgroundTaskIdentifier.invalid + taskId = UIApplication.shared.beginBackgroundTask(withName: "yourssh.grace") { [weak self] in + // The OS is about to suspend us: end the task so it does not kill the app. + self?.endBackgroundTask(taskId.rawValue) + } + if taskId == .invalid { + result(nil) + return + } + backgroundTasks[taskId.rawValue] = taskId + let remaining = UIApplication.shared.backgroundTimeRemaining + let remainingMs = remaining.isFinite && remaining < Double(Int32.max) + ? Int(remaining * 1000) : -1 + result(["id": taskId.rawValue, "remainingMs": remainingMs]) + } + + private func endBackgroundTask(_ id: Int) { + guard let task = backgroundTasks.removeValue(forKey: id) else { return } + UIApplication.shared.endBackgroundTask(task) + } + + private func excludeFromBackup(_ arguments: Any?, _ result: @escaping FlutterResult) { + guard let path = arguments as? String else { + result(FlutterError(code: "bad_args", message: "path expected", details: nil)) + return + } + var url = URL(fileURLWithPath: path) + var values = URLResourceValues() + values.isExcludedFromBackup = true + do { + try url.setResourceValues(values) + result(nil) + } catch { + result(FlutterError(code: "exclude_failed", message: "\(error)", details: nil)) + } + } +} diff --git a/app/ios/RunnerTests/RunnerTests.swift b/app/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 00000000..9d454788 --- /dev/null +++ b/app/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,13 @@ +import Flutter +import Testing +import UIKit + +struct RunnerTests { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/xcode/swift-testing/ for more information about using + // Swift Testing. + } + +} diff --git a/app/lib/mobile/files/app_paths.dart b/app/lib/mobile/files/app_paths.dart new file mode 100644 index 00000000..091ead4b --- /dev/null +++ b/app/lib/mobile/files/app_paths.dart @@ -0,0 +1,58 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import '../../platform/runtime_platform.dart'; +import '../../util/file_mode.dart'; +import '../../util/native_chmod.dart'; + +/// `chmod(path, mode)`; same shape as the `KeyGenService` constructor type. +typedef ChmodFn = Future Function(String path, int mode); + +const MethodChannel _filesChannel = MethodChannel('yourssh/files'); + +Future _defaultExcludeFromBackup(String path) async { + if (!isIOSPlatform) return; + await _filesChannel.invokeMethod('excludeFromBackup', path); +} + +/// Where the mobile app keeps its files. +/// +/// On iOS the Documents directory is shown in the Files app +/// (`UIFileSharingEnabled`), so private keys must live elsewhere: in the +/// Application Support directory, which is neither exposed nor — once the +/// directory is flagged — backed up. +class AppPaths { + AppPaths._(); + + /// Directory name of the private keys dir inside Application Support. + static const keysDirName = 'keys'; + + /// Path of [privateKeysDir] without creating it or touching its mode. + static Future privateKeysDirPath() async => + p.join((await getApplicationSupportDirectory()).path, keysDirName); + + /// `/keys`: created, 0700, excluded from backups. + static Future privateKeysDir({ + ChmodFn? chmod, + Future Function(String path)? excludeFromBackup, + }) async { + final support = await getApplicationSupportDirectory(); + final dir = Directory(p.join(support.path, keysDirName)); + await dir.create(recursive: true); + await (chmod ?? (supportsSubprocesses ? chmodLocal : chmodNative))( + dir.path, 0x1C0); + await (excludeFromBackup ?? _defaultExcludeFromBackup)(dir.path); + return dir; + } + + /// `/Downloads`: the only folder the Files app shows for us. + static Future downloadsDir() async { + final docs = await getApplicationDocumentsDirectory(); + final dir = Directory(p.join(docs.path, 'Downloads')); + await dir.create(recursive: true); + return dir; + } +} diff --git a/app/lib/mobile/files/file_export.dart b/app/lib/mobile/files/file_export.dart new file mode 100644 index 00000000..e78d3f65 --- /dev/null +++ b/app/lib/mobile/files/file_export.dart @@ -0,0 +1,82 @@ +import 'dart:io'; + +import 'package:flutter/widgets.dart'; +import 'package:path/path.dart' as p; +import 'package:share_plus/share_plus.dart'; + +import '../../platform/runtime_platform.dart'; +import '../../util/file_mode.dart'; +import '../../util/native_chmod.dart'; +import '../../util/safe_local_path.dart'; +import 'app_paths.dart'; + +/// Copies (never moves) a picked private key into [into] under a unique, +/// sanitized name with mode 0600, and returns the copy. +Future importPrivateKey( + String pickedPath, + Directory into, { + ChmodFn? chmod, +}) async { + final base = p + .basename(pickedPath) + .replaceAll(RegExp(r'[^a-zA-Z0-9._-]'), '_') + .replaceFirst(RegExp(r'^\.+'), '_'); + final target = uniqueLocalPath(into.path, base.isEmpty ? 'key' : base); + final chmodFn = chmod ?? (supportsSubprocesses ? chmodLocal : chmodNative); + // Create empty and restrict before any key bytes land. + final out = await File(target).create(exclusive: true); + try { + await chmodFn(out.path, 0x180); + await out.writeAsBytes(await File(pickedPath).readAsBytes()); + } catch (_) { + if (out.existsSync()) await out.delete(); + rethrow; + } + return out; +} + +/// [name] inside [dir] (validated by [safeLocalChild]); when taken, the +/// first free `name (1).ext`, `name (2).ext`, ... +String uniqueLocalPath(String dir, String name) { + final first = safeLocalChild(dir, name); + if (!_exists(first)) return first; + final ext = p.extension(name); + final stem = ext.isEmpty ? name : name.substring(0, name.length - ext.length); + for (var i = 1;; i++) { + final candidate = safeLocalChild(dir, '$stem ($i)$ext'); + if (!_exists(candidate)) return candidate; + } +} + +bool _exists(String path) => FileSystemEntity.typeSync(path, followLinks: false) != + FileSystemEntityType.notFound; + +/// Streams [data] into `finalPath.part` and renames it to [finalPath] on +/// success. On any error the partial file is deleted and the error rethrown, +/// so a failed download never leaves a truncated file behind. +Future writeDownload(Stream> data, String finalPath) async { + final part = File('$finalPath.part'); + final sink = part.openWrite(); + try { + await sink.addStream(data); + await sink.close(); + await part.rename(finalPath); + } catch (_) { + try { + await sink.close(); + } catch (_) {} + try { + if (part.existsSync()) await part.delete(); + } catch (_) {} + rethrow; + } +} + +/// Opens the iOS share sheet for [path]. +Future shareFile(BuildContext context, String path) async { + final box = context.findRenderObject() as RenderBox?; + final origin = box != null && box.hasSize + ? box.localToGlobal(Offset.zero) & box.size + : null; + await Share.shareXFiles([XFile(path)], sharePositionOrigin: origin); +} diff --git a/app/lib/mobile/lifecycle/background_tasks.dart b/app/lib/mobile/lifecycle/background_tasks.dart new file mode 100644 index 00000000..b63290e7 --- /dev/null +++ b/app/lib/mobile/lifecycle/background_tasks.dart @@ -0,0 +1,56 @@ +import 'package:flutter/services.dart'; + +/// An OS grant to keep running briefly after the app leaves the foreground. +class BackgroundLease { + const BackgroundLease({required this.id, this.remaining}); + + final int id; + + /// Time the OS says is left; null when unknown. + final Duration? remaining; +} + +/// Asks the OS for background execution time (iOS +/// `beginBackgroundTask(withName:expirationHandler:)`). +abstract class BackgroundTasks { + /// Null when the OS refuses. + Future begin(); + Future end(int id); +} + +class MethodChannelBackgroundTasks implements BackgroundTasks { + MethodChannelBackgroundTasks( + [MethodChannel channel = const MethodChannel('yourssh/background')]) + : _channel = channel; + + final MethodChannel _channel; + + @override + Future begin() async { + try { + final r = await _channel.invokeMapMethod('begin'); + if (r == null) return null; + final id = r['id'] as int?; + if (id == null) return null; + final ms = r['remainingMs'] as int?; + return BackgroundLease( + id: id, + remaining: (ms == null || ms < 0) ? null : Duration(milliseconds: ms)); + } on PlatformException { + return null; + } on MissingPluginException { + return null; + } + } + + @override + Future end(int id) async { + try { + await _channel.invokeMethod('end', id); + } on PlatformException { + // The task is already over (the OS expired it). + } on MissingPluginException { + // No native side (tests, other platforms). + } + } +} diff --git a/app/lib/mobile/lifecycle/mobile_lifecycle_coordinator.dart b/app/lib/mobile/lifecycle/mobile_lifecycle_coordinator.dart new file mode 100644 index 00000000..0c395f69 --- /dev/null +++ b/app/lib/mobile/lifecycle/mobile_lifecycle_coordinator.dart @@ -0,0 +1,168 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../models/port_forward.dart'; +import '../../providers/port_forward_provider.dart'; +import '../../providers/session_provider.dart'; +import '../../services/p2p_sync_service.dart'; +import '../../services/port_forward_service.dart'; +import 'background_tasks.dart'; + +/// iOS suspends the app soon after it leaves the foreground and kills its +/// sockets. This keeps a short, deliberate grace window (a quick app switch +/// changes nothing), then closes everything cleanly — port forwards first so +/// their reconnect backoff never starts — and reconnects on return. +/// +/// `inactive` (Face ID sheet, Control Center) is never acted on: only the +/// paused/resumed lifecycle states call [onBackground]/[onForeground]. +class MobileLifecycleCoordinator { + MobileLifecycleCoordinator({ + required this.sessions, + required this.forwards, + required this.forwardRules, + required this.tasks, + this.stagger = const Duration(milliseconds: 300), + this.maxGrace = const Duration(seconds: 25), + Future Function()? stopPairing, + }) : stopPairing = stopPairing ?? P2PSyncService.stopAll; + + final SessionProvider sessions; + final PortForwardService forwards; + final PortForwardProvider forwardRules; + final BackgroundTasks tasks; + final Duration stagger; + final Duration maxGrace; + + /// Closes the LAN pairing server (its socket dies with the suspension). + final Future Function() stopPairing; + + /// The OS keeps part of its allowance for its own expiration handling. + static const _osMargin = Duration(seconds: 5); + + Timer? _graceTimer; + BackgroundLease? _lease; + List _stoppedForwards = const []; + Future? _expiry; + final _open = {}; + + Future _endLease(BackgroundLease lease) async { + if (_open.remove(lease.id)) await tasks.end(lease.id); + } + bool _background = false; + bool _disposed = false; + + /// Bumped on every background/foreground transition so an answer to an older + /// `begin()` can tell it was superseded. + int _epoch = 0; + + Duration _graceFor(BackgroundLease? lease) { + if (lease == null) return Duration.zero; + final remaining = lease.remaining; + final byOs = remaining == null ? maxGrace : remaining - _osMargin; + final grace = byOs < maxGrace ? byOs : maxGrace; + return grace.isNegative ? Duration.zero : grace; + } + + Future onBackground() async { + if (_disposed || _background) return; + _background = true; + final epoch = ++_epoch; + final lease = await tasks.begin(); + if (epoch != _epoch || _disposed) { + // Foregrounded (or backgrounded again) while the OS was answering. + if (lease != null) unawaited(tasks.end(lease.id)); + return; + } + if (lease != null) _open.add(lease.id); + _lease = lease; + _graceTimer?.cancel(); + final grace = _graceFor(lease); + if (grace == Duration.zero) { + await (_expiry = _onGraceExpired(epoch)); + } else { + _graceTimer = Timer(grace, () => _expiry = _onGraceExpired(epoch)); + } + } + + Future _onGraceExpired(int epoch) async { + _graceTimer = null; + final lease = _lease; + try { + // Remember what ran, across several backgrounds before one foreground. + final known = _stoppedForwards.map((f) => f.id).toSet(); + _stoppedForwards = [ + ..._stoppedForwards, + ...forwardRules.forwards + .where((f) => forwards.isRunning(f.id) && !known.contains(f.id)), + ]; + await forwards.stopAll(); + // The app came back (or left again) while the tunnels were closing: + // this expiry belongs to an older background and must not pause + // anything. + if (epoch == _epoch && !_disposed) { + sessions.pauseAll(); + await stopPairing(); + } + } catch (e) { + debugPrint('[MobileLifecycleCoordinator] pause failed: $e'); + } finally { + // Release our own lease even when a newer background already replaced + // `_lease`; [_endLease] is idempotent against the foreground's release. + if (lease != null) { + if (identical(_lease, lease)) _lease = null; + await _endLease(lease); + } + } + } + + Future onForeground() async { + // `resumed` also follows an inactive-only transition (Face ID sheet, + // Control Center): nothing was backgrounded, so there is nothing to do. + if (_disposed || !_background) return; + _background = false; + final epoch = ++_epoch; + _graceTimer?.cancel(); + _graceTimer = null; + final expiry = _expiry; + if (expiry != null) await expiry; + // A newer background started while we waited: it owns the lease, the + // recorded forwards and the next foreground. + if (epoch != _epoch || _disposed) return; + if (identical(_expiry, expiry)) _expiry = null; + final lease = _lease; + _lease = null; + if (lease != null) await _endLease(lease); + // Each step below can take seconds; a background that began meanwhile + // owns the recorded forwards and the paused sessions. + bool stale() => epoch != _epoch || _disposed; + if (stale()) return; + await sessions.resumePaused(stagger: stagger); + if (!stale()) await sessions.verifyLive(); + // The recorded forwards stay in `_stoppedForwards` until each one is + // started, so a foreground that goes stale keeps them for the next one. + await _restartStopped(); + } + + /// Starts the recorded forwards one by one while the app is in the + /// foreground. Safe to run from several foregrounds at once: each forward + /// is removed before it starts, so it starts once. A stale foreground also + /// calls this, so forwards are never left stopped when a newer foreground + /// already finished. + Future _restartStopped() async { + while (!_background && !_disposed && _stoppedForwards.isNotEmpty) { + final f = _stoppedForwards.first; + _stoppedForwards = _stoppedForwards.skip(1).toList(); + await forwards.start(f); + } + } + + void dispose() { + _disposed = true; + _graceTimer?.cancel(); + _graceTimer = null; + final lease = _lease; + _lease = null; + if (lease != null) unawaited(_endLease(lease)); + } +} diff --git a/app/lib/mobile/links/mobile_cli_handlers.dart b/app/lib/mobile/links/mobile_cli_handlers.dart new file mode 100644 index 00000000..6a352eed --- /dev/null +++ b/app/lib/mobile/links/mobile_cli_handlers.dart @@ -0,0 +1,37 @@ +import '../../models/host.dart'; +import '../../providers/host_provider.dart'; +import '../../services/cli/cli_handlers.dart'; +import '../../services/cli/host_resolver.dart'; + +/// [CliHandlers] for `yourssh://` links on mobile: saved hosts only. +class MobileCliHandlers implements CliHandlers { + MobileCliHandlers({ + required this.hostProvider, + required this.open, + required this.appVersion, + }); + + final HostProvider hostProvider; + + /// Opens a session for [Host]; the source is recorded on the audit row. + final Future Function(Host host, String source) open; + + @override + final String appVersion; + + @override + List get hosts => hostProvider.allHosts; + + @override + Future connect(Host host, {required String source}) => + open(host, source); + + /// URLs never allow ad-hoc targets (the resolver is called with + /// `allowAdHoc: false`); reaching this is a bug. + @override + Future connectAdHoc(AdHocTarget target) => + throw StateError('ad-hoc connects are not available from links'); + + @override + Future focusWindow() async {} +} diff --git a/app/lib/mobile/links/mobile_links.dart b/app/lib/mobile/links/mobile_links.dart new file mode 100644 index 00000000..b36d1c30 --- /dev/null +++ b/app/lib/mobile/links/mobile_links.dart @@ -0,0 +1,164 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart' show debugPrint; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh_cli/yourssh_cli.dart' show generateToken, sanitize; +import 'package:yourssh_ui/yourssh_ui.dart' show showYsConfirm; + +import '../../models/host.dart'; +import '../../services/cli/cli_server.dart'; +import '../../services/cli/link_refused.dart'; +import '../../services/cli/url_channel.dart'; +import '../../theme/app_theme.dart' show AppSnack; +import '../mobile_bootstrap.dart'; +import '../navigation/open_session.dart'; +import '../screens/mobile_add_host_screen.dart'; +import '../security/app_lock_gate.dart' show mobileAppLocked; +import '../util/mobile_prefs.dart'; +import 'mobile_cli_handlers.dart'; +import 'ssh_link.dart'; + +/// The `yourssh/ssh_url` method channel (YourSshNative.swift on iOS): `ssh://` +/// URLs, kept apart from `yourssh/url` so they can be switched off. +const MethodChannel kSshUrlChannel = MethodChannel('yourssh/ssh_url'); + +/// Wires `yourssh://` (always) and `ssh://` (opt-in) links on iOS. +/// +/// `yourssh://connect/` goes through the same [CliServer] as the +/// desktop CLI and URL handling (one parser, one resolver): saved hosts only, +/// no ad-hoc targets, no commands. `ssh://user@host[:port]` opens a saved +/// match, or after a confirmation prefills the Add Host form; it never +/// connects to an unsaved target. +class MobileLinks { + MobileLinks({ + required this.bootstrap, + required this.navigator, + required this.appVersion, + this.urlChannel = kUrlMethodChannel, + this.sshChannel = kSshUrlChannel, + this.openSession = openMobileSession, + }); + + /// Opens a session; [openMobileSession] in production, replaced in tests. + final Future Function(NavigatorState nav, Host host, + {String auditSource, bool resetStack}) openSession; + + final MobileBootstrap bootstrap; + final GlobalKey navigator; + final String appVersion; + final MethodChannel urlChannel; + final MethodChannel sshChannel; + + late final Future _ready = Future.wait([ + bootstrap.hostProvider.ready, + bootstrap.knownHosts.ready, + bootstrap.keyProvider.ready, + ]); + + /// Newest link wins while the app is locked: a flood of links cannot open a + /// pile of sessions once the user unlocks. + int _generation = 0; + + void attach() { + final server = CliServer( + handlers: MobileCliHandlers( + hostProvider: bootstrap.hostProvider, + appVersion: appVersion, + open: (host, source) => _whenUnlocked( + () => _openHost(host, source)), + ), + // Never written anywhere: only the in-process URL channel (trusted + // `open`) can reach this server. + token: generateToken(), + ready: _ready, + onUrlRefused: (url, reason) { + final n = linkRefusedNotification(url, reason); + _toast(n.title); + }, + ); + UrlChannel(server: server, channel: urlChannel).attach(); + + final ssh = SshLinkHandler( + hosts: () => bootstrap.hostProvider.allHosts, + enabled: () async => + (await SharedPreferences.getInstance()).getBool(kSshLinksPrefKey) ?? + false, + openSaved: (host) => + _whenUnlocked(() => _openHost(host, 'url')), + confirm: _confirm, + addHost: (prefill) => unawaited(_whenUnlocked(() async { + final nav = navigator.currentState; + if (nav == null) return; + nav.popUntil((r) => r.isFirst); + await nav.push(MaterialPageRoute( + builder: (_) => MobileAddHostScreen(prefill: prefill))); + })), + refused: _toast, + ); + sshChannel.setMethodCallHandler((call) async { + if (call.method != 'open' || call.arguments is! String) return; + try { + await _ready.timeout(CliServer.defaultReadyTimeout); + await ssh.handle(call.arguments as String); + } catch (e) { + debugPrint('[ssh-url] failed: $e'); + } + }); + // Flush URLs the native side queued before Dart listened. + sshChannel.invokeMethod('ready').catchError((Object _) {}); + } + + Future _openHost(Host host, String source) async { + final nav = navigator.currentState; + if (nav == null) return; + await openSession(nav, host, auditSource: source, resetStack: true); + } + + Future _confirm(SshLinkTarget t) async { + final ctx = navigator.currentContext; + if (ctx == null) return false; + // Nothing is shown while locked; wait, but let a newer link supersede. + var ok = false; + await _whenUnlocked(() async { + final c = navigator.currentContext; + if (c == null) return; + ok = await showYsConfirm( + c, + title: 'Open ssh:// link?', + message: + 'A link wants to add ${sanitize(t.query)} as a new host. Nothing ' + 'is saved or connected until you review and save it.', + confirmLabel: 'Review', + ); + }); + return ok; + } + + /// Runs [action] now, or once the app is unlocked; dropped if a newer link + /// arrived meanwhile. + Future _whenUnlocked(Future Function() action) async { + final mine = ++_generation; + if (mobileAppLocked.value) { + final done = Completer(); + void listener() { + if (!mobileAppLocked.value && !done.isCompleted) done.complete(); + } + + mobileAppLocked.addListener(listener); + try { + await done.future; + } finally { + mobileAppLocked.removeListener(listener); + } + if (mine != _generation) return; + } + await action(); + } + + void _toast(String message) { + final ctx = navigator.currentContext; + if (ctx != null) AppSnack.error(ctx, message); + } +} diff --git a/app/lib/mobile/links/ssh_link.dart b/app/lib/mobile/links/ssh_link.dart new file mode 100644 index 00000000..586a524d --- /dev/null +++ b/app/lib/mobile/links/ssh_link.dart @@ -0,0 +1,135 @@ +import '../../models/host.dart'; +import '../../services/cli/cli_server.dart'; +import '../../services/cli/host_resolver.dart'; + +/// Longest `ssh://` link considered at all. +const int kMaxSshLinkLength = 2048; + +/// `user@host[:port]` from an `ssh://` link. +class SshLinkTarget { + const SshLinkTarget(this.user, this.host, this.port); + + final String user; + + /// Hostname, IPv4 or IPv6 (without brackets). + final String host; + final int port; + + /// The query [resolveHost] understands (`user@host:port`, IPv6 bracketed). + String get query => '$user@${host.contains(':') ? '[$host]' : host}:$port'; + + /// Display form, identical to [query]. + @override + String toString() => query; +} + +// user: [A-Za-z0-9._-]+; host: DNS name / IPv4 or [IPv6]; optional port and a +// single trailing slash. Nothing else: no password, `;` parameters, path, +// query or fragment. `$` (no multiLine) only matches at the very end, so a +// trailing newline does not slip through. +final _sshLink = RegExp( + r'^ssh://([A-Za-z0-9._-]+)@(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9.-]+)(?::(\d{1,5}))?/?$', + caseSensitive: false); + +/// Parses `ssh://user@host[:port]` (optional trailing `/`); null for anything +/// else. Never throws. +SshLinkTarget? parseSshLink(String url) { + if (url.length > kMaxSshLinkLength) return null; + final m = _sshLink.firstMatch(url); + if (m == null) return null; + final user = m.group(1)!; + var host = m.group(2)!; + if (host.startsWith('[')) host = host.substring(1, host.length - 1); + final port = m.group(3) == null ? 22 : int.parse(m.group(3)!); + if (port < 1 || port > 65535) return null; + // A leading '-' could be parsed as an ssh option downstream. + if (user.startsWith('-') || host.startsWith('-') || host.isEmpty) return null; + return SshLinkTarget(user, host, port); +} + +/// Decides what an `ssh://` link may do: open a saved host, or after an +/// explicit confirmation prefill (never save, never connect) a new host. +class SshLinkHandler { + SshLinkHandler({ + required this.hosts, + required this.enabled, + required this.openSaved, + required this.confirm, + required this.addHost, + required this.refused, + this.now = DateTime.now, + }); + + final List Function() hosts; + final Future Function() enabled; + final Future Function(Host host) openSaved; + final Future Function(SshLinkTarget t) confirm; + final void Function(Host prefill) addHost; + + /// Shows a refusal. Messages are fixed strings: the link text is never + /// echoed (it comes from another app or a web page). + final void Function(String message) refused; + final DateTime Function() now; + + final Map _recent = {}; + bool _confirming = false; + + Future handle(String url) async { + if (url.length > kMaxSshLinkLength) { + refused('ssh:// link refused: too long'); + return; + } + if (_isRepeat(url)) return; + if (!await enabled()) { + refused('ssh:// links are off (Settings › Security)'); + return; + } + final t = parseSshLink(url); + if (t == null) { + refused('ssh:// link refused: only ssh://user@host[:port] is supported'); + return; + } + switch (resolveHost(t.query, hosts(), allowAdHoc: true)) { + case ResolvedHost(:final host): + // The resolver also matches by label: a host merely LABELLED + // "user@host:port" must not stand in for a different target. + if (host.username != t.user || + host.host.toLowerCase() != t.host.toLowerCase() || + host.port != t.port) { + refused('ssh:// link refused: no saved host for that target'); + return; + } + await openSaved(host); + case AmbiguousHost(): + refused('ssh:// link refused: several saved hosts match'); + case UnknownHost(): + refused('ssh:// link refused'); + case AdHocTarget(): + if (_confirming) { + refused('ssh:// link refused: another link is waiting for an answer'); + return; + } + _confirming = true; + try { + if (!await confirm(t)) return; + } finally { + _confirming = false; + } + addHost(Host( + label: '${t.user}@${t.host}', + host: t.host, + port: t.port, + username: t.user, + )); + } + } + + bool _isRepeat(String url) { + final key = url.toLowerCase(); + final t = now(); + _recent.removeWhere((_, at) => t.difference(at) >= CliServer.dedupeWindow); + if (_recent.containsKey(key)) return true; + _recent[key] = t; + return false; + } +} diff --git a/app/lib/mobile/mobile_app.dart b/app/lib/mobile/mobile_app.dart index 440ddccd..aab3c68e 100644 --- a/app/lib/mobile/mobile_app.dart +++ b/app/lib/mobile/mobile_app.dart @@ -1,6 +1,11 @@ import 'package:flutter/material.dart'; +import 'package:package_info_plus/package_info_plus.dart'; import 'package:provider/provider.dart'; +import '../platform/runtime_platform.dart'; +import 'lifecycle/background_tasks.dart'; +import 'lifecycle/mobile_lifecycle_coordinator.dart'; +import 'links/mobile_links.dart'; import 'mobile_bootstrap.dart'; import 'screens/mobile_home_shell.dart'; import 'security/app_lock_gate.dart'; @@ -20,9 +25,47 @@ class YourSSHMobileApp extends StatefulWidget { class _YourSSHMobileAppState extends State { final _bootstrap = MobileBootstrap(); + MobileLifecycleCoordinator? _lifecycle; + AppLifecycleListener? _lifecycleListener; + + @override + void initState() { + super.initState(); + // iOS only: the OS suspends the app and kills its sockets shortly after it + // leaves the foreground. Android keeps today's behavior (no coordinator). + if (isIOSPlatform) { + final c = _lifecycle = MobileLifecycleCoordinator( + sessions: _bootstrap.sessions, + forwards: _bootstrap.portForwardService, + forwardRules: _bootstrap.portForwardProvider, + tasks: MethodChannelBackgroundTasks(), + ); + // `inactive` (Face ID sheet, Control Center) is deliberately not handled. + _lifecycleListener = AppLifecycleListener( + onPause: c.onBackground, + onResume: c.onForeground, + ); + // yourssh:// and ssh:// links: attach after the first frame, when the + // navigator exists; the native side holds earlier URLs until then. + WidgetsBinding.instance.addPostFrameCallback((_) async { + String version = ''; + try { + version = (await PackageInfo.fromPlatform()).version; + } catch (_) {} + if (!mounted) return; + MobileLinks( + bootstrap: _bootstrap, + navigator: _bootstrap.navigatorKey, + appVersion: version, + ).attach(); + }); + } + } @override void dispose() { + _lifecycleListener?.dispose(); + _lifecycle?.dispose(); _bootstrap.dispose(); super.dispose(); } @@ -32,6 +75,7 @@ class _YourSSHMobileAppState extends State { return MultiProvider( providers: _bootstrap.providers, child: MaterialApp( + navigatorKey: _bootstrap.navigatorKey, title: 'YourSSH', debugShowCheckedModeBanner: false, themeMode: ThemeMode.dark, diff --git a/app/lib/mobile/mobile_bootstrap.dart b/app/lib/mobile/mobile_bootstrap.dart index d006bee4..78f6aa1a 100644 --- a/app/lib/mobile/mobile_bootstrap.dart +++ b/app/lib/mobile/mobile_bootstrap.dart @@ -1,9 +1,12 @@ import 'dart:async'; +import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:provider/single_child_widget.dart'; import 'package:yourssh_snippets/yourssh_snippets.dart'; +import '../platform/runtime_platform.dart'; +import '../util/native_chmod.dart'; import '../providers/host_provider.dart'; import '../providers/key_provider.dart'; import '../providers/known_hosts_provider.dart'; @@ -12,6 +15,7 @@ import '../providers/session_provider.dart'; import '../providers/settings_provider.dart'; import '../providers/sync_provider.dart'; import '../services/key_gen_service.dart'; +import '../theme/app_theme.dart' show AppSnack; import '../services/port_forward_service.dart'; import '../services/sftp_transfer_service.dart'; import '../services/ssh_service.dart'; @@ -39,8 +43,11 @@ class MobileBootstrap { late final PortForwardService portForwardService; late final KeyGenService keyGen; + /// Navigator key of the mobile MaterialApp, for toasts raised outside the tree. + final navigatorKey = GlobalKey(); + MobileBootstrap() { - storage = StorageService(); + storage = StorageService(allowPlaintextFallback: !isIOSPlatform); ssh = SshService(storage); hostProvider = HostProvider(storage); keyProvider = KeyProvider() @@ -63,7 +70,7 @@ class MobileBootstrap { portForwardProvider.setStatus(id, status, error: error), onConnections: (id, n) => portForwardProvider.setConnections(id, n), ); - keyGen = KeyGenService(); + keyGen = KeyGenService(chmod: supportsSubprocesses ? null : chmodNative); hostProvider.onHostDeleted = (id) => unawaited(portForwardService.stopForHost(id)); unawaited(portForwardProvider.ready.then( @@ -82,6 +89,12 @@ class MobileBootstrap { sessions.hostKeyVerifier = knownHosts.verifyHostKey; sessions.onOsDetected = (id, os) => hostProvider.updateDetectedOs(id, os); + ssh.onSudoPasswordNotSaved = (_) { + final ctx = navigatorKey.currentContext; + if (ctx != null) { + AppSnack.error(ctx, 'Could not save the sudo password to the iOS Keychain'); + } + }; ssh.defaultHostKeyVerifier = knownHosts.verifyHostKey; ssh.defaultKeyLookup = (id) => keyProvider.findById(id); ssh.defaultJumpHostLookup = diff --git a/app/lib/mobile/navigation/open_session.dart b/app/lib/mobile/navigation/open_session.dart new file mode 100644 index 00000000..d7aab343 --- /dev/null +++ b/app/lib/mobile/navigation/open_session.dart @@ -0,0 +1,64 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../../models/host.dart'; +import '../../platform/runtime_platform.dart'; +import '../../providers/session_provider.dart'; +import '../../theme/app_theme.dart'; +import '../screens/mobile_port_forward_screen.dart'; +import '../screens/mobile_sftp_screen.dart'; +import '../screens/mobile_terminal_screen.dart'; + +/// Whether [host] can be opened on this platform: SSH everywhere, RDP/VNC only +/// where [supportsRemoteDesktop] is true. +bool canOpenOnMobile(Host host) => + host.protocol == HostProtocol.ssh || supportsRemoteDesktop; + +/// Opens [host] in the mobile terminal: reuses its live SSH session or starts a +/// new one, then pushes [MobileTerminalScreen]. [resetStack] pops to the first +/// route before pushing (used by links). [SessionProvider] is read from +/// `nav.context` (the providers sit above `MaterialApp`). +Future openMobileSession( + NavigatorState nav, + Host host, { + String auditSource = 'app', + bool resetStack = false, +}) async { + if (!canOpenOnMobile(host)) { + AppSnack.info(nav.context, 'RDP and VNC hosts open in the desktop app'); + return; + } + final sp = nav.context.read(); + + final existing = sp.sshSessions.where((s) => s.host.id == host.id).toList(); + String? sessionId; + if (existing.isNotEmpty) { + sessionId = existing.last.id; + } else { + // The connect future must NOT be awaited: SessionProvider._doConnect awaits + // SshService.openShell, which only completes once the shell closes, so + // awaiting it would strand the user on the host list for the whole session. + // The session is registered synchronously, so the terminal can pick it up + // now and render its own connecting state. + unawaited(sp.connectAny(host, auditSource: auditSource)); + final after = sp.sshSessions.where((s) => s.host.id == host.id).toList(); + sessionId = after.isNotEmpty ? after.last.id : null; + } + if (!nav.mounted) return; + if (resetStack) nav.popUntil((r) => r.isFirst); + await nav.push( + MaterialPageRoute( + builder: (ctx) => MobileTerminalScreen( + focusSessionId: sessionId, + onOpenFiles: (h) => Navigator.of(ctx).push( + MaterialPageRoute(builder: (_) => MobileSftpScreen(host: h)), + ), + onOpenPortForward: (h) => Navigator.of(ctx).push( + MaterialPageRoute(builder: (_) => MobilePortForwardScreen(host: h)), + ), + ), + ), + ); +} diff --git a/app/lib/mobile/screens/mobile_add_host_screen.dart b/app/lib/mobile/screens/mobile_add_host_screen.dart index 6c7917e7..75be79f6 100644 --- a/app/lib/mobile/screens/mobile_add_host_screen.dart +++ b/app/lib/mobile/screens/mobile_add_host_screen.dart @@ -3,6 +3,8 @@ import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:yourssh_ui/yourssh_ui.dart'; +import '../../services/storage_service.dart'; +import '../../theme/app_theme.dart'; import '../../models/host.dart'; import '../../models/ssh_key.dart'; import '../../providers/host_provider.dart'; @@ -24,7 +26,12 @@ class MobileAddHostScreen extends StatefulWidget { /// The host to edit, or null to create a new one. final Host? existing; - const MobileAddHostScreen({super.key, this.existing}); + /// Seeds a NEW host form (label/host/port/username) from [prefill], e.g. an + /// `ssh://` link. Ignored when [existing] is set; nothing is saved until the + /// user taps Save. + final Host? prefill; + + const MobileAddHostScreen({super.key, this.existing, this.prefill}); @override State createState() => _MobileAddHostScreenState(); @@ -85,6 +92,11 @@ class _MobileAddHostScreenState extends State { // Group = first tag (round-trip: save writes it back as the first tag). _group.text = h.tags.isNotEmpty ? h.tags.first : ''; _snippet.text = h.startupSnippet ?? ''; + } else if (widget.prefill case final p?) { + _label.text = p.label; + _address.text = p.host; + _port.text = '${p.port}'; + _username.text = p.username; } } @@ -186,13 +198,24 @@ class _MobileAddHostScreenState extends State { Future _save() async { if (!_canSave) return; - await _doSave(); + try { + await _doSave(); + } on SecretStoreException { + if (mounted) AppSnack.error(context, 'Could not save to the iOS Keychain'); + return; + } if (mounted) Navigator.of(context).pop(); } Future _saveAndConnect() async { if (!_canSave) return; - final savedId = await _doSave(); + final String savedId; + try { + savedId = await _doSave(); + } on SecretStoreException { + if (mounted) AppSnack.error(context, 'Could not save to the iOS Keychain'); + return; + } if (!mounted) return; // Use the id returned by _doSave — deterministic, no .last assumption. final host = context.read().byId(savedId); diff --git a/app/lib/mobile/screens/mobile_hosts_screen.dart b/app/lib/mobile/screens/mobile_hosts_screen.dart index a6ad28ed..04fcd236 100644 --- a/app/lib/mobile/screens/mobile_hosts_screen.dart +++ b/app/lib/mobile/screens/mobile_hosts_screen.dart @@ -9,6 +9,7 @@ import '../../models/ssh_session.dart'; import '../../providers/host_provider.dart'; import '../../providers/session_provider.dart'; import '../../util/host_query.dart'; +import '../navigation/open_session.dart'; import '../services/host_reachability_probe.dart'; import '../theme/mobile_theme.dart'; import '../theme/mobile_tokens.dart'; @@ -19,9 +20,6 @@ import '../widgets/section_header.dart'; import '../widgets/status_dot.dart'; import '../widgets/tag_chip.dart'; import 'mobile_add_host_screen.dart'; -import 'mobile_port_forward_screen.dart'; -import 'mobile_sftp_screen.dart'; -import 'mobile_terminal_screen.dart'; /// Hosts tab: header + search + folder chips + tag-grouped list + amber FAB. /// Tap a host → connect via SessionProvider. Long-press → edit/delete sheet. @@ -300,77 +298,13 @@ class _MobileHostsScreenState extends State { connecting: connState == HostConnState.connecting || ping.state == HostReachState.probing, latencyMs: ping.ms, - onTap: () => _openSession(host), + onTap: () => openMobileSession(Navigator.of(context), host), onLongPress: () => _showActions(host), ); } // ── Actions ────────────────────────────────────────────────────────────── - Future _openSession(Host host) async { - final sp = context.read(); - - // Re-entry: if a live session exists for this host, just open the terminal. - final existing = sp.sshSessions - .where((s) => s.host.id == host.id) - .toList(); - if (existing.isNotEmpty) { - final sessionId = existing.last.id; - if (!mounted) return; - await Navigator.of(context).push( - MaterialPageRoute( - builder: (ctx) => MobileTerminalScreen( - focusSessionId: sessionId, - onOpenFiles: (h) => _pushSftp(ctx, h), - onOpenPortForward: (h) => _pushPortForward(ctx, h), - ), - ), - ); - return; - } - - // No live session — start connecting and navigate straight away. The - // connect future must NOT be awaited: SessionProvider._doConnect awaits - // SshService.openShell, which only completes once the shell closes, so - // awaiting it would strand the user on the host list for the whole session. - // The session is registered synchronously, so the terminal can pick it up - // now and render its own connecting state. - unawaited(sp.connectAny(host)); - if (!mounted) return; - - // The session is in sshSessions already; find the freshest one. - final after = sp.sshSessions - .where((s) => s.host.id == host.id) - .toList(); - final sessionId = after.isNotEmpty ? after.last.id : null; - - await Navigator.of(context).push( - MaterialPageRoute( - builder: (ctx) => MobileTerminalScreen( - focusSessionId: sessionId, - onOpenFiles: (h) => _pushSftp(ctx, h), - onOpenPortForward: (h) => _pushPortForward(ctx, h), - ), - ), - ); - } - - void _pushSftp(BuildContext ctx, Host host) { - Navigator.of(ctx).push( - MaterialPageRoute( - builder: (_) => MobileSftpScreen(host: host), - ), - ); - } - - void _pushPortForward(BuildContext ctx, Host host) { - Navigator.of(ctx).push( - MaterialPageRoute( - builder: (_) => MobilePortForwardScreen(host: host), - ), - ); - } - void _pushAddHost() { Navigator.of(context).push( MaterialPageRoute(builder: (_) => const MobileAddHostScreen()), diff --git a/app/lib/mobile/screens/mobile_keys_screen.dart b/app/lib/mobile/screens/mobile_keys_screen.dart index 594ffa48..dd64da53 100644 --- a/app/lib/mobile/screens/mobile_keys_screen.dart +++ b/app/lib/mobile/screens/mobile_keys_screen.dart @@ -1,14 +1,16 @@ -import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; -import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; +import '../../services/storage_service.dart'; +import '../../theme/app_theme.dart'; import '../../models/ssh_key.dart'; import '../../providers/host_provider.dart'; import '../../providers/key_provider.dart'; import '../../services/key_gen_service.dart'; +import '../files/app_paths.dart'; +import '../files/file_export.dart'; import '../theme/mobile_theme.dart'; import '../theme/mobile_tokens.dart'; import '../widgets/key_card.dart'; @@ -149,10 +151,25 @@ class MobileKeysScreen extends StatelessWidget { if (!context.mounted) return; final keyProv = context.read(); - final entry = await keyProv.addKeyFromFile(path, result.files.first.name); - - if (passphrase.isNotEmpty && context.mounted) { - await keyProv.savePassphrase?.call(entry.id, passphrase); + try { + // Copy the key into the private keys dir (not Documents, which the Files + // app exposes) and register the copy; the picker's temp copy is cleared. + final copy = await importPrivateKey(path, await AppPaths.privateKeysDir()); + final entry = await keyProv.addKeyFromFile(copy.path, result.files.first.name); + + if (passphrase.isNotEmpty && context.mounted) { + try { + await keyProv.savePassphrase?.call(entry.id, passphrase); + } on SecretStoreException { + if (context.mounted) AppSnack.error(context, 'Could not save to the iOS Keychain'); + } + } + } catch (e) { + if (context.mounted) AppSnack.error(context, 'Could not import key: $e'); + } finally { + try { + await FilePicker.platform.clearTemporaryFiles(); + } catch (_) {} } } @@ -255,7 +272,7 @@ class _GenerateSheetState extends State<_GenerateSheet> { final _nameCtrl = TextEditingController(); final _passphraseCtrl = TextEditingController(); String _algo = 'ed25519'; - bool _sshKeygenAvailable = false; + bool _sshKeygenAvailable = false; // true when RSA/ECDSA are offered bool _loading = false; String? _error; @@ -266,8 +283,8 @@ class _GenerateSheetState extends State<_GenerateSheet> { } Future _probe() async { - final available = await context.read().probeSshKeygen(); - if (mounted) setState(() => _sshKeygenAvailable = available); + final algos = await context.read().supportedAlgorithms(); + if (mounted) setState(() => _sshKeygenAvailable = algos.contains('rsa')); } @override @@ -309,7 +326,11 @@ class _GenerateSheetState extends State<_GenerateSheet> { if (!mounted) return; final entry = await keyProv.addKeyFromFile(result.privateKeyPath, name); if (_passphraseCtrl.text.isNotEmpty && mounted) { - await keyProv.savePassphrase?.call(entry.id, _passphraseCtrl.text); + try { + await keyProv.savePassphrase?.call(entry.id, _passphraseCtrl.text); + } on SecretStoreException { + if (mounted) AppSnack.error(context, 'Could not save to the iOS Keychain'); + } } if (mounted) Navigator.pop(context); } catch (e) { @@ -320,10 +341,7 @@ class _GenerateSheetState extends State<_GenerateSheet> { } Future _keysDir() async { - final docs = await getApplicationDocumentsDirectory(); - final dir = Directory('${docs.path}/YourSSH/keys'); - if (!dir.existsSync()) dir.createSync(recursive: true); - return dir.path; + return (await AppPaths.privateKeysDir()).path; } @override diff --git a/app/lib/mobile/screens/mobile_qr_scan_screen.dart b/app/lib/mobile/screens/mobile_qr_scan_screen.dart index cfd68331..44de9d90 100644 --- a/app/lib/mobile/screens/mobile_qr_scan_screen.dart +++ b/app/lib/mobile/screens/mobile_qr_scan_screen.dart @@ -3,6 +3,7 @@ import 'package:mobile_scanner/mobile_scanner.dart'; import 'package:provider/provider.dart'; import 'package:yourssh_ui/yourssh_ui.dart'; +import '../../services/storage_service.dart'; import '../../providers/host_provider.dart'; import '../../services/p2p_sync_encryption.dart'; import '../../services/p2p_sync_service.dart'; @@ -58,6 +59,10 @@ class _MobileQrScanScreenState extends State { if (mounted) { Navigator.of(context).pop('Imported ${payload.hosts.length} hosts'); } + } on SecretStoreException { + if (mounted) { + Navigator.of(context).pop('Could not save to the iOS Keychain'); + } } catch (e) { if (mounted) { Navigator.of(context).pop( diff --git a/app/lib/mobile/screens/mobile_settings_screen.dart b/app/lib/mobile/screens/mobile_settings_screen.dart index 17baa5e3..0b821d18 100644 --- a/app/lib/mobile/screens/mobile_settings_screen.dart +++ b/app/lib/mobile/screens/mobile_settings_screen.dart @@ -4,6 +4,8 @@ import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh_ui/yourssh_ui.dart'; +import '../../platform/runtime_platform.dart'; +import '../../providers/settings_provider.dart'; import '../../providers/sync_provider.dart'; import '../../widgets/terminal_appearance_controls.dart'; import '../security/app_lock_gate.dart'; @@ -28,6 +30,7 @@ class MobileSettingsScreen extends StatefulWidget { class _MobileSettingsScreenState extends State { // ── Security ────────────────────────────────────────────────────────────── bool _appLock = true; + bool _sshLinks = false; // ── Keyboard ────────────────────────────────────────────────────────────── bool _accessoryBar = true; @@ -42,6 +45,7 @@ class _MobileSettingsScreenState extends State { if (mounted) { setState(() { _appLock = p.getBool(kAppLockPrefKey) ?? true; + _sshLinks = p.getBool(kSshLinksPrefKey) ?? false; _accessoryBar = p.getBool(kAccessoryBarPrefKey) ?? true; }); } @@ -133,6 +137,7 @@ class _MobileSettingsScreenState extends State { // ── TERMINAL group ──────────────────────────────────────────────────────── Widget _terminalGroup() { + final settings = context.watch(); return ListGroup( label: 'Terminal', children: [ @@ -142,6 +147,13 @@ class _MobileSettingsScreenState extends State { layout: AppearanceControlsLayout.rows, ), ), + SettingsRow( + leading: const Icon(FLucideIcons.layers, + color: YsColors.mutedForeground, size: 20), + title: 'Keep sessions in tmux', + toggle: settings.tmuxEnabled, + onToggle: (v) => settings.save(tmuxEnabled: v), + ), ], ); } @@ -162,6 +174,18 @@ class _MobileSettingsScreenState extends State { await p.setBool(kAppLockPrefKey, v); }, ), + if (isIOSPlatform) + SettingsRow( + leading: const Icon(FLucideIcons.link, + color: YsColors.mutedForeground, size: 20), + title: 'Open ssh:// links', + toggle: _sshLinks, + onToggle: (v) async { + setState(() => _sshLinks = v); + final p = await SharedPreferences.getInstance(); + await p.setBool(kSshLinksPrefKey, v); + }, + ), SettingsRow( leading: const Icon(FLucideIcons.timer, color: MobileColors.textMuted, size: 20), title: 'Auto-lock', diff --git a/app/lib/mobile/screens/mobile_sftp_screen.dart b/app/lib/mobile/screens/mobile_sftp_screen.dart index 03556654..b6faa7df 100644 --- a/app/lib/mobile/screens/mobile_sftp_screen.dart +++ b/app/lib/mobile/screens/mobile_sftp_screen.dart @@ -7,6 +7,10 @@ import 'package:path/path.dart' as p; import 'package:provider/provider.dart'; import '../../models/host.dart'; +import '../../platform/runtime_platform.dart'; +import '../files/app_paths.dart'; +import '../files/file_export.dart'; +import '../../providers/session_provider.dart'; import '../../services/sftp_transfer_service.dart'; import '../../services/ssh_service.dart'; import '../theme/mobile_theme.dart'; @@ -27,12 +31,31 @@ class MobileSftpScreen extends StatefulWidget { /// tree can be pumped without a real SSH connection. final Future> Function(String path)? lister; - const MobileSftpScreen({super.key, required this.host, this.lister}); + /// Optional override for opening the SFTP channel — injected in tests. + final Future Function()? sftpOpener; + + const MobileSftpScreen({ + super.key, + required this.host, + this.lister, + this.sftpOpener, + }); @override State createState() => _MobileSftpScreenState(); } +/// True when [e] means the SFTP channel or its SSH connection is gone (closed +/// socket, aborted channel, closed stream) rather than that one operation was +/// refused (`SftpStatusError`) or failed locally (`FileSystemException`). +bool isDeadChannelError(Object e) => + e is io.SocketException || + e is SSHSocketError || + e is SSHStateError || + e is SSHChannelOpenError || + e is SftpAbortError || + e is StateError; + enum _SortField { name, size } class _MobileSftpScreenState extends State { @@ -65,14 +88,51 @@ class _MobileSftpScreenState extends State { Future _client() async { if (_sftp != null) return _sftp!; - _sftp = await context.read().openSftp(widget.host); - return _sftp!; + final opener = widget.sftpOpener; + final sftp = opener != null + ? await opener() + : await context.read().openSftp(widget.host); + return _sftp = sftp; + } + + /// Drops the cached channel. The connection may have been closed while the + /// app was paused in the background, which leaves the channel dead. + void _dropClient() { + final old = _sftp; + _sftp = null; + try { + old?.close(); + } catch (_) {} + } + + bool _sessionsPaused() { + try { + return context.read().hasPausedSessions; + } on ProviderNotFoundException { + return false; + } + } + + /// Runs [op] on the cached channel. Only when it fails because the channel + /// or connection is dead ([isDeadChannelError]) is the channel discarded and + /// [op] retried once on a fresh one (reconnecting if the session was paused). + /// Server status errors and local I/O errors propagate untouched. + Future _withSftp(Future Function(SftpClient sftp) op) async { + try { + return await op(await _client()); + } catch (e) { + if (!isDeadChannelError(e)) rethrow; + _dropClient(); + // Paused for the background: the host is closed on purpose, and a + // re-dial now would race the resume. Fail cleanly instead. + if (!mounted || _sessionsPaused()) rethrow; + return await op(await _client()); + } } Future> _listDir(String path) async { if (widget.lister != null) return widget.lister!(path); - final sftp = await _client(); - return sftp.listdir(path); + return _withSftp((sftp) => sftp.listdir(path)); } Future _load(String path) async { @@ -197,45 +257,68 @@ class _MobileSftpScreenState extends State { // ── Transfer ops ────────────────────────────────────────────────────────── Future _download(SftpName e) async { - final dir = await FilePicker.platform.getDirectoryPath(); - if (dir == null) return; final String localPath; try { - localPath = safeLocalChild(dir, e.filename); + final dir = isIOSPlatform + ? (await AppPaths.downloadsDir()).path + : await FilePicker.platform.getDirectoryPath(); + if (dir == null) return; + localPath = uniqueLocalPath(dir, e.filename); } on UnsafeRemotePathException catch (err) { _snack('$err'); return; } - final sink = io.File(localPath).openWrite(); try { - final sftp = await _client(); - final file = await sftp.open(_join(e.filename)); - await for (final chunk in file.read()) { - sink.add(chunk); - } - await file.close(); - _snack('Downloaded ${e.filename}'); + await _withSftp((sftp) async { + final file = await sftp.open(_join(e.filename)); + try { + await writeDownload(file.read(), localPath); + } finally { + await file.close(); + } + }); } catch (err) { _snack('Download failed: $err'); - } finally { - await sink.close(); + return; + } + if (!mounted) return; + if (isIOSPlatform) { + showYsToast( + context, + 'Downloaded ${p.basename(localPath)}', + kind: YsToastKind.success, + actionLabel: 'Share', + onAction: () { + if (mounted) shareFile(context, localPath); + }, + ); + } else { + _snack('Downloaded ${p.basename(localPath)}'); } } Future _upload() async { final transfer = context.read(); - final picked = await FilePicker.platform.pickFiles(); - final localPath = picked == null || picked.files.isEmpty - ? null - : picked.files.first.path; - if (localPath == null) return; - final name = p.basename(localPath); + String? localPath; try { - await transfer.uploadFile(widget.host, localPath, _join(name)); - _snack('Uploaded $name'); - _load(_path); - } catch (err) { - _snack('Upload failed: $err'); + final picked = await FilePicker.platform.pickFiles(); + localPath = picked == null || picked.files.isEmpty + ? null + : picked.files.first.path; + if (localPath == null) return; + final name = p.basename(localPath); + try { + await transfer.uploadFile(widget.host, localPath, _join(name)); + _snack('Uploaded $name'); + _load(_path); + } catch (err) { + _snack('Upload failed: $err'); + } + } finally { + // The picker copies the file into the app's temp dir; drop that copy. + try { + await FilePicker.platform.clearTemporaryFiles(); + } catch (_) {} } } diff --git a/app/lib/mobile/screens/mobile_snippets_screen.dart b/app/lib/mobile/screens/mobile_snippets_screen.dart index 30df4e8f..e65686d2 100644 --- a/app/lib/mobile/screens/mobile_snippets_screen.dart +++ b/app/lib/mobile/screens/mobile_snippets_screen.dart @@ -130,7 +130,10 @@ class _MobileSnippetsScreenState extends State { AppSnack.info(context, 'No active session'); return; } - context.read().sendInput(sessionId, '${snippet.command}\n'); + final sent = context + .read() + .sendInput(sessionId, '${snippet.command}\n'); + if (!sent) AppSnack.info(context, 'Session is not connected'); } } diff --git a/app/lib/mobile/screens/mobile_sync_screen.dart b/app/lib/mobile/screens/mobile_sync_screen.dart index f09dd3d7..cb80ba97 100644 --- a/app/lib/mobile/screens/mobile_sync_screen.dart +++ b/app/lib/mobile/screens/mobile_sync_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qr_flutter/qr_flutter.dart'; +import '../../services/storage_service.dart'; import '../../providers/host_provider.dart'; import '../../providers/sync_provider.dart'; import '../../services/p2p_sync_encryption.dart'; @@ -104,7 +105,12 @@ class _MobileSyncScreenState extends State { setState(() => _configError = null); final sync = context.read(); await sync.setSupabaseConfig(url, anonKey); - await sync.setSyncCode(_code.text); + try { + await sync.setSyncCode(_code.text); + } on SecretStoreException { + if (mounted) AppSnack.error(context, 'Could not save to the iOS Keychain'); + return; + } if (mounted) { setState(() => _editingConfig = false); AppSnack.success(context, 'Sync settings saved'); @@ -131,6 +137,8 @@ class _MobileSyncScreenState extends State { final err = context.read().error; AppSnack.info(context, err ?? 'Nothing new to pull'); } + } on SecretStoreException { + if (mounted) AppSnack.error(context, 'Could not save to the iOS Keychain'); } finally { if (mounted) setState(() => _pulling = false); } @@ -185,6 +193,15 @@ class _MobileSyncScreenState extends State { setState(() => _secondsLeft--); }); + _p2p.onInterrupted = () { + _countdown?.cancel(); + if (mounted) { + setState(() { + _qrData = null; + _qrStatus = 'Code expired — paused in the background'; + }); + } + }; _p2p.onServerError = (e) { if (mounted) setState(() => _qrStatus = 'Transfer error: $e'); }; diff --git a/app/lib/mobile/screens/mobile_terminal_screen.dart b/app/lib/mobile/screens/mobile_terminal_screen.dart index 272c3c07..1bd34424 100644 --- a/app/lib/mobile/screens/mobile_terminal_screen.dart +++ b/app/lib/mobile/screens/mobile_terminal_screen.dart @@ -9,8 +9,10 @@ import '../../models/ssh_session.dart'; import '../../providers/host_provider.dart'; import '../../providers/session_provider.dart'; import '../../providers/settings_provider.dart'; +import '../../theme/app_theme.dart' show AppSnack; import '../../theme/terminal_themes.dart'; import '../../util/terminal_appearance.dart'; +import '../navigation/open_session.dart'; import '../terminal/accessory_bar_controller.dart'; import '../terminal/accessory_key_bar.dart'; import '../terminal/terminal_cursor_gestures.dart'; @@ -113,9 +115,20 @@ class _MobileTerminalScreenState extends State { showTerminalSidePanel( context, sessionId: active.id, - onInsert: (cmd) => active.terminal.textInput(cmd), - onKey: (k, {ctrl = false, alt = false}) => - active.terminal.keyInput(k, ctrl: ctrl, alt: alt), + onInsert: (cmd) { + if (!active.acceptsInput) { + AppSnack.info(context, 'Session is not connected'); + return; + } + active.terminal.textInput(cmd); + }, + onKey: (k, {ctrl = false, alt = false}) { + if (!active.acceptsInput) { + AppSnack.info(context, 'Session is not connected'); + return; + } + active.terminal.keyInput(k, ctrl: ctrl, alt: alt); + }, initialTab: initialTab, ); } @@ -166,7 +179,11 @@ class _MobileTerminalScreenState extends State { builder: (sheetCtx) { // Read hosts inside the builder so the list is live while the sheet // is open (not a stale snapshot captured before the sheet opened). - final hosts = sheetCtx.read().allHosts; + final hosts = sheetCtx + .read() + .allHosts + .where(canOpenOnMobile) + .toList(); return SafeArea( top: false, child: Column( @@ -560,7 +577,7 @@ class _SessionBodyState extends State<_SessionBody> { @override Widget build(BuildContext context) { - if (widget.session.status == SessionStatus.connected) { + if (widget.session.acceptsInput) { return Column( children: [ Expanded( @@ -619,7 +636,9 @@ class _SessionBodyState extends State<_SessionBody> { child: FCircularProgress(), ), Text( - widget.session.statusLabel, + widget.session.paused + ? 'Session paused — reconnecting' + : widget.session.statusLabel, style: const TextStyle(color: MobileColors.textMuted), ), if (widget.session.errorMessage != null) ...[ diff --git a/app/lib/mobile/security/app_lock_gate.dart b/app/lib/mobile/security/app_lock_gate.dart index 2039cf90..54ec21ad 100644 --- a/app/lib/mobile/security/app_lock_gate.dart +++ b/app/lib/mobile/security/app_lock_gate.dart @@ -6,6 +6,13 @@ import 'package:yourssh_ui/yourssh_ui.dart'; const String kAppLockPrefKey = 'app_lock_enabled'; +/// True while the lock screen covers the app. Starts true: the app counts as +/// locked until the gate has decided (prefs read, device support) — never +/// fail open before that. The gate sits in `MaterialApp.builder`, so it covers +/// every route and dialog; link handlers still wait for this to turn false so +/// a link never opens a session before the user has unlocked. +final ValueNotifier mobileAppLocked = ValueNotifier(true); + /// Wraps the mobile app in a biometric lock. Locked on launch (and on /// resume-from-background) when enabled; unlocks on a successful auth. The /// [authenticator] and [enabledOverride] seams keep the state machine testable @@ -29,6 +36,11 @@ class AppLockGate extends StatefulWidget { class _AppLockGateState extends State with WidgetsBindingObserver { bool _enabled = false; bool _locked = false; + + /// False until [_init] has read the setting and device support. Until then + /// the child is kept offstage behind a blank screen, so a cold start never + /// paints the app before the lock is in place. + bool _decided = false; bool _authInFlight = false; @override @@ -41,6 +53,7 @@ class _AppLockGateState extends State with WidgetsBindingObserver { @override void dispose() { WidgetsBinding.instance.removeObserver(this); + mobileAppLocked.value = false; super.dispose(); } @@ -54,9 +67,11 @@ class _AppLockGateState extends State with WidgetsBindingObserver { final enabled = wantEnabled && await _canAuthenticate(); if (!mounted) return; setState(() { + _decided = true; _enabled = enabled; _locked = enabled; }); + mobileAppLocked.value = enabled; if (enabled) _authenticate(); } @@ -81,7 +96,10 @@ class _AppLockGateState extends State with WidgetsBindingObserver { case AppLifecycleState.paused: case AppLifecycleState.hidden: // Cover the app-switcher snapshot: lock before the OS captures it. - if (!_locked && mounted) setState(() => _locked = true); + if (!_locked && mounted) { + setState(() => _locked = true); + mobileAppLocked.value = true; + } case AppLifecycleState.resumed: if (_locked) _authenticate(); case AppLifecycleState.detached: @@ -105,7 +123,10 @@ class _AppLockGateState extends State with WidgetsBindingObserver { if (_authInFlight) return; _authInFlight = true; final ok = await (widget.authenticator ?? _defaultAuth)(); - if (mounted && ok) setState(() => _locked = false); + if (mounted && ok) { + setState(() => _locked = false); + mobileAppLocked.value = false; + } // Clear the guard one frame later, so the inactive→resumed transition that // accompanies dismissing the system biometric sheet is still ignored above // (otherwise it re-locks immediately after unlocking). @@ -114,7 +135,7 @@ class _AppLockGateState extends State with WidgetsBindingObserver { @override Widget build(BuildContext context) { - if (!_locked) return widget.child; + if (_decided && !_locked) return widget.child; // The child (navigator, pushed routes, dialogs, toasts) stays mounted so // sessions and routes survive the unlock, but offstage with tickers off: // nothing of it is painted, so neither the screen nor the app-switcher @@ -126,7 +147,10 @@ class _AppLockGateState extends State with WidgetsBindingObserver { Offstage( child: TickerMode(enabled: false, child: widget.child), ), - FTheme(data: ysThemeDataTouch(), child: _lockScreen()), + if (_decided) + FTheme(data: ysThemeDataTouch(), child: _lockScreen()) + else + const ColoredBox(color: YsColors.background), ], ); } diff --git a/app/lib/mobile/util/mobile_prefs.dart b/app/lib/mobile/util/mobile_prefs.dart index c99278bb..6bff898a 100644 --- a/app/lib/mobile/util/mobile_prefs.dart +++ b/app/lib/mobile/util/mobile_prefs.dart @@ -4,3 +4,6 @@ /// Whether the terminal accessory key bar is shown (default: true). /// Read by the terminal accessory bar widget; persisted here. const String kAccessoryBarPrefKey = 'mobile_accessory_bar_enabled'; + +/// Whether `ssh://` links may act (default: false). Read by `MobileLinks`. +const String kSshLinksPrefKey = 'mobile_ssh_links_enabled'; diff --git a/app/lib/models/ssh_session.dart b/app/lib/models/ssh_session.dart index 5c96da63..469b0d9f 100644 --- a/app/lib/models/ssh_session.dart +++ b/app/lib/models/ssh_session.dart @@ -14,6 +14,21 @@ class SshSession implements TerminalSession { @override final Terminal terminal; SessionStatus status; + + /// True while the app lifecycle logic (iOS background) has closed this + /// session's connection on purpose. A paused session is `disconnected`, is + /// never auto-reconnected by the drop path and is reconnected by + /// `SessionProvider.resumePaused` when the app returns to the foreground. + bool paused = false; + + /// Bumped whenever the provider invalidates in-flight connect attempts + /// (a pause); an attempt that finds a different value stops quietly. + int connectGeneration = 0; + + /// Whether keystrokes may reach the remote shell. Input to anything else is + /// rejected visibly by callers, never queued. + bool get acceptsInput => status == SessionStatus.connected && !paused; + String? errorMessage; DateTime connectedAt; final String? initialCommand; diff --git a/app/lib/platform/runtime_platform.dart b/app/lib/platform/runtime_platform.dart index 02981903..46d6f1ef 100644 --- a/app/lib/platform/runtime_platform.dart +++ b/app/lib/platform/runtime_platform.dart @@ -9,3 +9,15 @@ import 'package:flutter/foundation.dart'; bool get isMobilePlatform => defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS; + +/// True on iOS; consumed by the iOS-specific branches (no subprocess, App Store rules). +bool get isIOSPlatform => defaultTargetPlatform == TargetPlatform.iOS; + +/// Whether RDP/VNC tabs are offered; consumed by the host editor and dashboard (mobile until phase 3). +bool get supportsRemoteDesktop => !isMobilePlatform; + +/// Whether the platform can spawn child processes (local shell, ssh-keygen, cloudflared); false on iOS. +bool get supportsSubprocesses => !isIOSPlatform; + +/// Whether tmux persistence is on by default (flaky mobile links); consumed by SettingsProvider. +bool get mobileDefaultTmux => isMobilePlatform; diff --git a/app/lib/providers/host_provider.dart b/app/lib/providers/host_provider.dart index 2092c49d..f0a0d919 100644 --- a/app/lib/providers/host_provider.dart +++ b/app/lib/providers/host_provider.dart @@ -73,11 +73,12 @@ class HostProvider extends ChangeNotifier { } Future addHost(Host host, {String? password}) async { - _hosts.add(host); - await _storage.saveHosts(_hosts); + // Secret first: if the secure store refuses (iOS), no host is added. if (password != null && password.isNotEmpty) { await _storage.savePassword(host.id, password); } + _hosts.add(host); + await _storage.saveHosts(_hosts); notifyListeners(); await onMutation?.call(); } @@ -85,11 +86,11 @@ class HostProvider extends ChangeNotifier { Future updateHost(Host host, {String? password}) async { final idx = _hosts.indexWhere((h) => h.id == host.id); if (idx == -1) return; - _hosts[idx] = host; - await _storage.saveHosts(_hosts); if (password != null && password.isNotEmpty) { await _storage.savePassword(host.id, password); } + _hosts[idx] = host; + await _storage.saveHosts(_hosts); notifyListeners(); await onMutation?.call(); } @@ -125,15 +126,35 @@ class HostProvider extends ChangeNotifier { final oldIds = _hosts.map((h) => h.id).toSet(); final newIds = hosts.map((h) => h.id).toSet(); final removedIds = oldIds.difference(newIds); + // Write every secret first. If one write fails (iOS Keychain refusing), + // restore the previous values and leave the host list untouched, so there + // is never a half-imported state. + final previous = {}; + try { + for (final entry in passwords.entries) { + final hostId = entry.key.replaceFirst('pw_', ''); + if (!previous.containsKey(hostId)) { + previous[hostId] = await _storage.loadPassword(hostId); + } + await _storage.savePassword(hostId, entry.value); + } + } catch (_) { + for (final e in previous.entries) { + try { + if (e.value == null) { + await _storage.deletePassword(e.key); + } else { + await _storage.savePassword(e.key, e.value!); + } + } catch (_) {/* best effort */} + } + rethrow; + } _hosts = hosts; await _storage.saveHosts(_hosts); for (final id in removedIds) { await _storage.deleteHostSecrets(id); } - for (final entry in passwords.entries) { - final hostId = entry.key.replaceFirst('pw_', ''); - await _storage.savePassword(hostId, entry.value); - } notifyListeners(); } } diff --git a/app/lib/providers/key_provider.dart b/app/lib/providers/key_provider.dart index 11204f33..3e16b038 100644 --- a/app/lib/providers/key_provider.dart +++ b/app/lib/providers/key_provider.dart @@ -1,9 +1,13 @@ import 'dart:convert'; import 'dart:io'; + import 'package:flutter/foundation.dart'; import 'package:path/path.dart' as p; import 'package:shared_preferences/shared_preferences.dart'; + +import '../mobile/files/app_paths.dart'; import '../models/ssh_key.dart'; +import '../platform/runtime_platform.dart'; class KeyProvider extends ChangeNotifier { static const _prefsKey = 'yourssh.keys'; @@ -23,7 +27,15 @@ class KeyProvider extends ChangeNotifier { /// temp dir. final String? sshDirPath; - KeyProvider({this.discoverSshKeys = true, this.sshDirPath}) { + /// Resolves the app-owned private keys dir (without creating it). Injectable + /// for tests. + final Future Function() _keysDirPath; + + KeyProvider({ + this.discoverSshKeys = true, + this.sshDirPath, + Future Function()? keysDirPath, + }) : _keysDirPath = keysDirPath ?? AppPaths.privateKeysDirPath { ready = _load(); } @@ -33,20 +45,62 @@ class KeyProvider extends ChangeNotifier { if (raw != null) { try { final list = jsonDecode(raw) as List; - _keys = list.map((e) => SshKeyEntry.fromJson(e as Map)).toList(); + _keys = list + .map((e) => SshKeyEntry.fromJson(e as Map)) + .toList(); } catch (e) { - debugPrint('[KeyProvider] saved keys JSON malformed, starting empty: $e'); + debugPrint( + '[KeyProvider] saved keys JSON malformed, starting empty: $e', + ); _keys = []; } } + if (isIOSPlatform && await _rebaseKeyPaths()) await _save(); // Auto-discover keys from ~/.ssh if (discoverSshKeys) await _discoverSshKeys(); notifyListeners(); } + /// iOS changes the data-container path on reinstall/update, so absolute + /// paths under `/keys` saved earlier go stale. Re-anchors + /// each missing one on the current keys dir. Returns true if any changed. + Future _rebaseKeyPaths() async { + final String dir; + try { + dir = await _keysDirPath(); + } catch (e) { + debugPrint('[KeyProvider] cannot resolve keys dir, skipping rebase: $e'); + return false; + } + final marker = '${p.separator}${AppPaths.keysDirName}${p.separator}'; + String? rebase(String? path) { + if (path == null || File(path).existsSync()) return null; + final i = path.lastIndexOf(marker); + if (i < 0) return null; + final rebased = p.join(dir, path.substring(i + marker.length)); + return File(rebased).existsSync() ? rebased : null; + } + + var changed = false; + for (final k in _keys) { + final key = rebase(k.privateKeyPath); + if (key != null) { + k.privateKeyPath = key; + changed = true; + } + final cert = rebase(k.certificatePath); + if (cert != null) { + k.certificatePath = cert; + changed = true; + } + } + return changed; + } + Future _discoverSshKeys() async { final sshDir = Directory( - sshDirPath ?? p.join(Platform.environment['HOME'] ?? '', '.ssh')); + sshDirPath ?? p.join(Platform.environment['HOME'] ?? '', '.ssh'), + ); if (!sshDir.existsSync()) return; final dismissed = await _loadDismissed(); @@ -61,13 +115,17 @@ class KeyProvider extends ChangeNotifier { if (dismissed.contains(keyFile.path)) continue; final algo = _algorithmFrom(name); - final pubKey = pubFile.existsSync() ? pubFile.readAsStringSync().trim() : ''; - _keys.add(SshKeyEntry( - label: name, - algorithm: algo, - publicKey: pubKey, - privateKeyPath: keyFile.path, - )); + final pubKey = pubFile.existsSync() + ? pubFile.readAsStringSync().trim() + : ''; + _keys.add( + SshKeyEntry( + label: name, + algorithm: algo, + publicKey: pubKey, + privateKeyPath: keyFile.path, + ), + ); final certFile = File(p.join(sshDir.path, '$name-cert.pub')); if (certFile.existsSync()) { _keys.last.certificatePath = certFile.path; @@ -110,7 +168,9 @@ class KeyProvider extends ChangeNotifier { if (!file.existsSync()) throw Exception('Key file not found: $path'); final pubFile = File('$path.pub'); - final pubKey = pubFile.existsSync() ? pubFile.readAsStringSync().trim() : ''; + final pubKey = pubFile.existsSync() + ? pubFile.readAsStringSync().trim() + : ''; final algo = _algorithmFrom(path); final entry = SshKeyEntry( @@ -135,6 +195,7 @@ class KeyProvider extends ChangeNotifier { Future deleteKey(String id) async { final removed = findById(id); _keys.removeWhere((k) => k.id == id); + if (removed != null) await _deleteOwnedFiles(removed); await _save(); // Remember the path so auto-discovery doesn't re-add it next launch. final path = removed?.privateKeyPath; @@ -150,6 +211,29 @@ class KeyProvider extends ChangeNotifier { notifyListeners(); } + /// Deletes the key's files only when they live in the app-owned keys dir; + /// anything elsewhere (e.g. `~/.ssh`) is never touched. + Future _deleteOwnedFiles(SshKeyEntry k) async { + final String dir; + try { + dir = await _keysDirPath(); + } catch (_) { + return; + } + final path = k.privateKeyPath; + if (!p.isWithin(dir, path)) return; + if (_keys.any((o) => o.privateKeyPath == path)) return; // still referenced + for (final f in [path, '$path.pub', '$path-cert.pub', k.certificatePath]) { + if (f == null || !p.isWithin(dir, f)) continue; + try { + final file = File(f); + if (file.existsSync()) await file.delete(); + } catch (e) { + debugPrint('[KeyProvider] could not delete $f: $e'); + } + } + } + Future setCertificate(String keyId, String certPath) async { final idx = _keys.indexWhere((k) => k.id == keyId); if (idx == -1) return; @@ -168,7 +252,10 @@ class KeyProvider extends ChangeNotifier { Future _save() async { final prefs = await SharedPreferences.getInstance(); - await prefs.setString(_prefsKey, jsonEncode(_keys.map((k) => k.toJson()).toList())); + await prefs.setString( + _prefsKey, + jsonEncode(_keys.map((k) => k.toJson()).toList()), + ); } SshKeyEntry? findById(String id) { diff --git a/app/lib/providers/session_provider.dart b/app/lib/providers/session_provider.dart index 65f73fc8..969dc797 100644 --- a/app/lib/providers/session_provider.dart +++ b/app/lib/providers/session_provider.dart @@ -508,6 +508,11 @@ class SessionProvider extends ChangeNotifier { // the one the status bar shows, whatever Settings says later. session.termType = host.termType ?? terminalType?.call() ?? 'xterm-256color'; + final generation = session.connectGeneration; + // A pause (or a newer attempt after it) supersedes this attempt: stop + // without touching status, timers or the drop callbacks. + bool superseded() => + session.paused || session.connectGeneration != generation; try { final keyEntry = host.keyId != null ? keyLookup?.call(host.keyId!) : null; final jumpChain = SshService.resolveJumpChain( @@ -524,8 +529,9 @@ class SessionProvider extends ChangeNotifier { 'Tunneling via ${jumpChain.map((h) => h.host.label).join(' → ')}'); } _safeNotify(); - await _ssh.connect( + final client = await _ssh.connect( host, + isCurrent: () => !superseded(), keyEntry: keyEntry, jumpChain: jumpChain, verifyHostKey: hostKeyVerifier != null @@ -537,6 +543,12 @@ class SessionProvider extends ChangeNotifier { _verifyAndLog(session, hop.host, hop.port, keyType, fp) : null, ); + if (superseded()) { + // Paused (or replaced by a newer attempt) while dialing: this client + // belongs to nobody. Close it before it can mark the tab connected. + _ssh.discardClient(host.id, client); + return; + } session.logConnection(ConnectionLogLevel.success, 'Connection established'); session.status = SessionStatus.connected; audit?.record(AuditEvent.now( @@ -566,6 +578,9 @@ class SessionProvider extends ChangeNotifier { ); _safeNotify(); + // Closed on purpose by pauseAll: not a drop, no reconnect, no callback. + if (superseded()) return; + // Shell closed — try auto-reconnect if (_sessions.contains(session) && (autoReconnectEnabled?.call() ?? false)) { // Paired logging: a flapping host must show its disconnects, not an @@ -587,7 +602,7 @@ class SessionProvider extends ChangeNotifier { _safeNotify(); } } catch (e) { - if (!_sessions.contains(session)) return; + if (!_sessions.contains(session) || superseded()) return; session.logConnection(ConnectionLogLevel.error, 'Connection failed: $e'); final maxAttempts = reconnectAttempts?.call() ?? 0; final isUnlimited = maxAttempts == 0; @@ -647,6 +662,7 @@ class SessionProvider extends ChangeNotifier { if (session == null || session.status == SessionStatus.connecting) return; _reconnectTimers.remove(sessionId)?.cancel(); _countdownTimers.remove(sessionId)?.cancel(); + session.paused = false; session.status = SessionStatus.connecting; session.errorMessage = null; // A manual retry is a fresh attempt — drop the prior attempt's trace so the @@ -657,6 +673,96 @@ class SessionProvider extends ChangeNotifier { unawaited(_doConnect(session, session.host, attempt: 1)); } + // ── App lifecycle (iOS background pause / foreground resume) ──────────── + + @visibleForTesting + void scheduleReconnectForTest(SshSession s) => + _scheduleReconnect(s, s.host, attempt: 1); + + @visibleForTesting + void addSessionForTest(SshSession s) { + _sessions.add(s); + _activeSessionId ??= s.id; + } + + /// Closes every live SSH connection on purpose (the OS is about to suspend + /// the app). Sessions that are `connected` or `connecting` (a reconnect + /// countdown included) become `paused`; `error` and user-closed + /// `disconnected` sessions are left alone. Each host's client is closed + /// once. This is not a drop: no reconnect is scheduled and + /// [onSessionDropped] does not fire. + void pauseAll() => _pauseSessions(sshSessions.where((s) => !s.isWatch)); + + /// True while any session is paused for the background (until + /// [resumePaused] reconnects it). Anything that would re-dial a host on its + /// own should wait. + // Deliberately global: pauseAll pauses every session together. + bool get hasPausedSessions => sshSessions.any((s) => s.paused); + + void _pauseSessions(Iterable candidates) { + final hostIds = {}; + for (final s in candidates.toList()) { + if (s.status != SessionStatus.connected && + s.status != SessionStatus.connecting) { + continue; + } + _reconnectTimers.remove(s.id)?.cancel(); + _countdownTimers.remove(s.id)?.cancel(); + s.connectGeneration++; + s.paused = true; + s.status = SessionStatus.disconnected; + s.terminal.write( + '\r\n\x1b[2m[Paused while YourSSH was in the background]\x1b[0m\r\n'); + // Clients are per tab but the service keys them by host: close this + // tab's own shell too, not just the newest client of the host. + _ssh.disconnectSession(s.id); + hostIds.add(s.host.id); + } + for (final id in hostIds) { + _ssh.disconnect(id); + } + if (hostIds.isNotEmpty) _safeNotify(); + } + + /// Reconnects every paused session in tab order, [stagger] apart. Ignores + /// the auto-reconnect setting: a pause is not a drop. + Future resumePaused( + {Duration stagger = const Duration(milliseconds: 300)}) async { + final paused = sshSessions.where((s) => s.paused).toList(); + for (var i = 0; i < paused.length; i++) { + final s = paused[i]; + if (!_sessions.contains(s) || !s.paused) continue; + if (_disposed) return; + reconnectSession(s.id); // clears `paused`, reuses the tab + if (i < paused.length - 1) await Future.delayed(stagger); + } + } + + /// After a resume: probes each host that still has a `connected` session and + /// pauses + reconnects the sessions of hosts whose link did not survive the + /// suspension (half-open TCP looks alive until something is sent). + Future verifyLive( + {Duration timeout = const Duration(seconds: 3)}) async { + final byHost = >{}; + for (final s in sshSessions) { + if (s.isWatch || s.status != SessionStatus.connected) continue; + byHost.putIfAbsent(s.host.id, () => []).add(s); + } + // Probe all hosts at once: sequentially, N stuck hosts cost N x timeout. + final alive = await Future.wait([ + for (final e in byHost.entries) _ssh.isAlive(e.key, timeout: timeout), + ]); + final dead = []; + var i = 0; + for (final e in byHost.entries) { + if (!alive[i++]) dead.addAll(e.value); + } + if (dead.isEmpty || _disposed) return; + // Sessions may have changed while probing; _pauseSessions re-checks status. + _pauseSessions(dead); + await resumePaused(stagger: Duration.zero); + } + void _scheduleReconnect(SshSession session, Host host, {required int attempt}) { session.reconnectCount++; final delay = (attempt * 2).clamp(2, 60); diff --git a/app/lib/providers/settings_provider.dart b/app/lib/providers/settings_provider.dart index c7b939bb..398eea58 100644 --- a/app/lib/providers/settings_provider.dart +++ b/app/lib/providers/settings_provider.dart @@ -7,6 +7,7 @@ import 'package:xterm/xterm.dart' as xterm; import '../models/keyword_highlight_rule.dart'; import '../models/shell_profile.dart'; +import '../platform/runtime_platform.dart'; import '../theme/terminal_themes.dart'; /// Default audit-log retention — single source for the provider, its @@ -118,7 +119,15 @@ class SettingsProvider extends ChangeNotifier { await prefs.setString('terminalTheme', terminalTheme); } networkStatsEnabled = prefs.getBool('networkStatsEnabled') ?? false; - tmuxEnabled = prefs.getBool('tmuxEnabled') ?? false; + final storedTmux = prefs.getBool('tmuxEnabled'); + if (storedTmux != null) { + tmuxEnabled = storedTmux; + } else { + // Decide once on mobile (like terminalTheme): a fresh install gets + // tmux for flaky links, an install that already has hosts keeps off. + tmuxEnabled = mobileDefaultTmux && !prefs.containsKey('yourssh.hosts'); + if (mobileDefaultTmux) await prefs.setBool('tmuxEnabled', tmuxEnabled); + } commandNotificationsEnabled = prefs.getBool('commandNotificationsEnabled') ?? false; shellIntegrationEnabled = prefs.getBool('shellIntegrationEnabled') ?? true; recordingRedactionEnabled = prefs.getBool('recordingRedactionEnabled') ?? true; diff --git a/app/lib/services/cli/link_refused.dart b/app/lib/services/cli/link_refused.dart index 08fda38b..fd333dbc 100644 --- a/app/lib/services/cli/link_refused.dart +++ b/app/lib/services/cli/link_refused.dart @@ -5,6 +5,11 @@ import '../../models/app_notification.dart'; /// Longest link shown in the bell title. const int _maxShown = 120; +/// Longest reason shown (a reason can embed the link's host segment). +const int _maxBody = 200; + +String _cap(String s, int n) => s.length > n ? '${s.substring(0, n)}…' : s; + /// Bell entry for a `yourssh://` open the app refused (unknown host, /// unsupported shape). The link comes from a web page or another app, so /// control and bidi-override characters are removed before display; the @@ -15,7 +20,7 @@ AppNotification linkRefusedNotification(String url, String reason) { return AppNotification( type: AppNotificationType.linkRefused, title: 'Link refused: $shown', - body: _clean(reason), + body: _cap(_clean(reason), _maxBody), dedupeKey: 'link-refused:${shown.toLowerCase()}', ); } diff --git a/app/lib/services/key_gen_service.dart b/app/lib/services/key_gen_service.dart index 484e1bfe..87624f19 100644 --- a/app/lib/services/key_gen_service.dart +++ b/app/lib/services/key_gen_service.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:dartssh2/dartssh2.dart'; import 'package:path/path.dart' as p; +import '../platform/runtime_platform.dart'; import '../util/file_mode.dart'; import 'shell_integration_service.dart'; @@ -60,6 +61,7 @@ class KeyGenService { /// proves the binary runs; only a missing executable throws. Future probeSshKeygen() async { if (_probeCache != null) return _probeCache!; + if (!supportsSubprocesses) return _probeCache = false; try { await Process.run('ssh-keygen', ['-?']); _probeCache = true; @@ -69,6 +71,11 @@ class KeyGenService { return _probeCache!; } + /// Algorithm ids the UI may offer: Ed25519 is always available (pure + /// Dart); RSA/ECDSA need the system ssh-keygen. + Future> supportedAlgorithms() async => + await probeSshKeygen() ? ['ed25519', 'rsa', 'ecdsa'] : ['ed25519']; + Future generateEd25519({ required String name, String passphrase = '', diff --git a/app/lib/services/p2p_sync_service.dart b/app/lib/services/p2p_sync_service.dart index 6c39c356..4e60a1f3 100644 --- a/app/lib/services/p2p_sync_service.dart +++ b/app/lib/services/p2p_sync_service.dart @@ -20,6 +20,23 @@ class NetworkInterfaceInfo { class P2PSyncService { HttpServer? _server; + /// Services whose pairing server is currently open, so the app can close + /// them all when it goes to the background ([stopAll]). + static final Set _active = {}; + + /// Closes every open pairing server because the app is leaving the + /// foreground (iOS suspends it and kills the socket). Each service's + /// [onInterrupted] fires first so its screen can show a stopped state. + static Future stopAll() async { + for (final s in _active.toList()) { + s.onInterrupted?.call(); + await s.stop(); + } + } + + /// Invoked when [stopAll] closes this service's server. + void Function()? onInterrupted; + /// Invoked when the local HTTP server emits an error (e.g., socket closed /// mid-transfer). Without this, the receiver gets a vague "could not fetch" /// and the sender has no idea anything went wrong. @@ -74,6 +91,7 @@ class P2PSyncService { }) async { // Bind only to the interface the user picked, not every interface. _server = await HttpServer.bind(InternetAddress(hostAddress), 0); + _active.add(this); final port = _server!.port; _handleRequests(encryptedPayload); return 'http://$hostAddress:$port/sync'; @@ -102,6 +120,7 @@ class P2PSyncService { } Future stop() async { + _active.remove(this); await _server?.close(force: true); _server = null; } diff --git a/app/lib/services/ssh_service.dart b/app/lib/services/ssh_service.dart index 40c5d567..dd591d22 100644 --- a/app/lib/services/ssh_service.dart +++ b/app/lib/services/ssh_service.dart @@ -54,6 +54,10 @@ class SshService { /// Global on/off for shell integration, read from SettingsProvider in /// main.dart. null => treat as enabled. bool Function()? isShellIntegrationEnabled; + + /// Fired when a validated sudo password could not be stored (iOS Keychain + /// refused and plaintext fallback is off), so the UI can tell the user. + void Function(Host host)? onSudoPasswordNotSaved; final Map _clients = {}; final Map _shells = {}; final Map _shellToHost = {}; // sessionId → hostId @@ -305,6 +309,47 @@ class SshService { // ── Connect ──────────────────────────────────────────── + /// Builds the destination [SSHClient] for [connect] (a seam for tests). + @visibleForTesting + SSHClient buildConnectClient( + SSHSocket socket, { + required Host host, + required String? password, + required List? identities, + required Future Function(String keyType, Uint8List fingerprint)? + verifyHostKey, + }) { + return SSHClient( + socket, + username: host.username, + onPasswordRequest: () => password ?? '', + identities: identities, + // Forwarding terminates at the destination client only (OpenSSH + // ProxyJump semantics) — never add a handler to _ensureJumpClient + // or testConnection. + agentHandler: host.agentForwarding + ? AgentForwardingHandler( + loadKeychainIdentities: () async => + await keychainIdentitiesLoader?.call(host.keyId) ?? + const [], + onRequestServed: (usedFallback) => + onAgentForwardingEvent?.call( + host.id, + null, + usedFallback + ? AgentForwardingState.fallback + : AgentForwardingState.active), + ) + : null, + onVerifyHostKey: (type, fp) => + hostKeyDecision(verifyHostKey, type.toString(), fp), + // Built-in keepalive is disabled: HealthMonitorService is the sole + // pinger (it both keeps the connection alive and measures latency), + // avoiding a race on the shared global-request reply queue. + keepAliveInterval: null, + ); + } + Future connect( Host host, { SshKeyEntry? keyEntry, @@ -314,6 +359,10 @@ class SshService { // [verifyHostKey] only covers the destination). Null → reject (fail closed). Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + // Returns false once this attempt was superseded (the app paused it while + // it was dialing). A stale attempt never touches the per-host caches the + // current one owns: it closes its own client and gives up quietly. + bool Function()? isCurrent, }) async { if (hookBus != null) { final result = hookBus!.fireInterceptable( @@ -343,44 +392,40 @@ class SshService { } else { socket = await localDial(host); } - client = SSHClient( - socket, - username: host.username, - onPasswordRequest: () => password ?? '', - identities: resolution.identities.isNotEmpty ? resolution.identities : null, - // Forwarding terminates at the destination client only (OpenSSH - // ProxyJump semantics) — never add a handler to _ensureJumpClient - // or testConnection. - agentHandler: host.agentForwarding - ? AgentForwardingHandler( - loadKeychainIdentities: () async => - await keychainIdentitiesLoader?.call(host.keyId) ?? - const [], - onRequestServed: (usedFallback) => - onAgentForwardingEvent?.call( - host.id, - null, - usedFallback - ? AgentForwardingState.fallback - : AgentForwardingState.active), - ) - : null, - onVerifyHostKey: (type, fp) => - hostKeyDecision(verifyHostKey, type.toString(), fp), - // Built-in keepalive is disabled: HealthMonitorService is the sole - // pinger (it both keeps the connection alive and measures latency), - // avoiding a race on the shared global-request reply queue. - keepAliveInterval: null, - ); + client = buildConnectClient(socket, + host: host, + password: password, + identities: resolution.identities.isNotEmpty + ? resolution.identities + : null, + verifyHostKey: verifyHostKey); await client.authenticated; } catch (e) { - if (resolution.agentProxy != null) { - unawaited(_agentProxies[host.id]?.close() ?? Future.value()); - _agentProxies.remove(host.id); + final proxy = resolution.agentProxy; + if (proxy != null) { + // Only the proxy this attempt registered: a newer attempt may own the + // map entry by now. + if (identical(_agentProxies[host.id], proxy)) { + _agentProxies.remove(host.id); + } + unawaited(proxy.close()); } - _teardownJumpChain(host.id); + // A stale attempt must not unwind the jump chain a newer one is using. + if (isCurrent?.call() ?? true) _teardownJumpChain(host.id); rethrow; } + if (!(isCurrent?.call() ?? true)) { + // Superseded while authenticating: do not evict the live client. + client.close(); + final proxy = resolution.agentProxy; + if (proxy != null) { + if (identical(_agentProxies[host.id], proxy)) { + _agentProxies.remove(host.id); + } + unawaited(proxy.close()); + } + return client; + } _clients[host.id] = client; return client; } @@ -723,6 +768,21 @@ class SshService { } } + /// Whether [hostId]'s client is open and answers a keepalive ping within + /// [timeout]. False without a client, with a closed one, or when the ping + /// does not complete in time (a half-open link after the OS suspended us). + Future isAlive(String hostId, + {Duration timeout = const Duration(seconds: 3)}) async { + final client = _clients[hostId]; + if (client == null || client.isClosed) return false; + try { + await client.ping().timeout(timeout); + return true; + } catch (_) { + return false; + } + } + // ── Shell session (feeds into xterm Terminal) ────────── Future openShell( @@ -1028,7 +1088,12 @@ class SshService { final out = g.flush(); if (out.isNotEmpty) outQueue.add(out); } - _onShellClosed(session); + // After a pause/resume the tab already runs a newer shell: only the + // current shell (or none) may tear the session's hooks down. + final current = _shells[session.id]; + if (current == null || identical(current, shell)) { + _onShellClosed(session); + } if (!done.isCompleted) done.complete(); }, onError: (Object e) { @@ -1375,8 +1440,11 @@ class SshService { if (validatedToPersist != null) { try { await _storage.saveSudoPassword(host.id, validatedToPersist!); - } catch (_) { + } catch (e) { // Keychain unavailable — the password still works for this session. + // Only surfaced when plaintext fallback is off (iOS), where it means + // the password was not remembered. + if (e is SecretStoreException) onSudoPasswordNotSaved?.call(host); } } return sftp; @@ -1476,6 +1544,13 @@ class SshService { _teardownJumpChain(hostId); } + /// Closes a [client] nobody will use (a connect attempt superseded while it + /// was dialing) and drops it from the cache only when it is the cached one. + void discardClient(String hostId, SSHClient client) { + if (identical(_clients[hostId], client)) _clients.remove(hostId); + client.close(); + } + void disconnectSession(String sessionId) { _shells[sessionId]?.close(); _shells.remove(sessionId); diff --git a/app/lib/services/storage_service.dart b/app/lib/services/storage_service.dart index f5b68a5c..45319965 100644 --- a/app/lib/services/storage_service.dart +++ b/app/lib/services/storage_service.dart @@ -5,7 +5,24 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../models/host.dart'; import '../models/known_host.dart'; +/// Thrown by [StorageService] when a secret cannot be written to the platform +/// secure store and plaintext fallback is disabled (iOS). +class SecretStoreException implements Exception { + final String key; + final Object cause; + SecretStoreException(this.key, this.cause); + + @override + String toString() => 'SecretStoreException($key): $cause'; +} + class StorageService { + /// [allowPlaintextFallback] false (iOS): a failed secure write throws + /// [SecretStoreException] and nothing lands in `SharedPreferences`. + StorageService({this.allowPlaintextFallback = true}); + + final bool allowPlaintextFallback; + static const _hostsKey = 'yourssh.hosts'; /// macOS deliberately uses the *legacy file* Keychain. @@ -24,7 +41,17 @@ class StorageService { useDataProtectionKeyChain: false, ); + /// iOS Keychain: items stay on this device (no iCloud Keychain sync, not + /// restored onto another device from a backup) and are readable after the + /// first unlock so background reconnects work. + @visibleForTesting + static const iosKeychainOptions = IOSOptions( + accessibility: KeychainAccessibility.first_unlock_this_device, + synchronizable: false, + ); + static const _storage = FlutterSecureStorage( + iOptions: iosKeychainOptions, mOptions: macOsKeychainOptions, wOptions: WindowsOptions(), ); @@ -84,6 +111,10 @@ class StorageService { if (prefs.containsKey(key)) await prefs.remove(key); _clearPlaintext(key); } catch (e) { + if (!allowPlaintextFallback) { + debugPrint('[StorageService] secure write failed for $key: $e'); + throw SecretStoreException(key, e); + } debugPrint('[StorageService] secure write failed for $key, falling back to prefs: $e'); final prefs = await SharedPreferences.getInstance(); await prefs.setString(key, value); @@ -98,6 +129,8 @@ class StorageService { } catch (e) { debugPrint('[StorageService] secure read failed for $key: $e'); } + // Without plaintext fallback nothing was ever written to prefs. + if (!allowPlaintextFallback) return null; final prefs = await SharedPreferences.getInstance(); return prefs.getString(key); } diff --git a/app/lib/util/native_chmod.dart b/app/lib/util/native_chmod.dart new file mode 100644 index 00000000..6427f58c --- /dev/null +++ b/app/lib/util/native_chmod.dart @@ -0,0 +1,36 @@ +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; + +/// `chmod(2)` through libc, for platforms that cannot spawn the `chmod` +/// binary (iOS). Not supported on Windows. +/// +/// `mode_t` is 16 bits on Darwin and 32 bits on Linux/Android. +Future chmodNative(String path, int mode) async { + if (Platform.isWindows) { + throw UnsupportedError('chmodNative is not supported on Windows'); + } + final lib = DynamicLibrary.process(); + final errnoLocation = lib.lookupFunction Function(), + Pointer Function()>( + Platform.isIOS || Platform.isMacOS ? '__error' : '__errno_location', + ); + final cPath = path.toNativeUtf8(); + try { + final int rc; + if (Platform.isIOS || Platform.isMacOS) { + rc = lib.lookupFunction, Uint16), + int Function(Pointer, int)>('chmod')(cPath, mode); + } else { + rc = lib.lookupFunction, Uint32), + int Function(Pointer, int)>('chmod')(cPath, mode); + } + if (rc != 0) { + final errno = errnoLocation().value; + throw FileSystemException('chmod failed', path, OSError('', errno)); + } + } finally { + calloc.free(cPath); + } +} diff --git a/app/macos/Flutter/GeneratedPluginRegistrant.swift b/app/macos/Flutter/GeneratedPluginRegistrant.swift index 6fbaeb85..436b0b82 100644 --- a/app/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/app/macos/Flutter/GeneratedPluginRegistrant.swift @@ -16,6 +16,7 @@ import mobile_scanner import network_info_plus import package_info_plus import screen_retriever +import share_plus import shared_preferences_foundation import sqlite3_flutter_libs import url_launcher_macos @@ -34,6 +35,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { NetworkInfoPlusPlugin.register(with: registry.registrar(forPlugin: "NetworkInfoPlusPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) ScreenRetrieverPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverPlugin")) + SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) Sqlite3FlutterLibsPlugin.register(with: registry.registrar(forPlugin: "Sqlite3FlutterLibsPlugin")) UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) diff --git a/app/pubspec.lock b/app/pubspec.lock index aacbe954..1677b56c 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -718,10 +718,10 @@ packages: dependency: "direct main" description: name: mobile_scanner - sha256: d234581c090526676fd8fab4ada92f35c6746e3fb4f05a399665d75a399fb760 + sha256: "175c62fc813c2bd762757359a2088f8cbdb72020cf85d4cd27fc4d3fe59be058" url: "https://pub.dev" source: hosted - version: "5.2.3" + version: "7.5.0" multicast_dns: dependency: "direct main" description: @@ -994,6 +994,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.9" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: fce43200aa03ea87b91ce4c3ac79f0cecd52e2a7a56c7a4185023c271fbfa6da + url: "https://pub.dev" + source: hosted + version: "10.1.4" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: cc012a23fc2d479854e6c80150696c4a5f5bb62cb89af4de1c505cf78d0a5d0b + url: "https://pub.dev" + source: hosted + version: "5.0.2" shared_preferences: dependency: "direct main" description: diff --git a/app/pubspec.yaml b/app/pubspec.yaml index a00cdc62..044e0d4c 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -39,7 +39,7 @@ dependencies: # QR code generation (P2P sync) qr_flutter: ^4.1.0 - mobile_scanner: ^5.2.3 + mobile_scanner: ^7.5.0 local_auth: ^2.3.0 # UUID generation @@ -49,6 +49,7 @@ dependencies: # Path utilities path: ^1.9.0 path_provider: ^2.1.4 + share_plus: ^10.1.4 # Hotkey management hotkey_manager: ^0.2.3 diff --git a/app/test/mobile/app_lock_gate_test.dart b/app/test/mobile/app_lock_gate_test.dart index 0291ec7a..7debdf60 100644 --- a/app/test/mobile/app_lock_gate_test.dart +++ b/app/test/mobile/app_lock_gate_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh/mobile/security/app_lock_gate.dart'; import 'package:yourssh/theme/app_theme.dart'; import 'package:yourssh_ui/yourssh_ui.dart'; @@ -27,6 +28,29 @@ void main() { expect(find.byKey(_childKey), findsOneWidget); }); + testWidgets('cold start paints nothing of the child before the gate decides', + (tester) async { + for (final enabled in [true, false]) { + SharedPreferences.setMockInitialValues({kAppLockPrefKey: enabled}); + await tester.pumpWidget(const SizedBox()); + await tester.pumpWidget(ysTestApp( + AppLockGate( + // No enabledOverride: the setting is read from prefs, as in the app. + authenticator: () async => false, + child: const Scaffold(body: SizedBox(key: _childKey)), + ), + touch: true, + )); + // First frame: the decision (prefs, device support) is still pending. + expect(find.byKey(_childKey), findsNothing, reason: 'enabled=$enabled'); + expect(find.byKey(_childKey, skipOffstage: false), findsOneWidget); + expect(find.text('Unlock'), findsNothing); + await tester.pumpAndSettle(); + expect(find.byKey(_childKey), enabled ? findsNothing : findsOneWidget, + reason: 'enabled=$enabled'); + } + }); + testWidgets('enabled + success unlocks to child', (tester) async { await _pump(tester, enabled: true, auth: () async => true); expect(find.byKey(_childKey), findsOneWidget); diff --git a/app/test/mobile/app_paths_test.dart b/app/test/mobile/app_paths_test.dart new file mode 100644 index 00000000..11578ee1 --- /dev/null +++ b/app/test/mobile/app_paths_test.dart @@ -0,0 +1,80 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:yourssh/mobile/files/app_paths.dart'; +import 'package:yourssh/mobile/files/file_export.dart'; + +class _FakePaths extends PathProviderPlatform with MockPlatformInterfaceMixin { + _FakePaths(this.docs, this.support); + final String docs; + final String support; + @override + Future getApplicationDocumentsPath() async => docs; + @override + Future getApplicationSupportPath() async => support; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root, docs, support; + + setUp(() { + root = Directory.systemTemp.createTempSync('app_paths_test'); + docs = Directory(p.join(root.path, 'Documents'))..createSync(); + support = Directory(p.join(root.path, 'Support'))..createSync(); + PathProviderPlatform.instance = _FakePaths(docs.path, support.path); + }); + tearDown(() => root.deleteSync(recursive: true)); + + test('keys live outside Documents; downloads inside it', () async { + final keys = await AppPaths.privateKeysDir( + chmod: (_, _) async {}, excludeFromBackup: (_) async {}); + expect(p.isWithin(docs.path, keys.path), isFalse); + expect(keys.path, p.join(support.path, 'keys')); + expect(keys.existsSync(), isTrue); + final dl = await AppPaths.downloadsDir(); + expect(dl.path, p.join(docs.path, 'Downloads')); + expect(dl.existsSync(), isTrue); + }); + + test('the key directory is 0700 and excluded from backup', () async { + final modes = {}; + final excluded = []; + final keys = await AppPaths.privateKeysDir( + chmod: (path, mode) async => modes[path] = mode, + excludeFromBackup: (path) async => excluded.add(path), + ); + expect(modes[keys.path], 0x1C0); + expect(excluded, [keys.path]); + }); + + test('importPrivateKey copies with 0600 and never overwrites', () async { + final picked = File(p.join(root.path, 'id_ed25519')) + ..writeAsStringSync('PRIVATE'); + final into = Directory(p.join(root.path, 'keys'))..createSync(); + final modes = {}; + Future chmod(String path, int mode) async => modes[path] = mode; + + final a = await importPrivateKey(picked.path, into, chmod: chmod); + final b = await importPrivateKey(picked.path, into, chmod: chmod); + + expect(picked.existsSync(), isTrue, reason: 'picked file is copied, not moved'); + expect(p.basename(a.path), 'id_ed25519'); + expect(p.basename(b.path), 'id_ed25519 (1)'); + expect(b.readAsStringSync(), 'PRIVATE'); + expect(modes[a.path], 0x180); + expect(modes[b.path], 0x180); + }); + + test('importPrivateKey sanitizes the file name', () async { + final picked = File(p.join(root.path, 'my key (copy).pem')) + ..writeAsStringSync('x'); + final into = Directory(p.join(root.path, 'keys'))..createSync(); + final f = await importPrivateKey(picked.path, into, chmod: (_, _) async {}); + expect(p.dirname(f.path), into.path); + expect(p.basename(f.path), isNot(contains(' '))); + }); +} diff --git a/app/test/mobile/desktop_only_guard_test.dart b/app/test/mobile/desktop_only_guard_test.dart new file mode 100644 index 00000000..0b124ec7 --- /dev/null +++ b/app/test/mobile/desktop_only_guard_test.dart @@ -0,0 +1,46 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('flutter_pty fork no longer declares an iOS platform', () { + final y = File('../packages/flutter_pty/pubspec.yaml').readAsStringSync(); + expect(RegExp(r'^\s+ios:', multiLine: true).hasMatch(y), isFalse); + }); + + test('app/lib/mobile imports no desktop-only module', () { + const banned = [ + "/main.dart'", 'main_screen.dart', 'single_instance.dart', + 'cli_listener', 'peer_cred.dart', 'app_cli_handlers.dart', + 'update_service.dart', 'update_provider.dart', 'local_shell_service.dart', + 'pty_runner.dart', '/recording_', '/audit_', '/plugin_', + 'yourssh_script_engine', 'window_manager', 'hotkey_manager', + 'local_notifier', + ]; + final offenders = [ + for (final f in Directory('lib/mobile') + .listSync(recursive: true) + .whereType() + .where((f) => f.path.endsWith('.dart'))) + for (final l + in f.readAsLinesSync().where((l) => l.startsWith('import '))) + if (banned.any(l.contains)) '${f.path}: $l', + ]; + expect(offenders, isEmpty); + }); + + test('main() returns for mobile before any desktop start-up', () { + final src = File('lib/main.dart').readAsStringSync(); + final start = src.indexOf('void main('); + final mobile = src.indexOf('runApp(const YourSSHMobileApp())', start); + expect(mobile, greaterThan(start)); + for (final call in [ + 'claimSingleInstance(', + '_migrateSandboxContainer(', + 'windowManager.ensureInitialized', + 'NotificationService.init', + ]) { + expect(src.indexOf(call, start), greaterThan(mobile), reason: call); + } + }); +} diff --git a/app/test/mobile/file_export_test.dart b/app/test/mobile/file_export_test.dart new file mode 100644 index 00000000..75be3a52 --- /dev/null +++ b/app/test/mobile/file_export_test.dart @@ -0,0 +1,43 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:yourssh/mobile/files/file_export.dart'; +import 'package:yourssh/util/safe_local_path.dart'; + +void main() { + late Directory tmp; + setUp(() => tmp = Directory.systemTemp.createTempSync('file_export_test')); + tearDown(() => tmp.deleteSync(recursive: true)); + + test('uniqueLocalPath never overwrites and rejects unsafe names', () { + expect(uniqueLocalPath(tmp.path, 'a.txt'), '${tmp.path}/a.txt'); + File('${tmp.path}/a.txt').createSync(); + expect(uniqueLocalPath(tmp.path, 'a.txt'), '${tmp.path}/a (1).txt'); + File('${tmp.path}/a (1).txt').createSync(); + expect(uniqueLocalPath(tmp.path, 'a.txt'), '${tmp.path}/a (2).txt'); + expect(() => uniqueLocalPath(tmp.path, '../x'), + throwsA(isA())); + }); + + test('writeDownload writes via .part and renames on success', () async { + final out = '${tmp.path}/ok.bin'; + await writeDownload(Stream.fromIterable([ + [1, 2], + [3], + ]), out); + expect(File(out).readAsBytesSync(), [1, 2, 3]); + expect(File('$out.part').existsSync(), isFalse); + }); + + test('writeDownload leaves nothing behind when the stream fails', () async { + final c = StreamController>(); + final f = writeDownload(c.stream, '${tmp.path}/out.bin'); + c + ..add([1, 2]) + ..addError(Exception('connection closed')); + await expectLater(f, throwsException); + expect(File('${tmp.path}/out.bin').existsSync(), isFalse); + expect(File('${tmp.path}/out.bin.part').existsSync(), isFalse); + }); +} diff --git a/app/test/mobile/ios_boot_test.dart b/app/test/mobile/ios_boot_test.dart new file mode 100644 index 00000000..27141edf --- /dev/null +++ b/app/test/mobile/ios_boot_test.dart @@ -0,0 +1,66 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/mobile/mobile_app.dart'; +import 'package:yourssh/mobile/screens/mobile_home_shell.dart'; +import 'package:yourssh/mobile/screens/mobile_hosts_screen.dart'; +import 'package:yourssh/mobile/screens/mobile_keys_screen.dart'; +import 'package:yourssh/mobile/screens/mobile_settings_screen.dart'; +import 'package:yourssh/mobile/screens/mobile_snippets_screen.dart'; +import 'package:yourssh/mobile/security/app_lock_gate.dart'; +import 'package:yourssh/mobile/widgets/mobile_tab_bar.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const secureChannel = + MethodChannel('plugins.it_nomads.com/flutter_secure_storage'); + + setUp(() { + SharedPreferences.setMockInitialValues({kAppLockPrefKey: false}); + PackageInfo.setMockInitialValues( + appName: 'YourSSH', + packageName: 'com.thangnm.yourssh', + version: '0.0.0', + buildNumber: '0', + buildSignature: '', + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureChannel, (_) async => null); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureChannel, null); + }); + + testWidgets('the mobile shell boots under iOS', + (t) async { + await t.pumpWidget(const YourSSHMobileApp()); + await t.pumpAndSettle(); + expect(find.byType(MobileHomeShell), findsOneWidget); + expect(find.byType(MobileTabBar), findsOneWidget); + expect(t.takeException(), isNull); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + + testWidgets('every tab renders under iOS', (t) async { + await t.pumpWidget(const YourSSHMobileApp()); + await t.pumpAndSettle(); + final screens = { + 'Snippets': MobileSnippetsScreen, + 'Keys': MobileKeysScreen, + 'Settings': MobileSettingsScreen, + 'Hosts': MobileHostsScreen, + }; + for (final e in screens.entries) { + await t.tap(find.descendant( + of: find.byType(MobileTabBar), matching: find.text(e.key))); + await t.pumpAndSettle(); + expect(t.takeException(), isNull, reason: e.key); + // IndexedStack: only the selected tab is onstage. + expect(find.byType(e.value), findsOneWidget, reason: e.key); + } + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +} diff --git a/app/test/mobile/links/mobile_links_lock_test.dart b/app/test/mobile/links/mobile_links_lock_test.dart new file mode 100644 index 00000000..1370dbfc --- /dev/null +++ b/app/test/mobile/links/mobile_links_lock_test.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/mobile/links/mobile_links.dart'; +import 'package:yourssh/mobile/mobile_bootstrap.dart'; +import 'package:yourssh/mobile/security/app_lock_gate.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/mobile/util/mobile_prefs.dart'; + +import '../../helpers/ys_test_app.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final initiallyLocked = mobileAppLocked.value; + const url = MethodChannel('yourssh/url'); + const ssh = MethodChannel('yourssh/ssh_url'); + + Future send(WidgetTester t, String name, String link) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage(name, + const StandardMethodCodec().encodeMethodCall(MethodCall('open', link)), + (_) {}); + // Real async: SharedPreferences and the providers' loads. + await t.runAsync(() => Future.delayed(const Duration(milliseconds: 200))); + } + + tearDown(() => mobileAppLocked.value = false); + + testWidgets('an ssh:// link to an unknown target asks only after unlock ' + '(nothing saved)', (tester) async { + SharedPreferences.setMockInitialValues({kSshLinksPrefKey: true}); + final b = MobileBootstrap(); + addTearDown(b.dispose); + await tester.pumpWidget(MultiProvider( + providers: b.providers, + child: ysTestApp( + Navigator( + key: b.navigatorKey, + onGenerateRoute: (_) => MaterialPageRoute( + builder: (_) => const Scaffold(body: Text('home'))), + ), + touch: true), + )); + MobileLinks( + bootstrap: b, + navigator: b.navigatorKey, + appVersion: '1', + urlChannel: url, + sshChannel: ssh) + .attach(); + + mobileAppLocked.value = true; + await send(tester, 'yourssh/ssh_url', 'ssh://demo@203.0.113.7'); + await tester.pump(); + expect(find.text('Open ssh:// link?'), findsNothing); + + mobileAppLocked.value = false; + await tester.runAsync(() => Future.delayed(const Duration(milliseconds: 100))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.text('Open ssh:// link?'), findsOneWidget); + expect(find.textContaining('demo@203.0.113.7:22'), findsOneWidget); + // Nothing was saved by asking. + expect(b.hostProvider.allHosts, isEmpty); + }); + + test('the app counts as locked until the gate has decided', () { + expect(initiallyLocked, isTrue); + }); + + testWidgets('two yourssh:// links while locked: nothing opens, then only the ' + 'newest does', (tester) async { + SharedPreferences.setMockInitialValues({}); + final b = MobileBootstrap(); + addTearDown(b.dispose); + final opened = []; + await tester.pumpWidget(MultiProvider( + providers: b.providers, + child: ysTestApp( + Navigator( + key: b.navigatorKey, + onGenerateRoute: (_) => MaterialPageRoute( + builder: (_) => const Scaffold(body: Text('home'))), + ), + touch: true), + )); + await tester.runAsync(() async { + await b.hostProvider.ready; + await b.hostProvider.addHost( + Host(label: 'one', host: '1.example.com', username: 'u')); + await b.hostProvider.addHost( + Host(label: 'two', host: '2.example.com', username: 'u')); + }); + MobileLinks( + bootstrap: b, + navigator: b.navigatorKey, + appVersion: '1', + urlChannel: url, + sshChannel: ssh, + openSession: (nav, host, {auditSource = 'app', resetStack = false}) async => + opened.add('${host.label}:$auditSource'), + ).attach(); + + mobileAppLocked.value = true; + await send(tester, 'yourssh/url', 'yourssh://connect/one'); + await send(tester, 'yourssh/url', 'yourssh://connect/two'); + expect(opened, isEmpty); + + mobileAppLocked.value = false; + await tester.runAsync(() => Future.delayed(const Duration(milliseconds: 100))); + expect(opened, ['two:url']); + }); +} diff --git a/app/test/mobile/links/mobile_links_test.dart b/app/test/mobile/links/mobile_links_test.dart new file mode 100644 index 00000000..0b61da43 --- /dev/null +++ b/app/test/mobile/links/mobile_links_test.dart @@ -0,0 +1,112 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/mobile/links/mobile_cli_handlers.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/providers/host_provider.dart'; +import 'package:yourssh/services/cli/cli_server.dart'; +import 'package:yourssh/services/cli/host_resolver.dart'; +import 'package:yourssh/services/cli/link_refused.dart'; +import 'package:yourssh/services/cli/url_channel.dart'; +import 'package:yourssh/services/storage_service.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const ch = MethodChannel('yourssh/url'); + late HostProvider hosts; + late List opened; + late List refused; + late DateTime clock; + late CliServer server; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + hosts = HostProvider(StorageService()); + await hosts.ready; + await hosts.addHost(Host(label: 'Prod-DB', host: 'db.example.com', username: 'u')); + await hosts.addHost(Host(label: 'DB', host: 'a.example.com', username: 'u')); + await hosts.addHost(Host(label: 'db', host: 'b.example.com', username: 'u')); + await hosts.addHost(Host(label: 'a', host: 'c.example.com', username: 'u')); + opened = []; + refused = []; + clock = DateTime(2026); + server = CliServer( + handlers: MobileCliHandlers( + hostProvider: hosts, + open: (h, s) async => opened.add('${h.label}:$s'), + appVersion: '1', + ), + token: 't', + now: () => clock, + onUrlRefused: (url, reason) { + final n = linkRefusedNotification(url, reason); + refused.add('${n.title} — ${n.body}'); + }, + ); + UrlChannel(server: server, channel: ch).attach(); + }); + tearDown(() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(ch, null)); + + Future send(String url) async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + 'yourssh/url', + const StandardMethodCodec().encodeMethodCall(MethodCall('open', url)), + (_) {}); + await pumpEventQueue(); + } + + test('yourssh://connect opens a saved host by label (NFC, any case)', () async { + await send('yourssh://connect/prod-db'); + expect(opened, ['Prod-DB:url']); + }); + + test('unknown, ambiguous and unsupported links open nothing and are refused', + () async { + for (final u in [ + 'yourssh://connect/nope', + 'yourssh://connect/db', // 'DB' + 'db' + 'yourssh://tunnel/start/x', + 'yourssh://connect/a?cmd=id', + 'yourssh://u@connect/a', + 'yourssh://connect/${'a' * 5000}', + ]) { + await send(u); + } + expect(opened, isEmpty); + expect(refused, hasLength(6)); + // The 5000-char link and its reason are capped in what is shown. + expect(refused.every((m) => m.length <= 120 + 200 + 40), isTrue); + }); + + test('control and bidi characters in a refused link never reach the message', + () async { + await send('yourssh://connect/x\u202e\x1b[31mevil'); + expect(opened, isEmpty); + expect(refused, hasLength(1)); + expect(refused.single, contains('Link refused: yourssh://connect/x[31mevil')); + expect(refused.single.contains('\u202e'), isFalse); + expect(refused.single.contains('\x1b'), isFalse); + }); + + test('the same link twice within 2 s opens once', () async { + await send('yourssh://connect/prod-db'); + await send('YOURSSH://connect/PROD-DB'); + expect(opened, ['Prod-DB:url']); + clock = clock.add(CliServer.dedupeWindow); + await send('yourssh://connect/prod-db'); + expect(opened, hasLength(2)); + }); + + test('ad-hoc connects are impossible through the handlers', () async { + final h = MobileCliHandlers( + hostProvider: hosts, open: (_, _) async {}, appVersion: '1'); + expect(() => h.connectAdHoc(const AdHocTarget('a', 'h', 22)), + throwsA(isA())); + await h.focusWindow(); // no-op + }); + +} diff --git a/app/test/mobile/links/ssh_link_test.dart b/app/test/mobile/links/ssh_link_test.dart new file mode 100644 index 00000000..e0e5c79f --- /dev/null +++ b/app/test/mobile/links/ssh_link_test.dart @@ -0,0 +1,122 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:yourssh/mobile/links/ssh_link.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/services/cli/cli_server.dart'; + +void main() { + test('parseSshLink accepts user@host[:port] and nothing else', () { + final t = parseSshLink('ssh://alice@10.0.0.5:2222')!; + expect([t.user, t.host, t.port], ['alice', '10.0.0.5', 2222]); + expect(t.query, 'alice@10.0.0.5:2222'); + expect(parseSshLink('ssh://alice@[fe80::1]/')!.port, 22); + expect(parseSshLink('SSH://alice@example.com')!.host, 'example.com'); + for (final u in [ + 'ssh://10.0.0.5', + 'ssh://a:pw@h', + 'ssh://a;fingerprint=x@h', + 'ssh://a@h/path', + 'ssh://a@h?x=1', + 'ssh://a@h#f', + 'ssh://-oProxyCommand=x@h', + 'ssh://a@-h', + 'ssh://a@h:0', + 'ssh://a@h:70000', + 'ssh://a@${'h' * 3000}', + 'ssh://a@h\u202e', + 'ssh://a@h\n', + 'ssh://a%40b@h', + 'yourssh://connect/a', + '', + ]) { + expect(parseSshLink(u), isNull, reason: u); + } + }); + + group('SshLinkHandler', () { + late List hosts; + late bool enabled; + late bool confirmAnswer; + late List log; + late DateTime clock; + + SshLinkHandler build() => SshLinkHandler( + hosts: () => hosts, + enabled: () async => enabled, + openSaved: (h) async => log.add('open:${h.label}'), + confirm: (t) async { + log.add('confirm:${t.query}'); + return confirmAnswer; + }, + addHost: (h) => + log.add('add:${h.username}@${h.host}:${h.port}:${h.label}'), + refused: (m) => log.add('refused:$m'), + now: () => clock, + ); + + setUp(() { + hosts = [Host(id: 'a', label: 'Prod', host: '10.0.0.5', username: 'alice', port: 2222)]; + enabled = true; + confirmAnswer = false; + log = []; + clock = DateTime(2026); + }); + + test('is refused while the setting is off', () async { + enabled = false; + await build().handle('ssh://alice@10.0.0.5:2222'); + expect(log, ['refused:ssh:// links are off (Settings › Security)']); + }); + + test('unparsable links are refused', () async { + await build().handle('ssh://a@h/path'); + expect(log, hasLength(1)); + expect(log.single, startsWith('refused:')); + }); + + test('a saved user@host:port opens that host without asking', () async { + await build().handle('ssh://alice@10.0.0.5:2222'); + expect(log, ['open:Prod']); + }); + + test('an unknown target asks first and only prefills Add Host', () async { + final h = build(); + await h.handle('ssh://alice@203.0.113.7'); + expect(log, ['confirm:alice@203.0.113.7:22']); + log.clear(); + confirmAnswer = true; + clock = clock.add(CliServer.dedupeWindow); + await h.handle('ssh://alice@203.0.113.7'); + expect(log, [ + 'confirm:alice@203.0.113.7:22', + 'add:alice@203.0.113.7:22:alice@203.0.113.7', + ]); + expect(log.any((l) => l.startsWith('open:')), isFalse); + }); + + test('an ambiguous saved target is refused', () async { + hosts.add(Host(id: 'b', label: 'Prod2', host: '10.0.0.5', username: 'alice', port: 2222)); + await build().handle('ssh://alice@10.0.0.5:2222'); + expect(log.single, startsWith('refused:')); + }); + + test('a host merely labelled like the target does not stand in for it', + () async { + hosts = [ + Host(id: 'x', label: 'alice@203.0.113.7:22', host: 'other.example.com', username: 'bob'), + ]; + await build().handle('ssh://alice@203.0.113.7'); + expect(log.single, startsWith('refused:')); + expect(log.any((l) => l.startsWith('open:')), isFalse); + }); + + test('the same link (any case) within the window is ignored', () async { + final h = build(); + await h.handle('ssh://alice@10.0.0.5:2222'); + await h.handle('SSH://ALICE@10.0.0.5:2222'); + expect(log, ['open:Prod']); + clock = clock.add(CliServer.dedupeWindow); + await h.handle('ssh://alice@10.0.0.5:2222'); + expect(log, ['open:Prod', 'open:Prod']); + }); + }); +} diff --git a/app/test/mobile/mobile_lifecycle_coordinator_test.dart b/app/test/mobile/mobile_lifecycle_coordinator_test.dart new file mode 100644 index 00000000..b8ddc801 --- /dev/null +++ b/app/test/mobile/mobile_lifecycle_coordinator_test.dart @@ -0,0 +1,442 @@ +import 'dart:async'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/mobile/lifecycle/background_tasks.dart'; +import 'package:yourssh/mobile/lifecycle/mobile_lifecycle_coordinator.dart'; +import 'package:yourssh/models/port_forward.dart'; +import 'package:yourssh/providers/port_forward_provider.dart'; +import 'package:yourssh/providers/session_provider.dart'; +import 'package:yourssh/services/port_forward_service.dart'; +import 'package:yourssh/services/ssh_service.dart'; +import 'package:yourssh/services/storage_service.dart'; +import 'package:yourssh/services/tab_metadata_service.dart'; + +late List log; + +class _Sessions extends SessionProvider { + _Sessions() : super(SshService(StorageService()), TabMetadataService()); + Completer? verifyGate; + List get calls => log; + + @override + void pauseAll() => log.add('sessions.pauseAll'); + + @override + Future resumePaused( + {Duration stagger = const Duration(milliseconds: 300)}) async { + log.add('sessions.resumePaused'); + } + + @override + Future verifyLive( + {Duration timeout = const Duration(seconds: 3)}) async { + log.add('sessions.verifyLive'); + await verifyGate?.future; + } +} + +class _Forwards extends PortForwardService { + _Forwards(this.running) + : super( + acquireTransport: (_) => throw UnimplementedError(), + resolveHost: (_) => null, + onStatus: (_, __, {error}) {}, + onConnections: (_, __) {}, + ); + Set running; + Completer? stopGate; + Completer? startGate; + + @override + bool isRunning(String id) => running.contains(id); + + @override + Future stopAll() async { + log.add('forwards.stopAll'); + await stopGate?.future; + running = {}; + } + + @override + Future start(PortForward fwd) async { + log.add('forwards.start:${fwd.id}'); + await startGate?.future; + } +} + +class _Rules extends PortForwardProvider { + _Rules(this.rules); + final List rules; + @override + List get forwards => rules; +} + +class _Tasks implements BackgroundTasks { + _Tasks(this.remaining); + final Duration? remaining; + final ended = []; + int lastId = 0; + bool refuse = false; + final gates = >[]; + bool gated = false; + + @override + Future begin() async { + if (refuse) return null; + final id = ++lastId; + if (gated) { + final g = Completer(); + gates.add(g); + await g.future; + } + return BackgroundLease(id: id, remaining: remaining); + } + + @override + Future end(int id) async { + log.add('tasks.end'); + ended.add(id); + } +} + +PortForward _fwd(String id) => + PortForward(id: id, label: id, type: ForwardType.local, localPort: 1000); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _Sessions sessions; + late _Forwards forwards; + late _Tasks tasks; + late MobileLifecycleCoordinator c; + var pairingStops = 0; + + void build({Duration? remaining, Set running = const {}}) { + SharedPreferences.setMockInitialValues({}); + log = []; + pairingStops = 0; + sessions = _Sessions(); + forwards = _Forwards(running); + tasks = _Tasks(remaining); + c = MobileLifecycleCoordinator( + sessions: sessions, + forwards: forwards, + forwardRules: _Rules([_fwd('a'), _fwd('b'), _fwd('c')]), + tasks: tasks, + stagger: Duration.zero, + stopPairing: () async => pairingStops++, + ); + } + + test('the LAN pairing server closes with the pause, not on a quick switch', () { + fakeAsync((fa) { + build(); + c.onBackground(); + fa.elapse(const Duration(seconds: 10)); + c.onForeground(); + fa.flushMicrotasks(); + expect(pairingStops, 0); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + expect(pairingStops, 1); + c.dispose(); + }); + }); + + test('a quick app switch pauses nothing and ends the task', () { + fakeAsync((fa) { + build(); + c.onBackground(); + fa.elapse(const Duration(seconds: 10)); + c.onForeground(); + fa.flushMicrotasks(); + expect(sessions.calls, isNot(contains('sessions.pauseAll'))); + expect(tasks.ended, [tasks.lastId]); + expect(tasks.ended, hasLength(1)); + c.dispose(); + }); + }); + + test('grace expiry stops forwards, then pauses sessions, then ends the task', + () { + fakeAsync((fa) { + build(); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + expect(log, ['forwards.stopAll', 'sessions.pauseAll', 'tasks.end']); + c.dispose(); + }); + }); + + test('grace follows the OS allowance', () { + fakeAsync((fa) { + build(remaining: const Duration(seconds: 12)); + c.onBackground(); + fa.elapse(const Duration(seconds: 6, milliseconds: 900)); + fa.flushMicrotasks(); + expect(log, isEmpty); + fa.elapse(const Duration(milliseconds: 200)); + fa.flushMicrotasks(); + expect(log, contains('sessions.pauseAll')); + c.dispose(); + }); + }); + + test('no lease means no grace: pause immediately', () { + fakeAsync((fa) { + build(); + tasks.refuse = true; + c.onBackground(); + fa.flushMicrotasks(); + expect(log, ['forwards.stopAll', 'sessions.pauseAll']); + c.dispose(); + }); + }); + + test('a lease shorter than 5 s clamps the grace at zero', () { + fakeAsync((fa) { + build(remaining: const Duration(seconds: 3)); + c.onBackground(); + fa.flushMicrotasks(); + expect(log, contains('sessions.pauseAll')); + c.dispose(); + }); + }); + + test( + 'foreground resumes paused sessions, probes the rest, restarts recorded forwards', + () { + fakeAsync((fa) { + build(running: {'a', 'b'}); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + log.clear(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log, [ + 'sessions.resumePaused', + 'sessions.verifyLive', + 'forwards.start:a', + 'forwards.start:b', + ]); + // A second foreground without a pause restarts nothing. + log.clear(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log.where((e) => e.startsWith('forwards.start')), isEmpty); + c.dispose(); + }); + }); + + test('backgrounding again while verifyLive is pending restarts no forwards', + () { + fakeAsync((fa) { + build(running: {'a', 'b'}); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + log.clear(); + sessions.verifyGate = Completer(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log, ['sessions.resumePaused', 'sessions.verifyLive']); + c.onBackground(); + fa.flushMicrotasks(); + sessions.verifyGate!.complete(); + fa.flushMicrotasks(); + expect(log.where((e) => e.startsWith('forwards.start')), isEmpty); + // The forwards survive for the next foreground. + log.clear(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + log.clear(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log.where((e) => e.startsWith('forwards.start')), + ['forwards.start:a', 'forwards.start:b']); + c.dispose(); + }); + }); + + test('a stale foreground that loses the race leaves no forward stopped', () { + fakeAsync((fa) { + build(running: {'a', 'b'}); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + log.clear(); + final gate = sessions.verifyGate = Completer(); + c.onForeground(); // fg1: stuck in verifyLive + fa.flushMicrotasks(); + c.onBackground(); // quick switch: no grace expiry yet + fa.flushMicrotasks(); + sessions.verifyGate = null; + c.onForeground(); // fg2 runs to completion + fa.flushMicrotasks(); + gate.complete(); // fg1 wakes up stale + fa.flushMicrotasks(); + expect(log.where((e) => e.startsWith('forwards.start')), + unorderedEquals(['forwards.start:a', 'forwards.start:b'])); + c.dispose(); + }); + }); + + test('backgrounding again mid-loop stops restarting the remaining forwards', + () { + fakeAsync((fa) { + build(running: {'a', 'b'}); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + log.clear(); + forwards.startGate = Completer(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log.where((e) => e.startsWith('forwards.start')), + ['forwards.start:a']); + c.onBackground(); + fa.flushMicrotasks(); + forwards.startGate!.complete(); + fa.flushMicrotasks(); + expect(log.where((e) => e.startsWith('forwards.start')), + ['forwards.start:a']); + c.dispose(); + }); + }); + + test('a foreground during a slow stopAll does not leave sessions paused', () { + fakeAsync((fa) { + build(running: {'a'}); + forwards.stopGate = Completer(); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + expect(log, ['forwards.stopAll']); + c.onForeground(); + fa.flushMicrotasks(); + forwards.stopGate!.complete(); + fa.flushMicrotasks(); + expect(log, [ + 'forwards.stopAll', + 'tasks.end', + 'sessions.resumePaused', + 'sessions.verifyLive', + 'forwards.start:a', + ]); + c.dispose(); + }); + }); + + test('bg1 expiry in flight, fg1, bg2: the stale foreground does nothing', () { + fakeAsync((fa) { + build(running: {'a'}); + forwards.stopGate = Completer(); + c.onBackground(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + c.onForeground(); // fg1: waits for the expiry + fa.flushMicrotasks(); + c.onBackground(); // bg2 while fg1 is still waiting + fa.flushMicrotasks(); + forwards.stopGate!.complete(); + fa.flushMicrotasks(); + // No pause for bg1, nothing resumed/restarted while backgrounded, and + // bg2's lease is still held. + expect(log, ['forwards.stopAll', 'tasks.end']); + expect(tasks.ended, [1]); + log.clear(); + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + expect(log, ['forwards.stopAll', 'sessions.pauseAll', 'tasks.end']); + log.clear(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log, [ + 'sessions.resumePaused', + 'sessions.verifyLive', + 'forwards.start:a', // remembered across both backgrounds, once + ]); + c.dispose(); + }); + }); + + test('a foreground without a background (Face ID sheet) probes nothing', () { + fakeAsync((fa) { + build(); + c.onForeground(); + fa.flushMicrotasks(); + expect(log, isEmpty); + c.dispose(); + }); + }); + + test('background, foreground, background within one begin ends the first lease', + () { + fakeAsync((fa) { + build(); + tasks.gated = true; + c.onBackground(); + c.onForeground(); + c.onBackground(); + fa.flushMicrotasks(); + expect(tasks.gates, hasLength(2)); + tasks.gates[0].complete(); + tasks.gates[1].complete(); + fa.flushMicrotasks(); + expect(tasks.ended, [1]); // the stale lease is released at once + fa.elapse(const Duration(seconds: 25)); + fa.flushMicrotasks(); + expect(log.where((e) => e == 'sessions.pauseAll'), hasLength(1)); + expect(tasks.ended, [1, 2]); + c.dispose(); + }); + }); + + test('dispose cancels a pending grace timer', () { + fakeAsync((fa) { + build(); + c.onBackground(); + fa.flushMicrotasks(); + c.dispose(); + fa.elapse(const Duration(seconds: 60)); + fa.flushMicrotasks(); + expect(log, isNot(contains('sessions.pauseAll'))); + }); + }); + + group('MethodChannelBackgroundTasks', () { + const channel = MethodChannel('yourssh/background'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + test('maps begin to a lease, -1 to unknown, and null to refused', () async { + Object? reply = {'id': 7, 'remainingMs': 12000}; + messenger.setMockMethodCallHandler(channel, (_) async => reply); + final t = MethodChannelBackgroundTasks(); + var l = await t.begin(); + expect(l!.id, 7); + expect(l.remaining, const Duration(seconds: 12)); + reply = {'id': 8, 'remainingMs': -1}; + expect((await t.begin())!.remaining, isNull); + reply = null; + expect(await t.begin(), isNull); + }); + + test('end sends the id', () async { + Object? got; + messenger.setMockMethodCallHandler(channel, (c) async { + got = [c.method, c.arguments]; + return null; + }); + await MethodChannelBackgroundTasks().end(7); + expect(got, ['end', 7]); + }); + }); +} diff --git a/app/test/mobile/mobile_sftp_screen_test.dart b/app/test/mobile/mobile_sftp_screen_test.dart index 8ac74066..4d0c7085 100644 --- a/app/test/mobile/mobile_sftp_screen_test.dart +++ b/app/test/mobile/mobile_sftp_screen_test.dart @@ -1,14 +1,45 @@ +import 'dart:io'; + +import 'package:dartssh2/dartssh2.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh/mobile/screens/mobile_sftp_screen.dart'; import 'package:yourssh/models/host.dart'; +import 'package:yourssh/models/ssh_session.dart'; +import 'package:yourssh/providers/session_provider.dart'; +import 'package:yourssh/services/tab_metadata_service.dart'; import 'package:yourssh/services/sftp_transfer_service.dart'; import 'package:yourssh/services/ssh_service.dart'; import 'package:yourssh/services/storage_service.dart'; import 'package:yourssh/theme/app_theme.dart'; +class _FakeSftp implements SftpClient { + _FakeSftp(this.names, {this.fail = false, this.error}); + final List names; + final bool fail; + final Object? error; + bool closed = false; + + @override + Future> listdir(String path) async { + if (error != null) throw error!; + if (fail) throw StateError('channel closed'); + return [ + for (final n in names) + SftpName( + filename: n, longname: n, attr: SftpFileAttrs(size: 1, mode: null)), + ]; + } + + @override + void close() => closed = true; + + @override + dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i); +} + // Updated after Task 13 redesign: MobileSftpScreen is now contextual and // requires a [Host]. The full smoke-test suite lives in // test/mobile/screens/sftp_screen_test.dart. @@ -46,4 +77,121 @@ void main() { expect(find.textContaining('Empty'), findsOneWidget); }); + + testWidgets('recovers when the cached SFTP channel died while paused', + (tester) async { + final storage = StorageService(); + final ssh = SshService(storage); + final transfer = SftpTransferService(ssh); + final host = Host( + id: 'h1', label: 'web-01', host: '10.0.0.1', port: 22, username: 'u'); + final dead = _FakeSftp(['old'], fail: true); + final fresh = _FakeSftp(['new.txt']); + final queue = [dead, fresh]; + var opened = 0; + + await tester.pumpWidget(MaterialApp( + builder: ysRootBuilderTouch, + home: MultiProvider( + providers: [ + Provider.value(value: ssh), + Provider.value(value: transfer), + ], + child: MobileSftpScreen( + host: host, + sftpOpener: () async { + opened++; + return queue.removeAt(0); + }, + ), + ), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(find.text('new.txt'), findsOneWidget); + expect(opened, 2, reason: 'the dead channel was replaced'); + expect(dead.closed, isTrue); + }); + + testWidgets('does not re-dial a dead channel while sessions are paused', + (tester) async { + final storage = StorageService(); + final ssh = SshService(storage); + final transfer = SftpTransferService(ssh); + final host = Host( + id: 'h1', label: 'web-01', host: '10.0.0.1', port: 22, username: 'u'); + final sessions = SessionProvider(ssh, TabMetadataService()); + addTearDown(sessions.dispose); + sessions.addSessionForTest( + SshSession(host: host, status: SessionStatus.connected)); + sessions.pauseAll(); + var opened = 0; + + await tester.pumpWidget(MaterialApp( + builder: ysRootBuilderTouch, + home: MultiProvider( + providers: [ + Provider.value(value: ssh), + Provider.value(value: transfer), + ChangeNotifierProvider.value(value: sessions), + ], + child: MobileSftpScreen( + host: host, + sftpOpener: () async { + opened++; + return _FakeSftp(['old'], fail: true); + }, + ), + ), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(opened, 1, reason: 'no second dial while paused'); + expect(find.textContaining('channel closed'), findsWidgets); + }); + + testWidgets('a protocol-level SFTP error does not drop or retry the channel', + (tester) async { + final storage = StorageService(); + final ssh = SshService(storage); + final transfer = SftpTransferService(ssh); + final host = Host( + id: 'h1', label: 'web-01', host: '10.0.0.1', port: 22, username: 'u'); + final denied = _FakeSftp([], error: SftpStatusError(3, 'permission denied')); + var opened = 0; + + await tester.pumpWidget(MaterialApp( + builder: ysRootBuilderTouch, + home: MultiProvider( + providers: [ + Provider.value(value: ssh), + Provider.value(value: transfer), + ], + child: MobileSftpScreen( + host: host, + sftpOpener: () async { + opened++; + return denied; + }, + ), + ), + )); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(opened, 1, reason: 'no retry on a server-side status error'); + expect(denied.closed, isFalse, reason: 'shared channel stays open'); + expect(find.textContaining('permission denied'), findsOneWidget); + }); + + test('isDeadChannelError classifies connection vs. operation errors', () { + expect(isDeadChannelError(const SocketException('reset')), isTrue); + expect(isDeadChannelError(SftpAbortError('closed')), isTrue); + expect(isDeadChannelError(SSHStateError('not connected')), isTrue); + expect(isDeadChannelError(StateError('closed')), isTrue); + expect(isDeadChannelError(SftpStatusError(3, 'denied')), isFalse); + expect(isDeadChannelError(const FileSystemException('disk full')), isFalse); + }); } diff --git a/app/test/mobile/mobile_terminal_paused_test.dart b/app/test/mobile/mobile_terminal_paused_test.dart new file mode 100644 index 00000000..3f54b2eb --- /dev/null +++ b/app/test/mobile/mobile_terminal_paused_test.dart @@ -0,0 +1,47 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:xterm/xterm.dart'; +import 'package:yourssh/mobile/screens/mobile_terminal_screen.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/models/ssh_session.dart'; +import 'package:yourssh/providers/session_provider.dart'; +import 'package:yourssh/providers/settings_provider.dart'; +import 'package:yourssh/services/ssh_service.dart'; +import 'package:yourssh/services/storage_service.dart'; +import 'package:yourssh/services/tab_metadata_service.dart'; + +import '../helpers/ys_test_app.dart'; + +class _Sessions extends SessionProvider { + _Sessions(this.list) + : super(SshService(StorageService()), TabMetadataService()); + final List list; + @override + List get sshSessions => list; +} + +void main() { + testWidgets('terminal shows the paused state and mounts no TerminalView', + (t) async { + SharedPreferences.setMockInitialValues({}); + final s = SshSession( + host: Host(id: 'h', label: 'h', host: 'h.com', username: 'u'), + status: SessionStatus.disconnected, + )..paused = true; + final sessions = _Sessions([s]); + final settings = SettingsProvider(); + await t.pumpWidget(MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: sessions), + ChangeNotifierProvider.value(value: settings), + ], + child: ysTestApp(const MobileTerminalScreen(), touch: true), + )); + await t.pump(); + expect(find.text('Session paused — reconnecting'), findsOneWidget); + expect(find.byType(TerminalView), findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +} diff --git a/app/test/mobile/open_session_test.dart b/app/test/mobile/open_session_test.dart new file mode 100644 index 00000000..9314f8c1 --- /dev/null +++ b/app/test/mobile/open_session_test.dart @@ -0,0 +1,70 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/mobile/navigation/open_session.dart'; +import 'package:yourssh/mobile/screens/mobile_terminal_screen.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/models/ssh_session.dart'; +import 'package:yourssh/providers/host_provider.dart'; +import 'package:yourssh/providers/session_provider.dart'; +import 'package:yourssh/providers/settings_provider.dart'; +import 'package:yourssh/services/ssh_service.dart'; +import 'package:yourssh/services/storage_service.dart'; +import 'package:yourssh/services/tab_metadata_service.dart'; +import 'package:yourssh/theme/app_theme.dart'; + +Future _pump(WidgetTester t, Host host, + {void Function(SessionProvider)? seed}) async { + final sessions = + SessionProvider(SshService(StorageService()), TabMetadataService()); + seed?.call(sessions); + await t.pumpWidget(MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: sessions), + ChangeNotifierProvider( + create: (_) => HostProvider(StorageService())), + ChangeNotifierProvider( + create: (_) => SettingsProvider()), + ], + child: MaterialApp( + builder: ysRootBuilderTouch, + home: Builder( + builder: (ctx) => TextButton( + onPressed: () => openMobileSession(Navigator.of(ctx), host), + child: const Text('open'), + ), + ), + ), + )); + await t.tap(find.text('open')); + await t.pump(); + await t.pump(const Duration(milliseconds: 300)); + return sessions; +} + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + testWidgets('an RDP host is refused on mobile: notice, no session, no route', + (t) async { + final host = Host( + label: 'Win', host: '1.1.1.1', username: 'a', protocol: HostProtocol.rdp); + final sessions = await _pump(t, host); + expect(sessions.sessions, isEmpty); + expect(find.text('RDP and VNC hosts open in the desktop app'), + findsOneWidget); + expect(find.byType(MobileTerminalScreen), findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + + testWidgets('an SSH host with a live session reuses it', (t) async { + final host = Host(label: 'Box', host: '127.0.0.1', username: 'a'); + late int before; + final sessions = await _pump(t, host, seed: (sp) { + sp.sessions.add(SshSession(host: host)); + before = sp.sessions.length; + }); + expect(sessions.sessions.length, before); + expect(find.byType(MobileTerminalScreen), findsOneWidget); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +} diff --git a/app/test/mobile/screens/settings_screen_test.dart b/app/test/mobile/screens/settings_screen_test.dart index b55f92d4..37f7a230 100644 --- a/app/test/mobile/screens/settings_screen_test.dart +++ b/app/test/mobile/screens/settings_screen_test.dart @@ -1,5 +1,6 @@ import 'package:yourssh_ui/yourssh_ui.dart'; import 'package:yourssh/theme/app_theme.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:package_info_plus/package_info_plus.dart'; @@ -63,6 +64,26 @@ void main() { expect(find.text('TERMINAL'), findsOneWidget); }); + testWidgets('the ssh:// links switch exists only on iOS', (tester) async { + await _pump(tester); + expect(find.text('Open ssh:// links'), findsNothing); + }); + + testWidgets('on iOS the ssh:// links switch persists kSshLinksPrefKey', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await _pump(tester); + final sw = find.descendant( + of: find.ancestor(of: find.text('Open ssh:// links'), matching: find.byType(Row)).last, + matching: find.byType(FSwitch), + ); + expect(tester.widget(sw).value, isFalse); + await tester.tap(sw); + await tester.pumpAndSettle(); + expect((await SharedPreferences.getInstance()).getBool(kSshLinksPrefKey), isTrue); + }); + testWidgets('renders SECURITY section header', (tester) async { await _pump(tester); expect(find.text('SECURITY'), findsOneWidget); diff --git a/app/test/platform/ios_plist_test.dart b/app/test/platform/ios_plist_test.dart new file mode 100644 index 00000000..aebbcc6b --- /dev/null +++ b/app/test/platform/ios_plist_test.dart @@ -0,0 +1,56 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('Info.plist and privacy manifest carry the required entries', () { + final plist = File('ios/Runner/Info.plist').readAsStringSync(); + for (final k in [ + 'NSCameraUsageDescription', + 'NSLocalNetworkUsageDescription', + 'NSFaceIDUsageDescription', + 'NSPhotoLibraryUsageDescription', + 'NSAppleMusicUsageDescription', + 'NSLocationWhenInUseUsageDescription', + 'UIFileSharingEnabled', + 'LSSupportsOpeningDocumentsInPlace', + ]) { + expect(plist, contains('$k')); + } + expect( + plist, + matches(RegExp(r'ITSAppUsesNonExemptEncryption\s*')), + ); + expect(plist, isNot(contains('NSAppTransportSecurity'))); + for (final k in [ + 'NSCameraUsageDescription', + 'NSLocalNetworkUsageDescription', + 'NSFaceIDUsageDescription', + 'NSPhotoLibraryUsageDescription', + 'NSAppleMusicUsageDescription', + 'NSLocationWhenInUseUsageDescription', + ]) { + expect( + plist, + matches(RegExp('$k\\s*[^<\\s][^<]*')), + ); + } + final pm = File('ios/Runner/PrivacyInfo.xcprivacy').readAsStringSync(); + expect(pm, matches(RegExp(r'NSPrivacyTracking\s*'))); + for (final k in [ + 'NSPrivacyCollectedDataTypes', + 'NSPrivacyTrackingDomains', + ]) { + expect(pm, matches(RegExp('$k\\s*'))); + } + expect(pm, contains('NSPrivacyAccessedAPICategoryUserDefaults')); + expect(pm, contains('NSPrivacyAccessedAPICategoryDiskSpace')); + expect(pm, contains('E174.1')); + expect(pm, contains('CA92.1')); + expect(pm, contains('C617.1')); + expect( + File('ios/Runner.xcodeproj/project.pbxproj').readAsStringSync(), + contains('PrivacyInfo.xcprivacy in Resources'), + ); + }); +} diff --git a/app/test/platform/ios_runner_config_test.dart b/app/test/platform/ios_runner_config_test.dart new file mode 100644 index 00000000..09fc9795 --- /dev/null +++ b/app/test/platform/ios_runner_config_test.dart @@ -0,0 +1,35 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('runner config', () { + final proj = + File('ios/Runner.xcodeproj/project.pbxproj').readAsStringSync(); + expect(proj, contains('PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh;')); + Set all(String key) => RegExp('$key = "?([^";]+)"?;') + .allMatches(proj) + .map((m) => m[1]!) + .toSet(); + expect(all('IPHONEOS_DEPLOYMENT_TARGET'), {'16.0'}); + expect(all('TARGETED_DEVICE_FAMILY'), {'1'}); + expect(proj, contains('DEVELOPMENT_TEAM = 84T567KMYD;')); + expect(proj, contains('YourSshNative.swift in Sources')); + expect(File('ios/Podfile').readAsStringSync(), + contains("\nplatform :ios, '16.0'")); + final plist = File('ios/Runner/Info.plist').readAsStringSync(); + expect( + plist, + matches(RegExp( + r'CFBundleDisplayName\s*YourSSH'))); + expect(plist, contains('UIApplicationSceneManifest')); + expect( + File('ios/Runner/AppDelegate.swift').readAsStringSync(), + allOf(contains('didInitializeImplicitFlutterEngine'), + contains('YourSshNative.register'))); + final lock = File('ios/Podfile.lock'); + if (lock.existsSync()) { + expect(lock.readAsStringSync(), isNot(contains('GoogleMLKit'))); + } + }); +} diff --git a/app/test/platform/runtime_platform_test.dart b/app/test/platform/runtime_platform_test.dart index 95fa2557..c98a21af 100644 --- a/app/test/platform/runtime_platform_test.dart +++ b/app/test/platform/runtime_platform_test.dart @@ -26,4 +26,27 @@ void main() { debugDefaultTargetPlatformOverride = TargetPlatform.linux; expect(isMobilePlatform, isFalse); }); + + test('iOS: no subprocesses or remote desktop; tmux default on', () { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + expect(isIOSPlatform, isTrue); + expect(supportsSubprocesses, isFalse); + expect(supportsRemoteDesktop, isFalse); + expect(mobileDefaultTmux, isTrue); + }); + + test('Android: subprocesses yes, remote desktop no, tmux default on', () { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + expect(isIOSPlatform, isFalse); + expect(supportsSubprocesses, isTrue); + expect(supportsRemoteDesktop, isFalse); + expect(mobileDefaultTmux, isTrue); + }); + + test('macOS keeps every desktop capability', () { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + expect(isIOSPlatform, isFalse); + expect(supportsSubprocesses && supportsRemoteDesktop, isTrue); + expect(mobileDefaultTmux, isFalse); + }); } diff --git a/app/test/providers/host_provider_secret_failure_test.dart b/app/test/providers/host_provider_secret_failure_test.dart new file mode 100644 index 00000000..1ced8814 --- /dev/null +++ b/app/test/providers/host_provider_secret_failure_test.dart @@ -0,0 +1,92 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/providers/host_provider.dart'; +import 'package:yourssh/services/storage_service.dart'; + +/// In-memory store whose savePassword can be told to fail on the Nth call. +class _FakeStorage extends StorageService { + final secrets = {}; + int saves = 0; + int? failOnSave; + + @override + Future savePassword(String hostId, String password) async { + saves++; + if (failOnSave == saves) { + throw SecretStoreException('pw_$hostId', 'keychain locked'); + } + secrets[hostId] = password; + } + + @override + Future loadPassword(String hostId) async => secrets[hostId]; + + @override + Future deletePassword(String hostId) async => secrets.remove(hostId); + + @override + Future deleteHostSecrets(String hostId) async => + secrets.remove(hostId); +} + +Host _h(String id) => + Host(id: id, label: id, host: '1.2.3.4', port: 22, username: 'u'); + +void main() { + late _FakeStorage storage; + late HostProvider provider; + late int mutations; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + storage = _FakeStorage(); + provider = HostProvider(storage); + mutations = 0; + provider.onMutation = () async => mutations++; + await Future.delayed(Duration.zero); + }); + + test('addHost: failed secret write leaves no host and no mutation', () async { + storage.failOnSave = 1; + await expectLater(provider.addHost(_h('a'), password: 'pw'), + throwsA(isA())); + expect(provider.allHosts, isEmpty); + expect((await storage.loadHosts()), isEmpty); + expect(mutations, 0); + + // Save again (keychain recovered): exactly one host, no duplicate. + storage.failOnSave = null; + await provider.addHost(_h('a'), password: 'pw'); + expect(provider.allHosts.length, 1); + expect(storage.secrets['a'], 'pw'); + }); + + test('updateHost: failed secret write keeps the old host', () async { + await provider.addHost(_h('a'), password: 'old'); + storage.failOnSave = storage.saves + 1; + final edited = _h('a').copyWith(label: 'renamed'); + await expectLater(provider.updateHost(edited, password: 'new'), + throwsA(isA())); + expect(provider.allHosts.single.label, 'a'); + expect((await storage.loadHosts()).single.label, 'a'); + expect(storage.secrets['a'], 'old'); + }); + + test('replaceAll: failure on the 2nd password changes nothing', () async { + await provider.addHost(_h('a'), password: 'oldA'); + await provider.addHost(_h('b'), password: 'oldB'); + mutations = 0; + storage.failOnSave = storage.saves + 2; + await expectLater( + provider.replaceAll( + [_h('a'), _h('b'), _h('c')], + {'pw_a': 'newA', 'pw_b': 'newB', 'pw_c': 'newC'}, + ), + throwsA(isA()), + ); + expect(provider.allHosts.map((h) => h.id), ['a', 'b']); + expect((await storage.loadHosts()).map((h) => h.id), ['a', 'b']); + expect(storage.secrets, {'a': 'oldA', 'b': 'oldB'}); + }); +} diff --git a/app/test/providers/key_provider_test.dart b/app/test/providers/key_provider_test.dart index 574aee57..8ef48a8f 100644 --- a/app/test/providers/key_provider_test.dart +++ b/app/test/providers/key_provider_test.dart @@ -1,4 +1,6 @@ import 'dart:io'; + +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh/providers/key_provider.dart'; @@ -8,6 +10,7 @@ void main() { setUp(() => SharedPreferences.setMockInitialValues({})); _keyRemovalTests(); + ownedKeysTests(); group('KeyProvider certificate methods', () { test('setCertificate persists certificatePath on the key entry', () async { @@ -54,8 +57,10 @@ void main() { } String _tmpKeyFile() { - final f = File('${Directory.systemTemp.path}${Platform.pathSeparator}' - 'test_key_${DateTime.now().millisecondsSinceEpoch}'); + final f = File( + '${Directory.systemTemp.path}${Platform.pathSeparator}' + 'test_key_${DateTime.now().millisecondsSinceEpoch}', + ); f.writeAsStringSync('placeholder'); return f.path; } @@ -128,3 +133,132 @@ void _keyRemovalTests() { }); }); } + +void ownedKeysTests() { + group('KeyProvider app-owned keys dir', () { + late Directory root; + setUp(() { + SharedPreferences.setMockInitialValues({}); + root = Directory.systemTemp.createTempSync('kp_owned'); + }); + tearDown(() { + debugDefaultTargetPlatformOverride = null; + root.deleteSync(recursive: true); + }); + + Directory keysIn(String name) => + Directory('${root.path}/$name/Library/Application Support/keys') + ..createSync(recursive: true); + + Future seed(String keyPath, {String? cert}) async { + final seeder = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => '/unused', + ); + await seeder.ready; + final e = await seeder.addKeyFromFile(keyPath, 'k'); + if (cert != null) await seeder.setCertificate(e.id, cert); + } + + test('iOS: stale container path is rebased onto the current keys dir and persisted', () async { + final a = keysIn('A'); + final b = keysIn('B'); + File('${a.path}/id_ed25519').writeAsStringSync('k'); + File('${a.path}/id_ed25519-cert.pub').writeAsStringSync('c'); + await seed('${a.path}/id_ed25519', cert: '${a.path}/id_ed25519-cert.pub'); + a.parent.parent.parent.deleteSync(recursive: true); // old container gone + File('${b.path}/id_ed25519').writeAsStringSync('k'); + File('${b.path}/id_ed25519-cert.pub').writeAsStringSync('c'); + + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + final prov = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => b.path, + ); + await prov.ready; + expect(prov.keys.single.privateKeyPath, '${b.path}/id_ed25519'); + expect(prov.keys.single.certificatePath, '${b.path}/id_ed25519-cert.pub'); + + final again = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => '/unused', + ); + await again.ready; + expect(again.keys.single.privateKeyPath, '${b.path}/id_ed25519'); + }); + + test('iOS: a path outside the keys dir is left untouched', () async { + final b = keysIn('B'); + final outside = File('${root.path}/elsewhere/id_rsa') + ..createSync(recursive: true); + await seed(outside.path); + outside.deleteSync(); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + final prov = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => b.path, + ); + await prov.ready; + expect(prov.keys.single.privateKeyPath, outside.path); + }); + + test('non-iOS: stale path is not rebased', () async { + final a = keysIn('A'); + final b = keysIn('B'); + File('${a.path}/id_ed25519').writeAsStringSync('k'); + await seed('${a.path}/id_ed25519'); + a.parent.parent.parent.deleteSync(recursive: true); + File('${b.path}/id_ed25519').writeAsStringSync('k'); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + final prov = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => b.path, + ); + await prov.ready; + expect(prov.keys.single.privateKeyPath, '${a.path}/id_ed25519'); + }); + + test( + 'deleteKey removes key, .pub and cert files under the keys dir', + () async { + final d = keysIn('A'); + final files = [ + File('${d.path}/id_x'), + File('${d.path}/id_x.pub'), + File('${d.path}/id_x-cert.pub'), + ]; + for (final f in files) { + f.writeAsStringSync('x'); + } + final prov = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => d.path, + ); + await prov.ready; + final e = await prov.addKeyFromFile('${d.path}/id_x', 'x'); + await prov.deleteKey(e.id); + for (final f in files) { + expect(f.existsSync(), isFalse, reason: f.path); + } + }, + ); + + test('deleteKey never touches files outside the keys dir', () async { + final d = keysIn('A'); + final ssh = Directory('${root.path}/home/.ssh') + ..createSync(recursive: true); + final key = File('${ssh.path}/id_rsa')..writeAsStringSync('x'); + final pub = File('${ssh.path}/id_rsa.pub')..writeAsStringSync('x'); + final cert = File('${ssh.path}/id_rsa-cert.pub')..writeAsStringSync('x'); + final prov = KeyProvider( + discoverSshKeys: false, + keysDirPath: () async => d.path, + ); + await prov.ready; + final e = await prov.addKeyFromFile(key.path, 'r'); + await prov.deleteKey(e.id); + expect(key.existsSync() && pub.existsSync() && cert.existsSync(), isTrue); + expect(prov.keys, isEmpty); + }); + }); +} diff --git a/app/test/providers/session_provider_audit_test.dart b/app/test/providers/session_provider_audit_test.dart index d52a8d58..1b47098c 100644 --- a/app/test/providers/session_provider_audit_test.dart +++ b/app/test/providers/session_provider_audit_test.dart @@ -34,6 +34,7 @@ class _FakeSsh extends SshService { Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + bool Function()? isCurrent, }) async { if (failConnect) throw Exception('refused'); return _NullClient(); diff --git a/app/test/providers/session_provider_connection_log_test.dart b/app/test/providers/session_provider_connection_log_test.dart index 2c670ac7..a318d2f7 100644 --- a/app/test/providers/session_provider_connection_log_test.dart +++ b/app/test/providers/session_provider_connection_log_test.dart @@ -36,6 +36,7 @@ class _FakeSsh extends SshService { Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + bool Function()? isCurrent, }) async { final gate = connectGate; if (gate != null) await gate.future; diff --git a/app/test/providers/session_provider_jump_test.dart b/app/test/providers/session_provider_jump_test.dart index 56b37d58..9c4a8d34 100644 --- a/app/test/providers/session_provider_jump_test.dart +++ b/app/test/providers/session_provider_jump_test.dart @@ -23,6 +23,7 @@ class _CapturingSsh extends SshService { Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + bool Function()? isCurrent, }) async { capturedChain = jumpChain; throw Exception('stop-before-shell'); diff --git a/app/test/providers/session_provider_pause_test.dart b/app/test/providers/session_provider_pause_test.dart new file mode 100644 index 00000000..1a4d0db9 --- /dev/null +++ b/app/test/providers/session_provider_pause_test.dart @@ -0,0 +1,362 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/models/ssh_key.dart'; +import 'package:yourssh/models/ssh_session.dart'; +import 'package:yourssh/providers/session_provider.dart'; +import 'package:yourssh/services/ssh_service.dart'; +import 'package:yourssh/services/storage_service.dart'; +import 'package:yourssh/services/tab_metadata_service.dart'; + +class _FakeClient implements SSHClient { + _FakeClient({this.closed = false, this.pingFuture}); + final bool closed; + final Future? pingFuture; + bool closeCalled = false; + @override + void close() => closeCalled = true; + @override + bool get isClosed => closed; + @override + Future ping() => pingFuture ?? Future.value(); + @override + dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i); +} + +class _Ssh extends SshService { + _Ssh() : super(StorageService()); + final connects = []; + final disconnects = []; + final sessionDisconnects = []; + int shellsOpened = 0; + final shellDone = Completer(); + bool connectCompletes = false; + + @override + Future connect( + Host host, { + SshKeyEntry? keyEntry, + List jumpChain = const [], + Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, + Future Function(Host hop, String keyType, Uint8List fp)? + verifyHopHostKey, + bool Function()? isCurrent, + }) { + connects.add(host.id); + if (connectCompletes) return Future.value(_FakeClient()); + return Completer().future; + } + + @override + Future openShell(SshSession session, + {bool useTmux = false, String termType = 'xterm-256color'}) { + shellsOpened++; + return shellDone.future; + } + + @override + void disconnectSession(String sessionId) => sessionDisconnects.add(sessionId); + + @override + void disconnect(String hostId) => disconnects.add(hostId); +} + +class _ScriptedShell implements SSHSession { + final written = []; + final _out = StreamController(); + final _err = StreamController(); + @override + bool get agentForwardingRefused => false; + @override + Stream get stdout => _out.stream; + @override + Stream get stderr => _err.stream; + @override + void write(Uint8List data) => written.add(String.fromCharCodes(data)); + @override + void resizeTerminal(int w, int h, [int pw = 0, int ph = 0]) {} + @override + Future close() async { + await _out.close(); + await _err.close(); + } + + @override + dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i); +} + +class _ScriptedClient extends _FakeClient { + _ScriptedClient(this.scripted); + final _ScriptedShell scripted; + @override + Future shell({ + SSHPtyConfig? pty = const SSHPtyConfig(), + SSHX11Config? x11, + Map? environment, + }) async => + scripted; +} + +class _GatedSsh extends _Ssh { + final connectGate = Completer(); + @override + Future connect( + Host host, { + SshKeyEntry? keyEntry, + List jumpChain = const [], + Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, + Future Function(Host hop, String keyType, Uint8List fp)? + verifyHopHostKey, + bool Function()? isCurrent, + }) => + connectGate.future; +} + +Host _host(String id) => + Host(id: id, label: id, host: '$id.com', username: 'u', detectedOs: 'ubuntu'); + +SshSession _session(String hostId, SessionStatus status) => + SshSession(host: _host(hostId), status: status); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late _Ssh ssh; + late SessionProvider p; + setUp(() { + SharedPreferences.setMockInitialValues({}); + ssh = _Ssh(); + p = SessionProvider(ssh, TabMetadataService()); + }); + tearDown(() => p.dispose()); + + test('pauseAll pauses connected and reconnecting sessions, closes each host once', + () { + final a1 = _session('A', SessionStatus.connected); + final a2 = _session('A', SessionStatus.connecting); + final b = _session('B', SessionStatus.connected); + final err = _session('C', SessionStatus.error); + final closed = _session('D', SessionStatus.disconnected); + for (final s in [a1, a2, b, err, closed]) { + p.addSessionForTest(s); + } + final dropped = []; + p.onSessionDropped = (s, r) => dropped.add(s); + + p.pauseAll(); + + for (final s in [a1, a2, b]) { + expect(s.paused, isTrue); + expect(s.status, SessionStatus.disconnected); + expect(s.acceptsInput, isFalse); + } + expect(err.paused, isFalse); + expect(err.status, SessionStatus.error); + expect(closed.paused, isFalse); + expect(ssh.disconnects, ['A', 'B']); + // Every paused session's own shell is closed too (clients are per tab). + expect(ssh.sessionDisconnects, unorderedEquals([a1.id, a2.id, b.id])); + expect(dropped, isEmpty); + }); + + test('pauseAll cancels a pending reconnect and writes a dim marker', () { + fakeAsync((fa) { + final host = _host('A'); + final s = SshSession(host: host, status: SessionStatus.connected); + p.addSessionForTest(s); + p.reconnectAttempts = () => 0; + p.autoReconnectEnabled = () => true; + p.scheduleReconnectForTest(s); + expect(s.status, SessionStatus.connecting); + p.pauseAll(); + fa.elapse(const Duration(seconds: 30)); + // The countdown timer is gone: no reconnect attempt started. + expect(ssh.connects, isEmpty); + expect(s.status, SessionStatus.disconnected); + expect(s.terminal.buffer.toString(), + contains('[Paused while YourSSH was in the background]')); + expect(s.terminal.buffer.toString(), isNot(contains('Reconnecting now'))); + }); + }); + + test('a paused session whose shell closes schedules no reconnect', () async { + ssh.connectCompletes = true; + p.autoReconnectEnabled = () => true; + final dropped = []; + p.onSessionDropped = (s, r) => dropped.add(s); + final done = p.connect(_host('A')); + await Future.delayed(Duration.zero); + final s = p.sshSessions.single; + expect(s.status, SessionStatus.connected); + + p.pauseAll(); + ssh.shellDone.complete(); + await done; + + expect(s.status, SessionStatus.disconnected); + expect(s.paused, isTrue); + expect(s.reconnectCount, 0); + expect(s.terminal.buffer.toString(), isNot(contains('Reconnecting'))); + expect(dropped, isEmpty); + }); + + test('an attempt superseded by a pause stops quietly when it later fails', + () async { + p.autoReconnectEnabled = () => true; + final failing = _GatedSsh(); + final q = SessionProvider(failing, TabMetadataService()); + addTearDown(q.dispose); + final dropped = []; + q.onSessionDropped = (s, r) => dropped.add(s); + final done = q.connect(_host('A')); + await Future.delayed(Duration.zero); + final s = q.sshSessions.single; + expect(s.status, SessionStatus.connecting); + + q.pauseAll(); + failing.connectGate.completeError(Exception('network down')); + await done; + + expect(s.status, SessionStatus.disconnected); + expect(s.paused, isTrue); + expect(s.reconnectCount, 0); + expect(s.errorMessage, isNull); + expect(dropped, isEmpty); + }); + + test('an attempt that succeeds after a pause stays paused and closes its client', + () async { + final gated = _GatedSsh(); + final q = SessionProvider(gated, TabMetadataService()); + addTearDown(q.dispose); + final done = q.connect(_host('A')); + await Future.delayed(Duration.zero); + final s = q.sshSessions.single; + + q.pauseAll(); + final client = _FakeClient(); + gated.connectGate.complete(client); + await done; + + expect(client.closeCalled, isTrue); + expect(s.status, SessionStatus.disconnected); + expect(s.paused, isTrue); + expect(gated.shellsOpened, 0); + }); + + test('resumePaused reconnects in tab order, stagger apart, even with auto-reconnect off', + () { + fakeAsync((fa) { + p.autoReconnectEnabled = () => false; + for (final id in ['a', 'b', 'c']) { + p.addSessionForTest(_session(id, SessionStatus.connected)); + } + p.pauseAll(); + p.resumePaused(stagger: const Duration(milliseconds: 300)); + fa.flushMicrotasks(); + expect(ssh.connects, ['a']); + fa.elapse(const Duration(milliseconds: 299)); + expect(ssh.connects, ['a']); + fa.elapse(const Duration(milliseconds: 1)); + expect(ssh.connects, ['a', 'b']); + fa.elapse(const Duration(milliseconds: 300)); + expect(ssh.connects, ['a', 'b', 'c']); + expect(p.sshSessions.every((s) => !s.paused), isTrue); + expect(p.sshSessions.every((s) => s.status == SessionStatus.connecting), + isTrue); + }); + }); + + test('paused session rejects input and nothing is buffered', () async { + // Real SshService + a scripted shell, so sendInput really has a shell. + final real = SshService(StorageService()); + final rp = SessionProvider(real, TabMetadataService()); + addTearDown(rp.dispose); + final host = _host('A'); + final s = SshSession(host: host, status: SessionStatus.connected); + rp.addSessionForTest(s); + final shell1 = _ScriptedShell(); + real.debugSetClient(host.id, _ScriptedClient(shell1)); + unawaited(real.openShell(s)); + await Future.delayed(Duration.zero); + expect(s.acceptsInput, isTrue); + expect(real.sendInput(s.id, 'ls\n'), isTrue); + expect(shell1.written, ['ls\n']); + + rp.pauseAll(); + expect(s.acceptsInput, isFalse); + expect(real.sendInput(s.id, 'rm -rf x\n'), isFalse); + + // The resumed attempt gets a fresh shell: nothing typed while paused may + // be replayed into it. + final shell2 = _ScriptedShell(); + real.debugSetClient(host.id, _ScriptedClient(shell2)); + s + ..paused = false + ..status = SessionStatus.connected; + unawaited(real.openShell(s)); + await Future.delayed(Duration.zero); + expect(shell2.written, isEmpty); + expect(real.sendInput(s.id, 'pwd\n'), isTrue); + expect(shell2.written, ['pwd\n']); + expect(shell1.written, ['ls\n']); + }); + + test('verifyLive probes only connected hosts and reconnects the dead ones', + () async { + ssh.connectCompletes = false; + final alive = _session('A', SessionStatus.connected); + final dead = _session('B', SessionStatus.connected); + final other = _session('C', SessionStatus.connecting); + for (final s in [alive, dead, other]) { + p.addSessionForTest(s); + } + ssh.debugSetClient('A', _FakeClient()); + // B has no client -> not alive. + await p.verifyLive(timeout: const Duration(milliseconds: 50)); + expect(ssh.disconnects, ['B']); + expect(ssh.connects, ['B']); + expect(alive.status, SessionStatus.connected); + expect(other.status, SessionStatus.connecting); + expect(dead.status, SessionStatus.connecting); + expect(dead.paused, isFalse); + }); + + test('verifyLive probes hosts concurrently: N slow hosts cost ~one timeout', + () { + fakeAsync((fa) { + ssh.connectCompletes = false; + for (final id in ['A', 'B', 'C', 'D']) { + p.addSessionForTest(_session(id, SessionStatus.connected)); + ssh.debugSetClient( + id, _FakeClient(pingFuture: Completer().future)); + } + var done = false; + unawaited(p + .verifyLive(timeout: const Duration(seconds: 3)) + .then((_) => done = true)); + fa.elapse(const Duration(seconds: 3, milliseconds: 100)); + fa.flushMicrotasks(); + expect(done, isTrue, reason: '4 hosts x 3 s sequentially would be 12 s'); + expect(ssh.disconnects.toSet(), {'A', 'B', 'C', 'D'}); + }); + }); + + group('SshService.isAlive', () { + test('false without a client, when closed, or when ping hangs', () async { + final s = _Ssh(); + expect(await s.isAlive('x'), isFalse); + s.debugSetClient('x', _FakeClient(closed: true)); + expect(await s.isAlive('x'), isFalse); + s.debugSetClient('y', _FakeClient(pingFuture: Completer().future)); + expect(await s.isAlive('y', timeout: const Duration(milliseconds: 20)), + isFalse); + s.debugSetClient('z', _FakeClient()); + expect(await s.isAlive('z'), isTrue); + }); + }); +} diff --git a/app/test/providers/session_provider_template_test.dart b/app/test/providers/session_provider_template_test.dart index cc3cf458..2a53a710 100644 --- a/app/test/providers/session_provider_template_test.dart +++ b/app/test/providers/session_provider_template_test.dart @@ -31,6 +31,7 @@ class _CapturingSsh extends SshService { Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + bool Function()? isCurrent, }) async => _NullClient(); diff --git a/app/test/providers/settings_provider_tmux_test.dart b/app/test/providers/settings_provider_tmux_test.dart new file mode 100644 index 00000000..1e11d4a9 --- /dev/null +++ b/app/test/providers/settings_provider_tmux_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/providers/settings_provider.dart'; + +void main() { + tearDown(() => debugDefaultTargetPlatformOverride = null); + + test('fresh mobile install: tmux on, decided once', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + SharedPreferences.setMockInitialValues({}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isTrue); + expect((await SharedPreferences.getInstance()).getBool('tmuxEnabled'), + isTrue); + }); + + test('existing mobile install without a choice keeps tmux off', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + SharedPreferences.setMockInitialValues({'yourssh.hosts': '[]'}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isFalse); + expect((await SharedPreferences.getInstance()).getBool('tmuxEnabled'), + isFalse); + }); + + test('a stored choice wins', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + SharedPreferences.setMockInitialValues({'tmuxEnabled': false}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isFalse); + }); + + test('desktop without a choice stays off and is not persisted', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + SharedPreferences.setMockInitialValues({}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isFalse); + }); +} diff --git a/app/test/services/cli/app_cli_handlers_test.dart b/app/test/services/cli/app_cli_handlers_test.dart index 38a5ffbc..510cd427 100644 --- a/app/test/services/cli/app_cli_handlers_test.dart +++ b/app/test/services/cli/app_cli_handlers_test.dart @@ -39,6 +39,7 @@ class _GatedSsh extends SshService { Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + bool Function()? isCurrent, }) async { await gate.future; return _NullClient(); diff --git a/app/test/services/cli/link_refused_test.dart b/app/test/services/cli/link_refused_test.dart index 129537d0..8870e907 100644 --- a/app/test/services/cli/link_refused_test.dart +++ b/app/test/services/cli/link_refused_test.dart @@ -19,6 +19,12 @@ void main() { expect(n.title, endsWith('…')); }); + test('a very long reason is capped too', () { + final n = linkRefusedNotification('yourssh://connect/x', 'unknown host: ${'a' * 5000}'); + expect(n.body!.length, lessThanOrEqualTo(201)); + expect(n.body, endsWith('…')); + }); + test('the same link refused twice is one entry (deduped)', () { final center = NotificationCenterProvider(); addTearDown(center.dispose); diff --git a/app/test/services/key_gen_service_test.dart b/app/test/services/key_gen_service_test.dart index 237f298e..1a25157c 100644 --- a/app/test/services/key_gen_service_test.dart +++ b/app/test/services/key_gen_service_test.dart @@ -1,5 +1,7 @@ import 'dart:io'; +import 'package:flutter/foundation.dart'; + import 'package:dartssh2/dartssh2.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:yourssh/services/key_gen_service.dart'; @@ -14,6 +16,24 @@ void main() { tearDown(() => tmp.delete(recursive: true)); + group('platform gating', () { + tearDown(() => debugDefaultTargetPlatformOverride = null); + + test('iOS: ed25519 only and ssh-keygen is never probed', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + final s = KeyGenService(); + expect(await s.probeSshKeygen(), isFalse); + expect(await s.supportedAlgorithms(), ['ed25519']); + }); + + test('with ssh-keygen present all algorithms are offered', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + final s = KeyGenService(); + if (!await s.probeSshKeygen()) return; // CI image without ssh-keygen + expect(await s.supportedAlgorithms(), ['ed25519', 'rsa', 'ecdsa']); + }); + }); + group('sanitizeKeyName', () { test('keeps safe chars, replaces the rest', () { expect(KeyGenService.sanitizeKeyName('id_ed25519'), 'id_ed25519'); diff --git a/app/test/services/p2p_sync_service_test.dart b/app/test/services/p2p_sync_service_test.dart index b78ecb6b..09920a00 100644 --- a/app/test/services/p2p_sync_service_test.dart +++ b/app/test/services/p2p_sync_service_test.dart @@ -35,6 +35,21 @@ void main() { ); }); + test('stopAll closes the open server and notifies the service', () async { + var interrupted = 0; + service.onInterrupted = () => interrupted++; + final url = await service.startServer( + encryptedPayload: 'data', + hostAddress: '127.0.0.1', + ); + await P2PSyncService.stopAll(); + expect(interrupted, 1); + expect(() => service.fetchPayload(url), throwsA(anything)); + // Already closed: a second stopAll is a no-op. + await P2PSyncService.stopAll(); + expect(interrupted, 1); + }); + test('getLocalInterfaces returns non-loopback addresses', () async { final ifaces = await service.getLocalInterfaces(); for (final i in ifaces) { diff --git a/app/test/services/ssh_service_jump_auto_connect_test.dart b/app/test/services/ssh_service_jump_auto_connect_test.dart index 2c99778c..093a3b29 100644 --- a/app/test/services/ssh_service_jump_auto_connect_test.dart +++ b/app/test/services/ssh_service_jump_auto_connect_test.dart @@ -24,6 +24,7 @@ class _RecordingSshService extends SshService { Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, Future Function(Host hop, String keyType, Uint8List fp)? verifyHopHostKey, + bool Function()? isCurrent, }) async { capturedChain = jumpChain; throw _Sentinel(); diff --git a/app/test/services/ssh_service_open_shell_test.dart b/app/test/services/ssh_service_open_shell_test.dart index 9d2ced03..1163e257 100644 --- a/app/test/services/ssh_service_open_shell_test.dart +++ b/app/test/services/ssh_service_open_shell_test.dart @@ -81,7 +81,9 @@ class _FakeShell implements SSHSession { } @override - Future close() async { + Future close() => closeStreams(); + + Future closeStreams() async { await _stdout.close(); await _stderr.close(); } @@ -551,4 +553,36 @@ void main() { await shell.close(); await shellDone; }); + + test( + 'a late close of an older shell does not tear down the session\'s new shell', + () async { + // Pause/resume reuses the tab: the old shell's done event can arrive after + // the resumed shell was registered, and must not null its input hooks. + final svc = SshService(StorageService()); + final host = Host(label: 'f', host: 'example.com', port: 22, username: 'u'); + final session = SshSession(host: host); + final shell1 = _FakeShell(); + final shell2 = _FakeShell(); + svc.debugSetClient(host.id, _FakeClient(shell1)); + final first = svc.openShell(session); + await Future.delayed(Duration.zero); + + svc.debugSetClient(host.id, _FakeClient(shell2)); + final second = svc.openShell(session); + await Future.delayed(Duration.zero); + expect(svc.sendInput(session.id, 'x'), isTrue); + expect(shell2.writtenText, 'x'); + + await shell1.closeStreams(); + await first; + + expect(session.terminal.onOutput, isNotNull); + expect(svc.sendInput(session.id, 'y'), isTrue); + expect(shell2.writtenText, 'xy'); + + await shell2.closeStreams(); + await second; + expect(svc.sendInput(session.id, 'z'), isFalse); + }); } diff --git a/app/test/services/ssh_service_stale_connect_test.dart b/app/test/services/ssh_service_stale_connect_test.dart new file mode 100644 index 00000000..6dfbad43 --- /dev/null +++ b/app/test/services/ssh_service_stale_connect_test.dart @@ -0,0 +1,145 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh/models/host.dart'; +import 'package:yourssh/models/ssh_key.dart'; +import 'package:yourssh/services/ssh_service.dart'; +import 'package:yourssh/services/storage_service.dart'; +import 'package:yourssh/services/system_agent_proxy.dart'; + +class _Channel implements SSHForwardChannel { + @override + dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i); +} + +class _Socket implements SSHSocket { + @override + dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i); +} + +class _Client implements SSHClient { + _Client(); + final auth = Completer(); + bool closed = false; + + @override + bool get isClosed => closed; + @override + Future get authenticated => auth.future; + @override + void close() => closed = true; + @override + Future forwardLocal(String host, int port, + {String? localHost, int? localPort}) async => + _Channel(); + @override + dynamic noSuchMethod(Invocation i) => super.noSuchMethod(i); +} + +/// Hands out a scripted client per `connect` and a shared bastion client. +class _Svc extends SshService { + _Svc() : super(StorageService()); + final built = <_Client>[]; + final hops = {}; + + @override + Future localDial(Host host, {Duration? timeout}) async => _Socket(); + + @override + SSHClient buildConnectClient(SSHSocket socket, + {required Host host, + required String? password, + required List? identities, + required Future Function(String keyType, Uint8List fingerprint)? + verifyHostKey}) { + final c = _Client(); + built.add(c); + return c; + } + + @override + Future<({SSHClient client, SystemAgentProxy? proxy})> dialHop( + Host hop, + SSHSocket? over, { + SshKeyEntry? keyEntry, + Future Function(String keyType, Uint8List fingerprint)? verifyHostKey, + }) async { + final c = hops.putIfAbsent(hop.id, () => _Client()..auth.complete()); + return (client: c, proxy: null); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const secureChannel = + MethodChannel('plugins.it_nomads.com/flutter_secure_storage'); + setUp(() { + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureChannel, (_) async => null); + }); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureChannel, null); + }); + + final host = Host(id: 'H', label: 'H', host: 'h.com', username: 'u'); + final bastion = Host(id: 'B', label: 'B', host: 'b.com', username: 'u'); + + test('a stale attempt that finishes after the resumed one keeps the live client', + () async { + final svc = _Svc(); + var staleCurrent = true; + final stale = svc.connect(host, isCurrent: () => staleCurrent); + await Future.delayed(Duration.zero); + final live = svc.connect(host); + await Future.delayed(Duration.zero); + expect(svc.built, hasLength(2)); + svc.built[1].auth.complete(); + final liveClient = await live; + + staleCurrent = false; + svc.built[0].auth.complete(); + await stale; + + expect(svc.built[0].closed, isTrue); + expect(liveClient.isClosed, isFalse); + expect(await svc.ensureClient(host), same(liveClient)); + }); + + test('a stale attempt that fails leaves the resumed attempt\'s bastion open', + () async { + final svc = _Svc(); + final chain = [(host: bastion, keyEntry: null as SshKeyEntry?)]; + var staleCurrent = true; + final stale = svc.connect(host, jumpChain: chain, isCurrent: () => staleCurrent); + await Future.delayed(Duration.zero); + final live = svc.connect(host, jumpChain: chain); + await Future.delayed(Duration.zero); + expect(svc.built, hasLength(2)); + + staleCurrent = false; + svc.built[0].auth.completeError(Exception('network down')); + await expectLater(stale, throwsException); + + expect(svc.hops['B']!.closed, isFalse); + svc.built[1].auth.complete(); + await live; + expect(svc.hops['B']!.closed, isFalse); + }); + + test('without isCurrent a failed attempt still unwinds its jump chain', + () async { + final svc = _Svc(); + final chain = [(host: bastion, keyEntry: null as SshKeyEntry?)]; + final f = svc.connect(host, jumpChain: chain); + await Future.delayed(Duration.zero); + svc.built[0].auth.completeError(Exception('boom')); + await expectLater(f, throwsException); + expect(svc.hops['B']!.closed, isTrue); + }); +} diff --git a/app/test/services/storage_service_test.dart b/app/test/services/storage_service_test.dart index abf6c830..03b4c88b 100644 --- a/app/test/services/storage_service_test.dart +++ b/app/test/services/storage_service_test.dart @@ -61,6 +61,43 @@ void main() { .setMockMethodCallHandler(channel, null); }); + group('StorageService iOS Keychain', () { + test('iOS keychain is this-device-only and not synced', () { + expect(StorageService.iosKeychainOptions.params['accessibility'], + 'first_unlock_this_device'); + expect( + StorageService.iosKeychainOptions.params['synchronizable'], 'false'); + }); + + test( + 'without plaintext fallback a failed secure write throws and prefs stay clean', + () async { + secureFailsAllWrites = true; + final s = StorageService(allowPlaintextFallback: false); + await expectLater(s.savePassword('h1', 'pw'), + throwsA(isA())); + expect((await SharedPreferences.getInstance()).containsKey('pw_h1'), + isFalse); + expect(s.hasPlaintextSecrets, isFalse); + }); + + test('without plaintext fallback reads ignore a prefs copy', () async { + SharedPreferences.setMockInitialValues({'pw_h1': 'stale'}); + expect(await StorageService(allowPlaintextFallback: false) + .loadPassword('h1'), isNull); + expect(await StorageService().loadPassword('h1'), 'stale'); + }); + + test('the default still falls back to prefs (desktop/Android unchanged)', + () async { + secureFailsAllWrites = true; + final s = StorageService(); + await s.savePassword('h1', 'pw'); + expect((await SharedPreferences.getInstance()).getString('pw_h1'), 'pw'); + expect(s.hasPlaintextSecrets, isTrue); + }); + }); + group('StorageService passwords', () { test('savePassword writes to secure storage', () async { final svc = StorageService(); diff --git a/app/test/tooling/check_ios_bundle_test.dart b/app/test/tooling/check_ios_bundle_test.dart new file mode 100644 index 00000000..83031525 --- /dev/null +++ b/app/test/tooling/check_ios_bundle_test.dart @@ -0,0 +1,53 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +Future check(String dir) => + Process.run('bash', ['../tool/check_ios_bundle.sh', dir]); + +void main() { + late Directory d; + setUp(() => d = Directory.systemTemp.createTempSync('ios_bundle_')); + tearDown(() => d.deleteSync(recursive: true)); + + test('rejects a bundle containing the QuickJS bridge', () async { + File('${d.path}/Frameworks/libqjsbridge.dylib').createSync(recursive: true); + final r = await check(d.path); + expect(r.exitCode, 1); + expect(r.stderr, contains('forbidden files or directories')); + expect(r.stderr, contains('libqjsbridge.dylib')); + }); + + test('rejects a binary carrying the PTY fork symbol', () async { + File('${d.path}/Frameworks/X.framework/X') + ..createSync(recursive: true) + ..writeAsBytesSync([0, ...'_pty_forkpty'.codeUnits, 0]); + final r = await check(d.path); + expect(r.exitCode, 1); + expect(r.stderr, contains('pty_forkpty')); + expect(r.stderr, contains('X.framework/X')); + }); + + test('rejects an Info.plist with any ATS dictionary', () async { + for (final body in [ + 'NSAppTransportSecurityNSAllowsArbitraryLoads', + 'NSAppTransportSecurityNSExceptionDomains', + ]) { + File('${d.path}/Info.plist').writeAsStringSync('$body'); + final r = await check(d.path); + expect(r.exitCode, 1, reason: body); + expect(r.stderr, contains('NSAppTransportSecurity'), reason: body); + } + }); + + test('matches forbidden names case-insensitively', () async { + File('${d.path}/Frameworks/LibQuickJS.dylib').createSync(recursive: true); + expect((await check(d.path)).exitCode, 1); + }); + + test('accepts a clean bundle', () async { + File('${d.path}/Runner').createSync(); + File('${d.path}/Info.plist').writeAsStringSync(''); + expect((await check(d.path)).exitCode, 0); + }); +} diff --git a/app/test/tooling/ios_ci_needed_test.dart b/app/test/tooling/ios_ci_needed_test.dart new file mode 100644 index 00000000..51e90b1b --- /dev/null +++ b/app/test/tooling/ios_ci_needed_test.dart @@ -0,0 +1,53 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +Future needed(List files) async { + final p = await Process.start('bash', ['../tool/ios_ci_needed.sh']); + p.stdin.write(files.map((f) => '$f\n').join()); + await p.stdin.close(); + final out = await p.stdout.transform(const SystemEncoding().decoder).join(); + expect(await p.exitCode, 0); + return out.trim(); +} + +void main() { + test('docs-only changes skip the iOS job', () async { + expect( + await needed([ + 'README.md', + 'CHANGELOG.md', + 'docs/superpowers/specs/x-design.md', + 'screenshots/docs/01.png', + '.claude/skills/yourssh-docs-sync/SKILL.md', + ]), + 'false', + ); + }); + + test('any app, package, tool or workflow change runs the iOS job', () async { + for (final f in [ + 'app/lib/main.dart', + 'app/ios/Runner/Info.plist', + 'packages/dartssh2/lib/src/ssh_client.dart', + 'tool/check_ios_bundle.sh', + '.github/workflows/pr-test.yml', + 'app/pubspec.yaml', + ]) { + expect(await needed(['README.md', f]), 'true', reason: f); + } + }); + + test('an empty or unknown change list runs the iOS job', () async { + expect(await needed([]), 'true'); + }); + + test('pr-test.yml gates the ios job on the changes job and accepts a skip', + () { + final y = File('../.github/workflows/pr-test.yml').readAsStringSync(); + expect(y, contains('tool/ios_ci_needed.sh')); + expect(y, contains("if: needs.changes.outputs.ios == 'true'")); + expect(y, contains('needs: [app, ui, bridge, android, cli, windows-cli, ios, changes]')); + expect(y, contains('needs.ios.result }}" = "skipped"')); + }); +} diff --git a/app/test/tooling/release_ios_job_test.dart b/app/test/tooling/release_ios_job_test.dart new file mode 100644 index 00000000..57502248 --- /dev/null +++ b/app/test/tooling/release_ios_job_test.dart @@ -0,0 +1,49 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +String job(String y, String name) { + final start = y.indexOf('\n $name:'); + final next = + RegExp(r'\n [a-z][a-z0-9-]*:\n').firstMatch(y.substring(start + 1)); + return next == null ? y.substring(start) : y.substring(start, start + 1 + next.start); +} + +void main() { + test('release.yml has a gated build-ios job that stays off the GitHub release', + () { + final y = File('../.github/workflows/release.yml').readAsStringSync(); + final ios = job(y, 'build-ios'); + expect(ios, contains('needs: test')); + expect(ios, contains('IOS_SIGNING:')); + expect(ios, contains("if: env.IOS_SIGNING == 'true'")); + expect(ios, contains('check_ios_bundle.sh')); + expect(ios, contains('ASC_KEY_ID')); + expect(ios, contains('if: always()')); + expect(ios, contains('github.run_attempt')); + expect(ios, isNot(contains('--build-number=\${{ github.run_number }}'))); + expect(ios, contains('--build-number="\$BUILD_NUMBER"')); + expect(job(y, 'release'), isNot(contains('build-ios'))); + expect(ios, contains('::add-mask::\$KEYCHAIN_PASSWORD')); + expect(ios.indexOf('SIGN_KEYCHAIN='), + lessThan(ios.indexOf('security import'))); + expect(ios.indexOf('Name the IPA'), lessThan(ios.indexOf('altool'))); + expect(ios, contains("if: always() && env.IOS_SIGNING == 'true'")); + final opts = File('ios/ExportOptions.plist').readAsStringSync(); + expect(opts, allOf(contains('84T567KMYD'), contains('app-store-connect'))); + }); + + test('profile name is consistent across workflow, export options, project', + () { + const name = 'YourSSH App Store'; + final y = File('../.github/workflows/release.yml').readAsStringSync(); + final opts = File('ios/ExportOptions.plist').readAsStringSync(); + final pbx = + File('ios/Runner.xcodeproj/project.pbxproj').readAsStringSync(); + expect(job(y, 'build-ios'), contains(name)); + expect(opts, contains('$name')); + expect(opts, contains('com.thangnm.yourssh')); + expect(pbx, contains('PROVISIONING_PROFILE_SPECIFIER = "$name";')); + expect(pbx, contains('CODE_SIGN_STYLE = Manual;')); + }); +} diff --git a/app/test/util/native_chmod_test.dart b/app/test/util/native_chmod_test.dart new file mode 100644 index 00000000..5fade42d --- /dev/null +++ b/app/test/util/native_chmod_test.dart @@ -0,0 +1,25 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:yourssh/util/native_chmod.dart'; + +void main() { + late Directory tmp; + setUp(() => tmp = Directory.systemTemp.createTempSync('native_chmod')); + tearDown(() => tmp.deleteSync(recursive: true)); + + test('chmodNative sets owner-only modes', () async { + final f = File('${tmp.path}/k')..writeAsStringSync('x'); + await chmodNative(f.path, 0x180); + expect(f.statSync().mode & 0x1ff, 0x180); + }, skip: Platform.isWindows); + + test('chmodNative throws FileSystemException with errno on failure', + () async { + await expectLater( + chmodNative('${tmp.path}/missing', 0x180), + throwsA(isA() + .having((e) => e.osError?.errorCode, 'errno', 2)), + ); + }, skip: Platform.isWindows); +} diff --git a/app/test/widgets/settings/settings_sections_test.dart b/app/test/widgets/settings/settings_sections_test.dart index fe9ef387..406015f2 100644 --- a/app/test/widgets/settings/settings_sections_test.dart +++ b/app/test/widgets/settings/settings_sections_test.dart @@ -3,6 +3,7 @@ import 'dart:io' show Platform; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh/models/ai_provider_config.dart'; import 'package:yourssh/models/app_release.dart'; import 'package:yourssh/models/audit_event.dart'; @@ -42,6 +43,9 @@ void main() { group('Connection', () { testWidgets('controls present; switch and selects persist', (tester) async { + // flutter_test reports Android, where tmux defaults on for fresh + // installs; this desktop section starts from an explicit "off". + SharedPreferences.setMockInitialValues({'tmuxEnabled': false}); final h = SettingsHarness(); await h.pump(tester, const ConnectionSettingsSection()); diff --git a/app/windows/flutter/generated_plugin_registrant.cc b/app/windows/flutter/generated_plugin_registrant.cc index d44f501a..e453409a 100644 --- a/app/windows/flutter/generated_plugin_registrant.cc +++ b/app/windows/flutter/generated_plugin_registrant.cc @@ -15,6 +15,7 @@ #include #include #include +#include #include void RegisterPlugins(flutter::PluginRegistry* registry) { @@ -36,6 +37,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { registry->GetRegistrarForPlugin("Sqlite3FlutterLibsPlugin")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); + SharePlusWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); WindowManagerPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("WindowManagerPlugin")); } diff --git a/app/windows/flutter/generated_plugins.cmake b/app/windows/flutter/generated_plugins.cmake index 87320052..5991e66c 100644 --- a/app/windows/flutter/generated_plugins.cmake +++ b/app/windows/flutter/generated_plugins.cmake @@ -12,6 +12,7 @@ list(APPEND FLUTTER_PLUGIN_LIST screen_retriever sqlite3_flutter_libs url_launcher_windows + share_plus window_manager ) diff --git a/docs/superpowers/plans/2026-11-12-yourssh-ios-phase1.md b/docs/superpowers/plans/2026-11-12-yourssh-ios-phase1.md new file mode 100644 index 00000000..240e0327 --- /dev/null +++ b/docs/superpowers/plans/2026-11-12-yourssh-ios-phase1.md @@ -0,0 +1,898 @@ +# YourSSH iOS Phase 1 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship the existing YourSSH mobile UI on iPhone (iOS 16+) as a signed TestFlight build, with Keychain/Face ID, background grace + pause + reconnect, Files integration, store-compliance metadata, `yourssh://` (and opt-in `ssh://`) links and CI. + +**Architecture:** Add `app/ios` (Flutter 3.50 runner, UIScene lifecycle) and reuse `app/lib/mobile` (forui, touch theme). Platform capability flags in `runtime_platform.dart` gate desktop-only code; the `flutter_pty` fork drops its iOS platform; no QuickJS/RDP/VNC native libs are bundled; `main()` already returns for mobile before the CLI lock, sandbox migration and window setup. One native class (`YourSshNative.swift`) owns the method channels. A `MobileLifecycleCoordinator` gives backgrounded sessions a grace window, then pauses them and reconnects on foreground; tmux defaults ON for fresh mobile installs. Links reuse the desktop `CliServer` + `UrlChannel`. + +**Tech Stack:** Flutter 3.50.0 (CI pin), Dart, forui 0.27 via `yourssh_ui`, Swift (UIScene: `FlutterImplicitEngineDelegate`, `FlutterSceneLifeCycleDelegate`), Swift Package Manager + CocoaPods, `flutter_secure_storage` 9.2, `local_auth` 2.3, `file_picker` 8.3, `mobile_scanner` (Apple Vision line), `share_plus` (new), GitHub Actions (macOS runner), App Store Connect API key. + +**Spec:** `docs/superpowers/specs/2026-11-12-yourssh-ios-design.md` (refreshed 2026-11-13 against `develop` @ `8c6f0cd1`). + +## Global Constraints + +- Bundle id `com.thangnm.yourssh`; display name `YourSSH`; minimum iOS 16; iPhone only (`TARGETED_DEVICE_FAMILY = 1`); Apple team `84T567KMYD` (SENPRINTS LLC). +- Flutter is pinned to `3.50.0` (`FLUTTER_VERSION` in `pr-test.yml` and `release.yml`, kept equal). This plan does not bump Flutter or the Android toolchain. +- The iOS runner is the Flutter 3.50 UIScene template (`AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate`, `SceneDelegate: FlutterSceneDelegate`). Native code registers in `didInitializeImplicitFlutterEngine` through `YourSshNative` and gets URLs from scene events; never `application(_:open:options:)`. +- Keychain: `IOSOptions(accessibility: first_unlock_this_device, synchronizable: false)`; no plaintext `SharedPreferences` fallback on iOS. The macOS legacy-Keychain options (`macOsKeychainOptions`) stay as they are. Secrets never in Documents, backups (`UserDefaults` included), logs or URLs. +- No JS plugin loader, QuickJS lib, RDP/VNC lib or `flutter_pty` binary in the iOS bundle; no subprocess (`Process.run`) on iOS. +- Desktop-only infrastructure never runs on iOS: the CLI socket/pipe listener and single-instance lock (`main()` returns for mobile first), `UpdateService`/`UpdateProvider`, the macOS sandbox migration, `migratePlaintextSecrets`, audit, recordings. +- Platform checks use the flags in `app/lib/platform/runtime_platform.dart` (`defaultTargetPlatform`), not raw `Platform.isIOS`, except in native-channel code. +- Input to a non-connected session is rejected visibly, never buffered or replayed. +- `yourssh://` links go through the existing `CliServer` + `UrlChannel` (`app/lib/services/cli/`): no second parser or resolver. `ssh://` is opt-in and never connects to an unknown target. +- UI: forui widgets / `Ys*` components, `YsColors` tokens (not the deprecated `MobileColors`), `FLucideIcons`, touch `FItem`s ≥ 44 px; toasts via `AppSnack`/`showYsToast`, dialogs via `showYsDialog`/`showYsConfirm`, sheets via `showFSheet`. `bash tool/check_ui_lint.sh` must pass (no `IconButton(`, `AlertDialog(`, `SnackBar(`, `Icons.`, `ScaffoldMessenger`, `showDialog(`, `showModalBottomSheet`, `TextField(`, no `Color(0x…)` in widgets). +- Widget tests: `ysTestApp(child, touch: true)` (`app/test/helpers/ys_test_app.dart`) or a `MaterialApp` with `builder: ysRootBuilderTouch`; iOS behavior via `variant: TargetPlatformVariant.only(TargetPlatform.iOS)` (plain `test()`s may set `debugDefaultTargetPlatformOverride` with a `tearDown` reset). The secure-storage channel is mocked as in `app/test/providers/session_provider_test.dart`. +- `ITSAppUsesNonExemptEncryption = true`; the app is free (no IAP); no tracking; privacy manifest present; no `NSAppTransportSecurity` exceptions. +- Conventional Commits; no `Co-Authored-By` / `Claude-Session` trailers. Signing/upload steps in `release.yml` are gated on secrets like the macOS ones. +- Commands: tests `cd app && flutter test`; analyze `cd app && flutter analyze --no-fatal-infos`; UI lint `bash tool/check_ui_lint.sh`; iOS builds `cd app && flutter build ios --simulator --no-codesign` and `flutter build ios --release --no-codesign`. +- Verification labels: **Local** runs on the owner's Mac (Xcode 27.2, iOS 27.2 SDK, CocoaPods 1.17, **no simulator runtime**: builds and `flutter test` work, launching does not). **CI-only** runs in the pr-test `ios` job (Task 12) on a macOS runner with simulators. **Manual** needs a booted simulator or a device and is not runnable on the owner's Mac today. + +## Review Focus + +1. App backgrounded mid-typing or mid-SFTP-transfer: inside the grace window nothing changes; after it, sessions show paused, an upload fails with a "failed" toast (never reported as done), a download leaves no partial file, and no keystroke is silently dropped or replayed after reconnect. +2. Foreground with many paused sessions and a server that no longer has tmux or is unreachable: reconnects are staggered, a session that died while still marked connected is caught by the keepalive probe, a missing tmux leaves a plain shell with the shell's own error, failures end in a visible error state, and a pause never fires `onSessionDropped` or burns reconnect attempts. +3. Private keys imported or generated on iOS must not appear in the Files app (`UIFileSharingEnabled` exposes Documents), in backups, or linger in the picker's temp copy; a failed Keychain write must not land in `UserDefaults`. +4. Face ID lock: it covers every pushed route and dialog (not only the home route), the app-switcher snapshot, and never loops on its own sheet's `inactive` → `resumed`; an unenrolled device falls open as on Android; the lock screen lives outside the Navigator, so nothing on it may need an `Overlay`. +5. A hostile `yourssh://connect/...` or `ssh://attacker:22` link (unknown label, ambiguous label, extra query params, userinfo, huge input, control/bidi characters) never connects without confirmation, never runs a command, and an unknown `ssh://` target only ever reaches a prefilled Add Host screen. +6. Nothing desktop-only starts on iOS: no `cli.token`/socket, no update banner or check, no plugin loader. + +--- + +### Task 1: Platform capability flags + +**Files:** +- Modify: `app/lib/platform/runtime_platform.dart` +- Test: `app/test/platform/runtime_platform_test.dart` (existing file; it already resets the override in `tearDown`) + +**Interfaces:** +- Produces: `bool get isIOSPlatform`, `bool get supportsRemoteDesktop` (= `!isMobilePlatform` until phase 3), `bool get supportsSubprocesses` (= `!isIOSPlatform`), `bool get mobileDefaultTmux` (= `isMobilePlatform`), all derived from `defaultTargetPlatform` / `isMobilePlatform`. No other flags: each has a consumer in this plan (Tasks 2, 7, 9). + +- [ ] **Step 1: Write the failing tests** (append to the existing `main()`) + +```dart +test('iOS: no subprocesses or remote desktop; tmux default on', () { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + expect(isIOSPlatform, isTrue); + expect(supportsSubprocesses, isFalse); + expect(supportsRemoteDesktop, isFalse); + expect(mobileDefaultTmux, isTrue); +}); +test('Android: subprocesses yes, remote desktop no, tmux default on', () { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + expect(isIOSPlatform, isFalse); + expect(supportsSubprocesses, isTrue); + expect(supportsRemoteDesktop, isFalse); + expect(mobileDefaultTmux, isTrue); +}); +test('macOS keeps every desktop capability', () { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + expect(isIOSPlatform, isFalse); + expect(supportsSubprocesses && supportsRemoteDesktop, isTrue); + expect(mobileDefaultTmux, isFalse); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `cd app && flutter test test/platform/runtime_platform_test.dart` +Expected: FAIL with "isIOSPlatform isn't defined". (**Local**) + +- [ ] **Step 3: Implement the four getters** next to `isMobilePlatform`, each with a one-line doc comment naming its consumer. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `cd app && flutter test test/platform/runtime_platform_test.dart` +Expected: PASS (**Local**) + +- [ ] **Step 5: Commit** + +```bash +git add app/lib/platform/runtime_platform.dart app/test/platform/runtime_platform_test.dart +git commit -m "feat: add platform capability flags for iOS" +``` + +### Task 2: Keep desktop-only code off the mobile path + +**Files:** +- Modify: `packages/flutter_pty/pubspec.yaml:45-46` (remove `ios:` / `ffiPlugin: true` under `flutter.plugin.platforms`; keep android/linux/macos/windows) +- Create: `app/lib/mobile/navigation/open_session.dart` +- Modify: `app/lib/mobile/screens/mobile_hosts_screen.dart:310-356` (`_openSession` → `openMobileSession`), `app/lib/mobile/screens/mobile_terminal_screen.dart:160-215` (the host picker sheet lists only hosts `canOpenOnMobile` accepts) +- Test: `app/test/mobile/desktop_only_guard_test.dart`, `app/test/mobile/open_session_test.dart` + +**Interfaces:** +- Consumes: `supportsRemoteDesktop` (Task 1). +- Produces: + - `bool canOpenOnMobile(Host host)` — `host.protocol == HostProtocol.ssh || supportsRemoteDesktop` + - `Future openMobileSession(NavigatorState nav, Host host, {String auditSource = 'app', bool resetStack = false})` — refuses a host `canOpenOnMobile` rejects with `AppSnack.info(nav.context, 'RDP and VNC hosts open in the desktop app')`; otherwise the current `_openSession` behavior (reuse the host's live SSH session or `SessionProvider.connectAny(host, auditSource: auditSource)` without awaiting it, then push `MobileTerminalScreen(focusSessionId:, onOpenFiles:, onOpenPortForward:)`); `resetStack` pops to the first route before pushing (used by links, Task 11). `SessionProvider` is read from `nav.context` (the providers sit above `MaterialApp`). +- Guard contract: no file under `app/lib/mobile` imports `/main.dart'`, `main_screen.dart`, `single_instance.dart`, `cli_listener`, `peer_cred.dart`, `app_cli_handlers.dart`, `update_service.dart`, `update_provider.dart`, `local_shell_service.dart`, `pty_runner.dart`, `/recording_`, `/audit_`, `/plugin_`, `yourssh_script_engine`, `window_manager`, `hotkey_manager`, `local_notifier`. (`cli_server.dart`, `url_channel.dart`, `host_resolver.dart`, `cli_handlers.dart`, `link_refused.dart` are allowed.) + +- [ ] **Step 1: Write the failing tests** + +```dart +// desktop_only_guard_test.dart (cwd is app/) +test('flutter_pty fork no longer declares an iOS platform', () { + final y = File('../packages/flutter_pty/pubspec.yaml').readAsStringSync(); + expect(RegExp(r'^\s+ios:', multiLine: true).hasMatch(y), isFalse); +}); +test('app/lib/mobile imports no desktop-only module', () { + const banned = ["/main.dart'", 'main_screen.dart', 'single_instance.dart', + 'cli_listener', 'peer_cred.dart', 'app_cli_handlers.dart', 'update_service.dart', + 'update_provider.dart', 'local_shell_service.dart', 'pty_runner.dart', + '/recording_', '/audit_', '/plugin_', 'yourssh_script_engine', + 'window_manager', 'hotkey_manager', 'local_notifier']; + final offenders = [ + for (final f in Directory('lib/mobile').listSync(recursive: true) + .whereType().where((f) => f.path.endsWith('.dart'))) + for (final l in f.readAsLinesSync().where((l) => l.startsWith('import '))) + if (banned.any(l.contains)) '${f.path}: $l', + ]; + expect(offenders, isEmpty); +}); +test('main() returns for mobile before any desktop start-up', () { + final src = File('lib/main.dart').readAsStringSync(); + final start = src.indexOf('void main('); + final mobile = src.indexOf('runApp(const YourSSHMobileApp())', start); + expect(mobile, greaterThan(start)); + for (final call in ['claimSingleInstance(', '_migrateSandboxContainer(', + 'windowManager.ensureInitialized', 'NotificationService.init']) { + expect(src.indexOf(call, start), greaterThan(mobile), reason: call); + } +}); + +// open_session_test.dart +testWidgets('an RDP host is refused on mobile: notice, no session, no route', + (t) async { + /* MultiProvider(SessionProvider over SshService(StorageService())) above + MaterialApp(builder: ysRootBuilderTouch, home: a button calling + openMobileSession(Navigator.of(ctx), Host(..., protocol: HostProtocol.rdp))) */ + expect(sessions.sessions, isEmpty); + expect(find.text('RDP and VNC hosts open in the desktop app'), findsOneWidget); + expect(find.byType(MobileTerminalScreen), findsNothing); +}, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +testWidgets('an SSH host with a live session reuses it', (t) async { + /* existing session for the host -> MobileTerminalScreen pushed, + no second connectAny (sessions.sessions.length unchanged) */ +}, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/mobile/desktop_only_guard_test.dart test/mobile/open_session_test.dart` +Expected: FAIL on the pubspec assertion and "openMobileSession isn't defined"; the import and `main()` guards already pass (they pin today's state). (**Local**) + +- [ ] **Step 3: Implement.** Remove the fork's `ios:` entry (leave `packages/flutter_pty/ios/` on disk; without the pubspec entry neither CocoaPods nor SPM builds it). Move `_openSession`'s body into `openMobileSession`; `MobileHostsScreen` calls it with `Navigator.of(context)`; the terminal screen's host picker filters with `canOpenOnMobile`. `MobileAddHostScreen._saveAndConnect` (`:196-205`) only creates SSH hosts and needs no change. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/mobile && flutter analyze --no-fatal-infos && bash ../tool/check_ui_lint.sh` +Expected: PASS, no new warnings, lint clean. (**Local**) + +- [ ] **Step 5: Commit** + +```bash +git add packages/flutter_pty/pubspec.yaml app/lib/mobile app/test/mobile +git commit -m "feat: keep flutter_pty and desktop-only features off the mobile path" +``` + +### Task 3: iOS runner scaffold (UIScene) and native entry point + +**Files:** +- Create: `app/ios/**` via `cd app && flutter create --platforms=ios --org com.thangnm --project-name yourssh .` (Flutter 3.50 template: `Runner/AppDelegate.swift` with `FlutterImplicitEngineDelegate`, `Runner/SceneDelegate.swift`, `UIApplicationSceneManifest` in `Info.plist`); the bundle id must be exactly `com.thangnm.yourssh` (tests target: `com.thangnm.yourssh.RunnerTests`) +- Create: `app/ios/Runner/YourSshNative.swift` (`final class YourSshNative: NSObject, FlutterPlugin, FlutterSceneLifeCycleDelegate` with `static func register(with registrar: FlutterPluginRegistrar)` that calls `registrar.addSceneDelegate(instance)`; no channels yet — Tasks 8, 9, 11 add them), added to the Runner target in `project.pbxproj` +- Modify: `app/ios/Runner/AppDelegate.swift` (`didInitializeImplicitFlutterEngine`: after `GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)`, `YourSshNative.register(with: engineBridge.pluginRegistry.registrar(forPlugin: "YourSshNative")!)`), `app/ios/Podfile` (uncomment `platform :ios, '16.0'`), `app/ios/Runner.xcodeproj/project.pbxproj` (`IPHONEOS_DEPLOYMENT_TARGET = 16.0` in every configuration, `DEVELOPMENT_TEAM = 84T567KMYD` on Runner, `TARGETED_DEVICE_FAMILY = 1` everywhere), `app/ios/Runner/Info.plist` (`CFBundleDisplayName` = `YourSSH`; drop `UISupportedInterfaceOrientations~ipad`), `tool/gen_app_icons.py` (emit `app/ios/Runner/Assets.xcassets/AppIcon.appiconset` from `assets/branding/yourssh_icon.svg`: opaque, no alpha, the 1024 marketing icon, idempotent like the other targets), `app/analysis_options.yaml` (`ios/**` under `analyzer.exclude`; `flutter pub get` adds it — commit it), `app/pubspec.yaml` + `app/pubspec.lock` (`mobile_scanner`, see Step 3) +- Test: `app/test/platform/ios_runner_config_test.dart` + +**Interfaces:** +- Produces: a runner that builds with `flutter build ios --simulator --no-codesign` and `flutter build ios --release --no-codesign` (output `build/ios/iphonesimulator/Runner.app` / `build/ios/iphoneos/Runner.app` — the product is `Runner.app`; the home-screen name comes from `CFBundleDisplayName`); the `YourSshNative` registration point. + +- [ ] **Step 1: Write the failing test** (file-content assertions; runs on any OS) + +```dart +test('runner config', () { + final proj = File('ios/Runner.xcodeproj/project.pbxproj').readAsStringSync(); + expect(proj, contains('PRODUCT_BUNDLE_IDENTIFIER = com.thangnm.yourssh;')); + Set all(String key) => RegExp('$key = "?([^";]+)"?;') + .allMatches(proj).map((m) => m[1]!).toSet(); + expect(all('IPHONEOS_DEPLOYMENT_TARGET'), {'16.0'}); + expect(all('TARGETED_DEVICE_FAMILY'), {'1'}); + expect(proj, contains('DEVELOPMENT_TEAM = 84T567KMYD;')); + expect(proj, contains('YourSshNative.swift in Sources')); + expect(File('ios/Podfile').readAsStringSync(), + contains("\nplatform :ios, '16.0'")); + final plist = File('ios/Runner/Info.plist').readAsStringSync(); + expect(plist, matches(RegExp( + r'CFBundleDisplayName\s*YourSSH'))); + expect(plist, contains('UIApplicationSceneManifest')); + expect(File('ios/Runner/AppDelegate.swift').readAsStringSync(), + allOf(contains('didInitializeImplicitFlutterEngine'), + contains('YourSshNative.register'))); + final lock = File('ios/Podfile.lock'); + if (lock.existsSync()) { + expect(lock.readAsStringSync(), isNot(contains('GoogleMLKit'))); + } +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `cd app && flutter test test/platform/ios_runner_config_test.dart` +Expected: FAIL (no `ios/` directory). (**Local**) + +- [ ] **Step 3: Generate and edit the files above.** Extend `gen_app_icons.py` idempotently (never hand-edit PNGs, CLAUDE.md "App icon"); add `app/ios/Pods/`, `app/ios/Flutter/ephemeral/` and `app/ios/.symlinks/` to ignores if `flutter create` did not. `mobile_scanner` is locked at 5.2.3, whose iOS podspec depends on `GoogleMLKit/BarcodeScanning ~> 6.0.0` (large binary, ML Kit's own data-collection disclosures, historically no arm64-simulator slice): bump it in `app/pubspec.yaml` to the newest release whose iOS implementation uses Apple Vision (read its CHANGELOG; no `GoogleMLKit` in `ios/Podfile.lock` afterwards) and adapt `mobile_qr_scan_screen.dart` to any API change; its tests (`app/test/mobile/screens/`) must stay green and the pr-test `android` job (`flutter build apk --debug`) proves Android still builds. + +- [ ] **Step 4: Run the test, then the real builds** + +Run: `cd app && flutter test test/platform/ios_runner_config_test.dart test/mobile && flutter build ios --simulator --no-codesign && flutter build ios --release --no-codesign` +Expected: PASS; both builds succeed and produce `Runner.app`. (**Local** — no simulator runtime is needed to build.) Launching: **Manual** (`flutter run -d `; the app opens on the hosts tab). + +- [ ] **Step 5: Commit** + +```bash +git add app/ios app/analysis_options.yaml app/pubspec.yaml app/pubspec.lock app/lib/mobile tool/gen_app_icons.py app/test/platform/ios_runner_config_test.dart +git commit -m "feat: add iOS runner (bundle id com.thangnm.yourssh, iOS 16, UIScene)" +``` + +### Task 4: Mobile UI boots on iPhone + +**Files:** +- Modify: `app/lib/mobile/**` only where an iOS-platform widget test or the simulator smoke run (Task 12) shows a Material/Android assumption breaking (safe areas, back-swipe on pushed routes, keyboard inset above the accessory bar, iOS text-selection controls); every change follows the UI rules in Global Constraints +- Test: `app/test/mobile/ios_boot_test.dart` + +**Interfaces:** +- Consumes: Tasks 1-3. + +- [ ] **Step 1: Write the test** + +```dart +testWidgets('the mobile shell boots under iOS without desktop services', + (t) async { + SharedPreferences.setMockInitialValues({kAppLockPrefKey: false}); + PackageInfo.setMockInitialValues(appName: 'YourSSH', packageName: + 'com.thangnm.yourssh', version: '0.0.0', buildNumber: '0', + buildSignature: ''); + // secure-storage channel mocked as in session_provider_test.dart + await t.pumpWidget(const YourSSHMobileApp()); + await t.pumpAndSettle(); + expect(find.byType(MobileHomeShell), findsOneWidget); + expect(find.byType(MobileTabBar), findsOneWidget); +}, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +testWidgets('every tab renders under iOS', (t) async { + /* same setup; tap each MobileTab (Hosts, Snippets, Keys, Settings), + pumpAndSettle, expect(t.takeException(), isNull) */ +}, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +``` + +- [ ] **Step 2: Run test (baseline)** + +Run: `cd app && flutter test test/mobile/ios_boot_test.dart` +Expected: PASS, or FAIL only where a widget assumes Android; fix that widget (no platform branches unless the iOS behavior is intended). (**Local**) + +- [ ] **Step 3: Check the screens on an iPhone simulator** — hosts, terminal (accessory bar above the keyboard, pinch zoom, long-press cursor drag), SFTP, snippets, keys, settings, toasts above `MobileTabBar`, notch/home-indicator safe areas, back-swipe. **Manual** (not runnable on the owner's Mac); the CI smoke test (Task 12) covers launch + hosts tab automatically. Record each fix in the commit body. + +- [ ] **Step 4: Run tests + full suite** + +Run: `cd app && flutter test && flutter analyze --no-fatal-infos && bash ../tool/check_ui_lint.sh` +Expected: PASS (**Local**) + +- [ ] **Step 5: Commit** + +```bash +git add app/lib/mobile app/test/mobile/ios_boot_test.dart +git commit -m "fix: make the mobile UI run cleanly on iPhone" +``` + +### Task 5: Keychain options and no plaintext fallback on iOS + +**Files:** +- Modify: `app/lib/services/storage_service.dart:27-30` (`iOptions:` on the `static const _storage`), `:76-90` (`_saveSecret`), constructor; `app/lib/mobile/mobile_bootstrap.dart:44` (`StorageService(allowPlaintextFallback: !isIOSPlatform)`); the mobile screens that save secrets — `mobile_add_host_screen.dart` (`_save`/`_saveAndConnect`, `:190-205`), `mobile_keys_screen.dart` (`:155`, `:312` passphrase saves), `mobile_sync_screen.dart` (sync code save), `mobile_qr_scan_screen.dart` (import) — catch `SecretStoreException` and show `AppSnack.error(context, 'Could not save to the iOS Keychain')` +- Test: `app/test/services/storage_service_test.dart` (existing; it already mocks `plugins.it_nomads.com/flutter_secure_storage`) + +**Interfaces:** +- Produces: + - `static const IOSOptions StorageService.iosKeychainOptions` = `IOSOptions(accessibility: KeychainAccessibility.first_unlock_this_device, synchronizable: false)` (default account name) + - `StorageService({bool allowPlaintextFallback = true})`; when false, a failed secure write throws `SecretStoreException(String key, Object cause)` and writes nothing to `SharedPreferences` (reads keep their prefs fallback) + - `class SecretStoreException implements Exception` +- `AiChatProvider` is desktop-only (not in `MobileBootstrap`): unchanged. + +- [ ] **Step 1: Write the failing tests** + +```dart +test('iOS keychain is this-device-only and not synced', () { + expect(StorageService.iosKeychainOptions.params['accessibility'], + 'first_unlock_this_device'); + expect(StorageService.iosKeychainOptions.params['synchronizable'], 'false'); +}); +test('without plaintext fallback a failed secure write throws and prefs stay clean', + () async { + /* channel handler throws PlatformException(code: '-25300') on 'write' */ + final s = StorageService(allowPlaintextFallback: false); + await expectLater(s.savePassword('h1', 'pw'), + throwsA(isA())); + expect((await SharedPreferences.getInstance()).containsKey('pw_h1'), isFalse); + expect(s.hasPlaintextSecrets, isFalse); +}); +test('the default still falls back to prefs (desktop/Android unchanged)', + () async { + /* same failing channel; StorageService() -> prefs has pw_h1, + hasPlaintextSecrets true */ +}); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/services/storage_service_test.dart` +Expected: FAIL with "iosKeychainOptions isn't defined". (**Local**) + +- [ ] **Step 3: Implement** the options, the constructor flag, the exception and the mobile call-site toasts; leave the plaintext accounting (`_markPlaintext`, `migratePlaintextSecrets`) unchanged for desktop. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/services test/mobile && bash ../tool/check_ui_lint.sh` +Expected: PASS (**Local**). On a device/simulator, a saved password survives an app relaunch (**Manual**). + +- [ ] **Step 5: Commit** + +```bash +git add app/lib/services/storage_service.dart app/lib/mobile app/test/services/storage_service_test.dart +git commit -m "feat: this-device-only Keychain and no plaintext secret fallback on iOS" +``` + +### Task 6: App lock covers every route; Face ID usage string + +**Files:** +- Modify: `app/lib/mobile/mobile_app.dart` (`home: const MobileHomeShell()`, `builder: (c, child) => ysRootBuilderTouch(c, AppLockGate(child: child ?? const SizedBox.shrink()))`), `app/lib/mobile/security/app_lock_gate.dart` (while locked: `Stack` of the child wrapped in `Offstage` + `TickerMode(enabled: false)`, and the lock screen; the child is never unmounted), `app/ios/Runner/Info.plist` (`NSFaceIDUsageDescription` = "Unlock YourSSH with Face ID to protect your servers and keys.") +- Test: `app/test/mobile/app_lock_gate_test.dart` (existing; update "nothing behind it" to "behind it but offstage"), `app/test/mobile/mobile_home_shell_test.dart` / `home_shell_test.dart` if they pump `YourSSHMobileApp` + +**Interfaces:** +- `AppLockGate` keeps its constructor (`child`, `authenticator`, `enabledOverride`) and its lifecycle rules (lock on `inactive`/`hidden`/`paused`, re-auth on `resumed`, `_authInFlight` guard, fall open when `isDeviceSupported()` is false). The lock screen sits outside the Navigator: no tooltips/popovers (no `Overlay` there). + +- [ ] **Step 1: Write the failing tests** + +```dart +testWidgets('a pushed route is covered while locked and survives the unlock', + (t) async { + final nav = GlobalKey(); + var allow = false; + await t.pumpWidget(MaterialApp( + navigatorKey: nav, + theme: ysMaterialTheme(), + builder: (c, child) => ysRootBuilderTouch(c, AppLockGate( + enabledOverride: true, authenticator: () async => allow, + child: child!)), + home: const Text('home'), + )); + await t.pumpAndSettle(); // auth failed: locked + nav.currentState!.push(MaterialPageRoute(builder: (_) => const Text('terminal'))); + await t.pumpAndSettle(); + expect(find.text('YourSSH is locked'), findsOneWidget); + expect(find.text('terminal'), findsNothing); // offstage: not painted + expect(find.text('terminal', skipOffstage: false), findsOneWidget); + allow = true; + await t.tap(find.text('Unlock')); + await t.pumpAndSettle(); + expect(find.text('terminal'), findsOneWidget); +}); +testWidgets('backgrounding re-locks over the current route without a prompt loop', + (t) async { + /* authenticator counts calls and returns true; push 'terminal'; + handleAppLifecycleStateChanged(inactive) + pump -> 'terminal' offstage; + resumed + pumpAndSettle -> 'terminal' visible, calls == 2 */ +}); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/mobile/app_lock_gate_test.dart` +Expected: FAIL: the pushed route is visible above the lock (today the gate is the home route). (**Local**) + +- [ ] **Step 3: Implement** the builder placement and the offstage child; add the Face ID string to `Info.plist`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/mobile && bash ../tool/check_ui_lint.sh` +Expected: PASS (**Local**). App-switcher snapshot shows the lock screen; Face ID prompt does not loop (**Manual**, device with Face ID or simulator with enrolled Face ID). + +- [ ] **Step 5: Commit** + +```bash +git add app/lib/mobile app/ios/Runner/Info.plist app/test/mobile +git commit -m "fix: app lock covers every route; Face ID usage string for iOS" +``` + +### Task 7: Mobile tmux default; Ed25519-only key generation without subprocesses + +**Files:** +- Modify: `app/lib/providers/settings_provider.dart:121` (first-run default), `app/lib/mobile/screens/mobile_settings_screen.dart` (Terminal group: `SettingsRow` "Keep sessions in tmux", `toggle: settings.tmuxEnabled`, `onToggle: (v) => settings.save(tmuxEnabled: v)`, Lucide icon, `YsColors`), `app/lib/services/key_gen_service.dart:23-26` (constructor), `:61-70` (`probeSshKeygen`), `app/lib/mobile/mobile_bootstrap.dart` (`KeyGenService(chmod: supportsSubprocesses ? null : chmodNative)`), `app/lib/mobile/screens/mobile_keys_screen.dart:268-271, :330-336` (options from `supportedAlgorithms()`) +- Create: `app/lib/util/native_chmod.dart` +- Test: `app/test/providers/settings_provider_tmux_test.dart`, `app/test/services/key_gen_service_test.dart` (existing), `app/test/util/native_chmod_test.dart` + +**Interfaces:** +- Consumes: `mobileDefaultTmux`, `supportsSubprocesses` (Task 1). +- Produces: + - `SettingsProvider` load rule: no stored `tmuxEnabled` + `mobileDefaultTmux` + no `yourssh.hosts` key → `tmuxEnabled = true` and persisted; no stored value otherwise → `false` (persisted on mobile so the decision is made once, like `terminalTheme`); a stored value always wins + - `Future> KeyGenService.supportedAlgorithms()` → `['ed25519']` when `probeSshKeygen()` is false, else `['ed25519', 'rsa', 'ecdsa']` + - `KeyGenService.probeSshKeygen()` returns false without spawning a process when `!supportsSubprocesses` + - `Future chmodNative(String path, int mode)` — libc `chmod` through `dart:ffi` (`DynamicLibrary.process()`; `mode_t` is `Uint16` on iOS/macOS, `Uint32` on Linux/Android); throws `FileSystemException` with `errno` on failure; unsupported on Windows + +- [ ] **Step 1: Write the failing tests** + +```dart +// settings_provider_tmux_test.dart — tearDown resets the override +test('fresh mobile install: tmux on, decided once', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + SharedPreferences.setMockInitialValues({}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isTrue); + expect((await SharedPreferences.getInstance()).getBool('tmuxEnabled'), isTrue); +}); +test('existing mobile install without a choice keeps tmux off', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + SharedPreferences.setMockInitialValues({'yourssh.hosts': '[]'}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isFalse); +}); +test('a stored choice wins', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + SharedPreferences.setMockInitialValues({'tmuxEnabled': false}); + final p = SettingsProvider(); + await pumpEventQueue(); + expect(p.tmuxEnabled, isFalse); +}); + +// key_gen_service_test.dart +test('iOS: ed25519 only and ssh-keygen is never probed', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + final s = KeyGenService(); + expect(await s.probeSshKeygen(), isFalse); + expect(await s.supportedAlgorithms(), ['ed25519']); +}); +// The injected-chmod path of generateEd25519 is already covered by the +// existing 'key is restricted before key material is written' test. + +// native_chmod_test.dart (skip on Windows) +test('chmodNative sets owner-only modes', () async { + final f = File('${tmp.path}/k')..writeAsStringSync('x'); + await chmodNative(f.path, 0x180); + expect(f.statSync().mode & 0x1ff, 0x180); +}, skip: Platform.isWindows); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/providers/settings_provider_tmux_test.dart test/services/key_gen_service_test.dart test/util/native_chmod_test.dart` +Expected: FAIL (missing members / file). (**Local**) + +- [ ] **Step 3: Implement.** In `_load`, mirror the `terminalTheme` first-run block for `tmuxEnabled`. The keys screen's `_AlgoOption` list comes from `supportedAlgorithms()`. Never call `Process.run` on iOS from the mobile path. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/providers test/services test/util test/mobile && bash ../tool/check_ui_lint.sh` +Expected: PASS (**Local**; `native_chmod_test` also runs on the macOS runner in Task 12, which exercises the `Uint16` Darwin signature). Generating an Ed25519 key on the simulator works (**Manual**). + +- [ ] **Step 5: Commit** + +```bash +git add app/lib app/test +git commit -m "feat: tmux default for fresh mobile installs; Ed25519-only key generation without subprocesses" +``` + +### Task 8: Background grace, pause, foreground resume + +**Files:** +- Create: `app/lib/mobile/lifecycle/background_tasks.dart`, `app/lib/mobile/lifecycle/mobile_lifecycle_coordinator.dart` +- Modify: `app/ios/Runner/YourSshNative.swift` (channel `yourssh/background`: `begin` → `["id": Int, "remainingMs": Int]` via `UIApplication.shared.beginBackgroundTask(withName:expirationHandler:)` and `backgroundTimeRemaining` (`-1` when not finite); the expiration handler ends the task; `end(id)`), `app/lib/models/ssh_session.dart` (`paused`, `acceptsInput`), `app/lib/providers/session_provider.dart` (`pauseAll`, `resumePaused`, `verifyLive`; early return for a paused session after `openShell` returns (`:569`) and in the `catch` (`:589`); `@visibleForTesting void addSessionForTest(SshSession s)`), `app/lib/services/ssh_service.dart` (`isAlive`), `app/lib/mobile/mobile_app.dart` (iOS only: build the coordinator with `MethodChannelBackgroundTasks`, an `AppLifecycleListener(onPause: c.onBackground, onResume: c.onForeground)`, dispose both), `app/lib/mobile/screens/mobile_terminal_screen.dart` (`_SessionBody` non-connected branch: "Session paused — reconnecting" for `session.paused`; `_openPanel` insert/key callbacks check `acceptsInput` and toast "Session is not connected"), `app/lib/mobile/screens/mobile_snippets_screen.dart:127-133` (`sendInput` false → `AppSnack.info(context, 'Session is not connected')`) +- Test: `app/test/mobile/mobile_lifecycle_coordinator_test.dart`, `app/test/providers/session_provider_pause_test.dart`, `app/test/mobile/mobile_terminal_paused_test.dart` + +**Interfaces:** +- Consumes: `SessionProvider.sshSessions`, `reconnectSession(String id)` (`:645`, reuses the tab, cancels pending timers, honors tmux and retry settings), `SshService.disconnect(hostId)` (`:1456`), `SshService.sendInput` (`:1446`, returns false without a live shell), `PortForwardService.isRunning/start/stopAll`, `PortForwardProvider.forwards`, `SSHClient.ping()` (dartssh2 fork). +- Produces: + - `class BackgroundLease { final int id; final Duration? remaining; }` (`remaining` null = unknown) + - `abstract class BackgroundTasks { Future begin(); Future end(int id); }` and `MethodChannelBackgroundTasks` on `MethodChannel('yourssh/background')` (`begin` returning null when the OS refuses) + - `MobileLifecycleCoordinator({required SessionProvider sessions, required PortForwardService forwards, required PortForwardProvider forwardRules, required BackgroundTasks tasks, Duration stagger = const Duration(milliseconds: 300), Duration maxGrace = const Duration(seconds: 25)})` with `Future onBackground()`, `Future onForeground()`, `void dispose()`; grace = `min(remaining − 5 s, maxGrace)` clamped at zero, zero when there is no lease + - `void SessionProvider.pauseAll()` — every SSH session that is `connected` or `connecting` (reconnect countdown) gets `paused = true`, `status = disconnected`, its reconnect/countdown timers cancelled and a dim `[Paused while YourSSH was in the background]` line; each affected host's client closed once; sessions in `error` or a user-closed `disconnected` state untouched + - `Future SessionProvider.resumePaused({Duration stagger})` — in tab order: `paused = false`, `reconnectSession(id)`, wait `stagger`; ignores the auto-reconnect setting (a pause is not a drop) + - `Future SessionProvider.verifyLive({Duration timeout = const Duration(seconds: 3)})` — per host with a `connected` session: `await _ssh.isAlive(hostId, timeout: timeout)`; false → pause that host's sessions and resume them + - `Future SshService.isAlive(String hostId, {Duration timeout})` — false when there is no client, it is closed, or `ping()` does not complete in time + - `bool SshSession.paused` (default false); `bool get SshSession.acceptsInput` → `status == SessionStatus.connected && !paused` + +- [ ] **Step 1: Write the failing tests** + +```dart +// mobile_lifecycle_coordinator_test.dart — SessionProvider / PortForwardService +// subclasses record calls; FakeBackgroundTasks hands out leases; fake_async. +test('a quick app switch pauses nothing and ends the task', () => fakeAsync((fa) { + c.onBackground(); fa.elapse(const Duration(seconds: 10)); + c.onForeground(); fa.flushMicrotasks(); + expect(sessions.calls, isNot(contains('pauseAll'))); + expect(tasks.ended, [tasks.lastId]); +})); +test('grace expiry stops forwards, then pauses sessions, then ends the task', + () => fakeAsync((fa) { + c.onBackground(); fa.elapse(const Duration(seconds: 25)); fa.flushMicrotasks(); + expect(log, ['forwards.stopAll', 'sessions.pauseAll', 'tasks.end']); +})); +test('grace follows the OS allowance', () => fakeAsync((fa) { + /* lease remaining 12 s -> pauseAll at 7 s, not before */ +})); +test('foreground resumes paused sessions, probes the rest, restarts recorded forwards', + () => fakeAsync((fa) { + /* 2 forwards were running at pause -> after onForeground: + ['sessions.resumePaused', 'sessions.verifyLive', 'forwards.start:a', 'forwards.start:b'] */ +})); + +// session_provider_pause_test.dart — SshService subclass: connect() records the +// host and never completes; disconnect() records the host id. +test('pauseAll pauses connected and reconnecting sessions, closes each host once', + () { /* 2 sessions on host A, 1 on B, 1 in error -> paused 3, disconnect [A, B], + error session untouched, no onSessionDropped */ }); +test('a paused session whose shell closes schedules no reconnect', () async { + /* paused flag set before openShell returns -> no countdown text, + status stays disconnected, onSessionDropped not called */ }); +test('resumePaused reconnects in tab order, stagger apart, even with auto-reconnect off', + () async { /* settings autoReconnectEnabled -> false; connect() calls ordered */ }); +test('paused session rejects input and nothing is buffered', () { + expect(s.acceptsInput, isFalse); + expect(ssh.sendInput(s.id, 'ls\n'), isFalse); +}); + +// mobile_terminal_paused_test.dart +testWidgets('terminal shows the paused state and mounts no TerminalView', (t) async { + expect(find.text('Session paused — reconnecting'), findsOneWidget); + expect(find.byType(TerminalView), findsNothing); +}, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/mobile/mobile_lifecycle_coordinator_test.dart test/providers/session_provider_pause_test.dart test/mobile/mobile_terminal_paused_test.dart` +Expected: FAIL with "MobileLifecycleCoordinator isn't defined". (**Local**) + +- [ ] **Step 3: Implement the signatures above.** `onBackground`: `begin()`, then start the grace timer; when it fires, record `forwardRules.forwards.where((f) => forwards.isRunning(f.id))`, `await forwards.stopAll()` (before any client closes, so its 2–30 s reconnect backoff never starts), `sessions.pauseAll()`, then `end(id)` in a `finally`. `onForeground`: cancel the timer, `end` the lease if still open, `await sessions.resumePaused(stagger: stagger)`, `await sessions.verifyLive()`, then `forwards.start` each recorded rule. Reconnecting does not wait for the lock gate. `inactive` is never acted on (Face ID sheet, Control Center). Android keeps today's behavior (no coordinator). + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/mobile test/providers test/services && flutter analyze --no-fatal-infos && bash ../tool/check_ui_lint.sh` +Expected: PASS (**Local**). On a simulator or device: background 10 s → the session is untouched; background 60 s → paused line, return → reconnects into the same tmux window and the port forward is back (**Manual**). + +- [ ] **Step 5: Commit** + +```bash +git add app/lib app/ios/Runner/YourSshNative.swift app/test +git commit -m "feat: background grace, pause and foreground reconnect on iOS" +``` + +### Task 9: Private key storage and Files integration + +**Files:** +- Create: `app/lib/mobile/files/app_paths.dart`, `app/lib/mobile/files/file_export.dart` +- Modify: `app/lib/mobile/screens/mobile_keys_screen.dart:133-157` (`_importKey`: copy, register the copy, `FilePicker.platform.clearTemporaryFiles()`), `:322-327` (`_keysDir` → `AppPaths.privateKeysDir()`), `app/lib/mobile/screens/mobile_sftp_screen.dart:199-240` (`_download`: iOS → `AppPaths.downloadsDir()` + `uniqueLocalPath`, Android keeps `FilePicker.platform.getDirectoryPath()`; both stream through `writeDownload`; on iOS the success toast has a "Share" action calling `shareFile`; `_upload` clears picker temp files when done), `app/ios/Runner/YourSshNative.swift` (channel `yourssh/files`: `excludeFromBackup(path)` sets `URLResourceValues.isExcludedFromBackup = true`), `app/pubspec.yaml` + `pubspec.lock` (add `share_plus`), `app/ios/Runner/Info.plist` (`UIFileSharingEnabled` = true, `LSSupportsOpeningDocumentsInPlace` = true) +- Test: `app/test/mobile/app_paths_test.dart`, `app/test/mobile/file_export_test.dart` + +**Interfaces:** +- Consumes: `chmodNative`, `supportsSubprocesses`, `isIOSPlatform` (Tasks 1, 7), `safeLocalChild` / `UnsafeRemotePathException` (`app/lib/util/safe_local_path.dart`), `KeyProvider.addKeyFromFile(path, label)`. +- Produces: + - `AppPaths.privateKeysDir({ChmodFn? chmod, Future Function(String path)? excludeFromBackup})` → `/keys`, created, 0700, excluded from backup (default `excludeFromBackup` = the `yourssh/files` channel on iOS, no-op elsewhere; default `chmod` = `chmodNative` when `!supportsSubprocesses`, else `chmodLocal`) + - `AppPaths.downloadsDir()` → `/Downloads`, created + - `Future importPrivateKey(String pickedPath, Directory into, {ChmodFn? chmod})` — copies (never moves) to a unique sanitized name in `into`, 0600 + - `String uniqueLocalPath(String dir, String name)` — `safeLocalChild(dir, name)`, then `name (1).ext`, `name (2).ext`… until free + - `Future writeDownload(Stream> data, String finalPath)` — writes `finalPath.part`, renames on success, deletes it on any error and rethrows + - `Future shareFile(BuildContext context, String path)` — `share_plus` share sheet (pass `sharePositionOrigin` from the context's render box) +- No legacy key migration: iOS has no earlier install; Android's Documents directory is app-private and its existing keys stay where they are. + +- [ ] **Step 1: Write the failing tests** + +```dart +// app_paths_test.dart — fake PathProviderPlatform as in +// app/test/widgets/keychain_screen_test.dart (docs + support paths) +test('keys live outside Documents; downloads inside it', () async { + final keys = await AppPaths.privateKeysDir( + chmod: (_, _) async {}, excludeFromBackup: (_) async {}); + expect(p.isWithin(docs.path, keys.path), isFalse); + expect((await AppPaths.downloadsDir()).path, p.join(docs.path, 'Downloads')); +}); +test('the key directory is 0700 and excluded from backup', () async { + /* records chmod (path, 0x1C0) and excludeFromBackup(path) for keys dir */ +}); +test('importPrivateKey copies with 0600 and never overwrites', () async { + /* picked file stays; second import of the same name -> 'id_ed25519 (1)'; + injected chmod saw 0x180 */ +}); + +// file_export_test.dart +test('uniqueLocalPath never overwrites and rejects unsafe names', () { + /* 'a.txt' exists -> 'a (1).txt'; '../x' -> throwsA(isA()) */ +}); +test('writeDownload leaves nothing behind when the stream fails', () async { + final c = StreamController>(); + final f = writeDownload(c.stream, '${tmp.path}/out.bin'); + c..add([1, 2])..addError(Exception('connection closed')); + await expectLater(f, throwsException); + expect(File('${tmp.path}/out.bin').existsSync(), isFalse); + expect(File('${tmp.path}/out.bin.part').existsSync(), isFalse); +}); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/mobile/app_paths_test.dart test/mobile/file_export_test.dart` +Expected: FAIL (`AppPaths` not defined). (**Local**) + +- [ ] **Step 3: Implement** the files and the screen changes; Android keeps its directory picker but gets `writeDownload`. `ChmodFn` is `Future Function(String path, int mode)` (the `KeyGenService` constructor type). + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/mobile && bash ../tool/check_ui_lint.sh && flutter build ios --simulator --no-codesign` +Expected: PASS; build succeeds with `share_plus` (**Local**). In the Files app, "On My iPhone › YourSSH" shows only `Downloads` (**Manual**). + +- [ ] **Step 5: Commit** + +```bash +git add app/lib app/pubspec.yaml app/pubspec.lock app/ios app/test +git commit -m "feat: keep private keys out of Files and backups; iOS download/share/import" +``` + +### Task 10: Usage strings, encryption flag and privacy manifest + +**Files:** +- Modify: `app/ios/Runner/Info.plist` +- Create: `app/ios/Runner/PrivacyInfo.xcprivacy` (added to the Runner target's resources in `project.pbxproj`) +- Test: `app/test/platform/ios_plist_test.dart` + +**Interfaces:** +- Produces Info.plist keys: `NSCameraUsageDescription` ("Scan the QR code YourSSH shows on your computer to import hosts."), `NSLocalNetworkUsageDescription` ("YourSSH connects to SSH servers and to your computer on the local network to import or share hosts."), `NSFaceIDUsageDescription` (Task 6), `UIFileSharingEnabled` / `LSSupportsOpeningDocumentsInPlace` (Task 9), `ITSAppUsesNonExemptEncryption` = `true`. **No** `NSAppTransportSecurity`: all networking is `dart:io`, which ATS does not cover. +- Privacy manifest: `NSPrivacyTracking` = false, `NSPrivacyTrackingDomains` empty, `NSPrivacyCollectedDataTypes` empty array, `NSPrivacyAccessedAPITypes` = UserDefaults `CA92.1`, FileTimestamp `C617.1` (add SystemBootTime `35F9.1` only if a dependency needs it). + +- [ ] **Step 1: Write the failing test** + +```dart +test('Info.plist and privacy manifest carry the required entries', () { + final plist = File('ios/Runner/Info.plist').readAsStringSync(); + for (final k in ['NSCameraUsageDescription', 'NSLocalNetworkUsageDescription', + 'NSFaceIDUsageDescription', 'UIFileSharingEnabled', + 'LSSupportsOpeningDocumentsInPlace']) { + expect(plist, contains('$k')); + } + expect(plist, matches(RegExp( + r'ITSAppUsesNonExemptEncryption\s*'))); + expect(plist, isNot(contains('NSAppTransportSecurity'))); + final pm = File('ios/Runner/PrivacyInfo.xcprivacy').readAsStringSync(); + expect(pm, matches(RegExp(r'NSPrivacyTracking\s*'))); + expect(pm, contains('NSPrivacyAccessedAPICategoryUserDefaults')); + expect(pm, contains('CA92.1')); + expect(pm, contains('C617.1')); + expect(File('ios/Runner.xcodeproj/project.pbxproj').readAsStringSync(), + contains('PrivacyInfo.xcprivacy in Resources')); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `cd app && flutter test test/platform/ios_plist_test.dart` +Expected: FAIL (missing keys / file). (**Local**) + +- [ ] **Step 3: Add the keys and the manifest exactly as listed above.** + +- [ ] **Step 4: Run test, then build and lint the bundle's plist** + +Run: `cd app && flutter test test/platform/ios_plist_test.dart && flutter build ios --release --no-codesign && plutil -lint build/ios/iphoneos/Runner.app/Info.plist && test -f build/ios/iphoneos/Runner.app/PrivacyInfo.xcprivacy` +Expected: PASS; `OK` from plutil; the manifest is in the bundle (**Local**). Purpose-string (ITMS-90683) and required-reason (ITMS-91053) warnings are only reported by App Store Connect on the first upload (Task 13); fix them there (plugin build flags preferred over new permission strings). + +- [ ] **Step 5: Commit** + +```bash +git add app/ios app/test/platform/ios_plist_test.dart +git commit -m "feat: iOS usage strings, encryption declaration and privacy manifest" +``` + +### Task 11: `yourssh://` and opt-in `ssh://` links + +**Files:** +- Create: `app/lib/mobile/links/mobile_cli_handlers.dart`, `app/lib/mobile/links/ssh_link.dart`, `app/lib/mobile/links/mobile_links.dart` +- Modify: `app/ios/Runner/YourSshNative.swift` (`scene(_:willConnectTo:options:)` cold-start `urlContexts` and `scene(_:openURLContexts:)` route by scheme: `yourssh` → channel `yourssh/url`, `ssh` → `yourssh/ssh_url`; each forwards `open(String)` and queues the newest 8 until Dart calls `ready` — the contract of `app/macos/Runner/MainFlutterWindow.swift`), `app/ios/Runner/Info.plist` (`CFBundleURLTypes`: `yourssh` named "YourSSH URL", `ssh`), `app/lib/mobile/mobile_app.dart` (a `GlobalKey` on `MaterialApp`; `MobileLinks(...).attach()` after the first frame), `app/lib/mobile/screens/mobile_add_host_screen.dart` (`prefill` parameter: a new host form seeded with label/host/port/username, saved as a new host), `app/lib/mobile/screens/mobile_settings_screen.dart` (Security group: "Open ssh:// links" switch), `app/lib/mobile/util/mobile_prefs.dart` (`kSshLinksPrefKey`, default false) +- Test: `app/test/mobile/links/mobile_links_test.dart`, `app/test/mobile/links/ssh_link_test.dart` + +**Interfaces:** +- Consumes (unchanged): `CliServer({handlers, token, ready, onUrlRefused})`, `CliServer.dedupeWindow`, `UrlChannel(server:, channel:)` + `attach()`, `kUrlMethodChannel`, `CliHandlers`, `resolveHost(query, hosts, allowAdHoc:)` + `ResolvedHost`/`AmbiguousHost`/`AdHocTarget`/`UnknownHost`, `linkRefusedNotification(url, reason)`, `generateToken()` / `sanitize()` from `yourssh_cli`, `openMobileSession` (Task 2), `HostProvider.ready`, `KnownHostsProvider.ready`, `KeyProvider.ready`. +- Produces: + - `class MobileCliHandlers implements CliHandlers` — `MobileCliHandlers({required HostProvider hostProvider, required Future Function(Host host, String source) open, required String appVersion})`; `connect` → `open(host, source)`; `connectAdHoc` throws `StateError` (URLs never allow ad-hoc); `focusWindow` is a no-op + - `class MobileLinks` — `MobileLinks({required MobileBootstrap bootstrap, required GlobalKey navigator, required String appVersion, MethodChannel urlChannel = kUrlMethodChannel, MethodChannel sshChannel = kSshUrlChannel})` with `void attach()`: one `CliServer(handlers: MobileCliHandlers(open: (h, s) => openMobileSession(nav, h, auditSource: s, resetStack: true)), token: generateToken() /* never written anywhere */, ready: Future.wait([hostProvider.ready, knownHosts.ready, keyProvider.ready]), onUrlRefused: (url, reason) { final n = linkRefusedNotification(url, reason); AppSnack.error(ctx, '${n.title} — ${n.body}'); })`, `UrlChannel(server: …, channel: urlChannel).attach()`, and the `ssh` channel handler + its `ready` + - `const MethodChannel kSshUrlChannel = MethodChannel('yourssh/ssh_url')` + - `class SshLinkTarget { final String user; final String host; final int port; String get query; }` and `SshLinkTarget? parseSshLink(String url)` — accepts only `ssh://user@host[:port]` with an optional trailing `/`: no password, no `;` parameters, no other path, no query/fragment, ≤ 2048 chars, user/host/port by the resolver's rules (user `[A-Za-z0-9._-]+`, host DNS/IPv4/`[IPv6]`, port 1–65535, neither starting with `-`) + - `class SshLinkHandler` — `SshLinkHandler({required List Function() hosts, required Future Function() enabled, required Future Function(Host host) openSaved, required Future Function(SshLinkTarget t) confirm, required void Function(Host prefill) addHost, required void Function(String message) refused, DateTime Function() now = DateTime.now})` with `Future handle(String url)`: off → refused("ssh:// links are off (Settings › Security)"); unparsable → refused; `resolveHost(t.query, hosts(), allowAdHoc: true)`: `ResolvedHost` → `openSaved`, `AmbiguousHost`/`UnknownHost` → refused, `AdHocTarget` → `confirm` (`showYsConfirm` showing `sanitize`d `user@host:port`) → `addHost(Host(label: 'user@host', host:, port:, username:))`; a repeat of the same URL (case-insensitive) within `CliServer.dedupeWindow` is ignored + +- [ ] **Step 1: Write the failing tests** + +```dart +// mobile_links_test.dart — drive the real CliServer through UrlChannel with a +// mocked 'yourssh/url' channel (see app/test/services/cli/url_channel_test.dart) +test('yourssh://connect opens a saved host by label (NFC, any case)', () async { + /* host label 'Prod-DB' -> open('yourssh://connect/prod-db') -> opened ['Prod-DB:url'] */ +}); +test('unknown, ambiguous and unsupported links open nothing and are refused', + () async { + for (final u in ['yourssh://connect/nope', 'yourssh://connect/db' /* 'DB' + 'db' */, + 'yourssh://tunnel/start/x', 'yourssh://connect/a?cmd=id', + 'yourssh://u@connect/a', 'yourssh://connect/${'a' * 5000}']) { /* ... */ } + expect(opened, isEmpty); + expect(refused, hasLength(6)); + expect(refused.any((m) => m.contains('‮') || m.contains('\x1b')), isFalse); +}); +test('the same link twice within 2 s opens once', () async { /* ... */ }); + +// ssh_link_test.dart +test('parseSshLink accepts user@host[:port] and nothing else', () { + final t = parseSshLink('ssh://alice@10.0.0.5:2222')!; + expect([t.user, t.host, t.port], ['alice', '10.0.0.5', 2222]); + expect(parseSshLink('ssh://alice@[fe80::1]/')!.port, 22); + for (final u in ['ssh://10.0.0.5', 'ssh://a:pw@h', 'ssh://a;fingerprint=x@h', + 'ssh://a@h/path', 'ssh://a@h?x=1', 'ssh://a@h#f', 'ssh://-oProxyCommand=x@h', + 'ssh://a@-h', 'ssh://a@h:0', 'ssh://a@h:70000', + 'ssh://a@${'h' * 3000}', 'yourssh://connect/a']) { + expect(parseSshLink(u), isNull, reason: u); + } +}); +test('ssh:// is refused while the setting is off', () async { /* enabled false */ }); +test('ssh:// to a saved user@host:port opens that host', () async { /* openSaved */ }); +test('ssh:// to an unknown target asks first and only prefills Add Host', + () async { + /* confirm false -> nothing; confirm true -> addHost(Host(username: 'alice', + host: '203.0.113.7', port: 22)); openSaved never called */ +}); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd app && flutter test test/mobile/links` +Expected: FAIL with "MobileLinks isn't defined". (**Local**) + +- [ ] **Step 3: Implement the signatures.** No new URL parser for `yourssh://`: everything goes through `CliServer` (`connect/` only, id then label, saved hosts only, refused → `onUrlRefused`, audit source `url`). `openMobileSession` refuses RDP/VNC hosts (Task 2). A link that arrives while the app is locked opens its route under the lock (Task 6) and is revealed on unlock. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd app && flutter test test/mobile test/services/cli && flutter analyze --no-fatal-infos && bash ../tool/check_ui_lint.sh` +Expected: PASS (**Local**; the desktop CLI tests stay green). On a simulator, warm and cold: `xcrun simctl openurl booted "yourssh://connect/