diff --git a/.claude/skills/yourssh-screenshots/SKILL.md b/.claude/skills/yourssh-screenshots/SKILL.md index 9675eb7a..9f6c9667 100644 --- a/.claude/skills/yourssh-screenshots/SKILL.md +++ b/.claude/skills/yourssh-screenshots/SKILL.md @@ -5,57 +5,83 @@ description: Use when the user wants to update, refresh, or add screenshots for # yourssh-screenshots -Captures screenshots of every YourSSH feature screen using Flutter integration tests (render tree — no macOS Screen Recording permission needed). Saves PNGs to `screenshots//`, then updates README. +Default path: the **isolated docs journey** (`tool/docs_journey.sh`). It drives the real macOS app through every feature against demo Docker containers and captures ~209 PNGs (render tree, so no Screen Recording permission). The app runs with a temp `HOME`, in-memory prefs, fake secure storage and temp path_provider dirs, so the owner's real data is never touched; the script checks the real prefs plist mtime and `~/.yourssh` hash before/after (`ISOLATION OK`). -## Quick Reference +## Default workflow ```bash -# Capture all general feature screenshots -cd app && flutter test integration_test/feature_screenshots_test.dart -d macos - -# Capture RDP-specific screenshots (requires Docker) -cd app && flutter test integration_test/rdp_screenshots_test.dart -d macos - -# Capture Android/mobile screenshots (requires an emulator + Docker sshd) -flutter emulators --launch Medium_Phone_API_36.1 -docker run -d --name yourssh-ssh-demo -p 2222:2222 \ - -e PASSWORD_ACCESS=true -e USER_NAME=demo -e USER_PASSWORD=demo1234 \ - lscr.io/linuxserver/openssh-server:latest -cd app && flutter drive \ - --driver=test_driver/integration_test.dart \ - --target=integration_test/mobile_screenshots_test.dart -d emulator-5554 +tool/docs_journey.sh setup # client key + image + network + 5 demo containers (idempotent) +tool/docs_journey.sh all # build the integration app, then run desktop + mobile launches (~30 min, needs a GUI session) +# review screenshots/docs/INDEX.md (one line per shot) and screenshots/docs/BUGS.md (anomalies found) +tool/docs_journey.sh teardown # remove ONLY the containers/network/image that setup created ``` -## Folder Structure +- Output: `screenshots/docs//.png` + `INDEX.md` + `BUGS.md` (untracked; `DOCS_OUT` overrides). +- Subcommands: `setup | build | run | all | teardown`. `run` skips the build; `build` only builds. +- Re-run a subset: `SECTIONS="07,08" MODES=desktop tool/docs_journey.sh run` (section numbers are the `NN-` prefixes of `app/integration_test/docs/sNN_*.dart`; `MODES` is `desktop`, `mobile`, or both). Use `run` after one full `build`; rebuild (`build`) after any Dart change. +- Demo servers (loopback only; the harness expects these defaults): `yourssh-docs-ssh` 2222 (hostname `yourssh-demo`, user `demo`/`demo1234` + key auth), `yourssh-docs-bastion` 2223, `yourssh-docs-db` (network only, `db-internal:22`), `yourssh-docs-rdp` 3389 (`demo`/`demo12345`), `yourssh-docs-vnc` 5900 (`demo12345`). Image files: `tool/docs_journey/Dockerfile`. +- The generated ed25519 client key lives in `~/.local/state/yourssh-docs-journey` (`DOCS_KEY_DIR` overrides), never in the repo. Never commit keys. +- `DOCS_PREFIX` and `SSH_PORT/BASTION_PORT/RDP_PORT/VNC_PORT` let `setup`/`teardown` run side by side with another set of containers (only for testing setup; the journey itself needs the default ports). +- Timestamps/progress go to `$TMPDIR/yourssh-docs-run.*/run-*.log`; a hung mobile launch is retried once automatically. +## Refreshing the README images from a run + +README images are copies of journey shots, resized: `sips -Z 1440 --out ` (writes a copy; never edit the source). Mapping (README path <- journey shot; confirm each against `screenshots/docs/INDEX.md` because shot numbers shift when sections change): + +| README path (under `screenshots/`) | Journey shot | +|---|---| +| `01-terminal-ssh/01-hosts-dashboard.png` | `06-dashboard/01-grid.png` | +| `01-terminal-ssh/02-new-host-panel-ssh.png` | `02-add-host/01-new-host-panel.png` | +| `02-ssh-terminal-ai.png` | `16-ai-chat/04-chat-open.png` | +| `01-terminal-ssh/04-dashboard-with-rdp-badge.png` | `12-rdp/04-dashboard-rdp-badge.png` | +| `02-sftp/01-sftp-browser.png` | `07-sftp/03-dual-panel.png` | +| `03-port-forwarding/01-port-forward-rules.png` | `08-port-forwarding/05-rule-list.png` | +| `04-credentials-security/01-keychain.png` | `04-keychain/05-key-list.png` | +| `04-credentials-security/02-known-hosts.png` | `09-known-hosts/01-list.png` | +| `05-settings/01-settings-general.png` | `14-settings/01-settings-top.png` | +| `05-settings/02-settings-terminal.png` | `14-settings/03-terminal.png` | +| `05-settings/03-settings-sync.png` | `14-settings/09-sync.png` | +| `10-settings-sync-qr-code.png` | `14-settings/17-sync-qr-dialog.png` (see gaps) | +| `05-settings/04-settings-updates.png` | `14-settings/12-updates.png` | +| `05-settings/05-terminal-theme-picker.png` | `03-first-connect/19-theme-picker.png` | +| `06-plugins/01-plugins.png` | `15-plugins/01-manager.png` | +| `05-devops-hub-network-tools.png` | `17-devops/04-network-tools.png` | +| `08-web-tools-http-client.png` | `18-web-tools/03-get-response.png` | +| `09-snippets.png` | `15-plugins/03-snippets-screen.png` | +| `02-host-editor-rdp-form.png` | `12-rdp/03-editor-filled.png` | +| `03-tofu-certificate-dialog.png` | `12-rdp/05-cert-trust-dialog.png` | +| `04-rdp-workspace-connected.png` | `12-rdp/06-session-connected.png` | +| `05-fullscreen-with-pill.png` | `12-rdp/08-fullscreen-pill.png` | +| `06-fullscreen-clean.png` | `12-rdp/09-fullscreen-clean.png` | +| `07-fullscreen-hover-reveal.png` | `12-rdp/10-fullscreen-hover-pill.png` | +| `08-back-to-windowed.png` | `12-rdp/11-back-windowed.png` | +| `10-audit-recording/01-audit-log.png` | `11-audit-log/01-rows.png` | +| `10-audit-recording/02-recording-library.png` | `10-recordings/02-library.png` | +| `11-recording.png` | `10-recordings/03b-player-playing.png` | +| `12-multiple-player.png` | no journey shot (needs two clients; keep the existing image) | + +After copying, check every README path exists: +```bash +grep -o 'screenshots/[^"]*\.png' README.md | while read p; do [ -f "$p" ] && echo "OK: $p" || echo "MISSING: $p"; done ``` -screenshots/ - 01-terminal-ssh/ # Dashboard, host editor, SSH terminal - 02-sftp/ # Dual-panel SFTP - 03-port-forwarding/ # Port forward rules - 04-credentials-security/ # Keychain, known hosts - 05-settings/ # Settings sections - 06-plugins/ # Plugin manager - 07-rdp/ # RDP workspace (populated by rdp test) - 08-devops/ # DevOps hub - 10-audit-recording/ # Audit log, recording library - 11-mobile/ # Android screens (populated by the mobile test) - *.png # Legacy flat screenshots (keep for features needing live connections) -``` +New feature screens: add the step to the matching `app/integration_test/docs/sNN_*.dart`, rebuild, re-run that section, then add the README `` (2-column `` rows per feature group). + +## Known gaps -## How It Works +- WebViews are blank in render-tree capture (embedded browser, Monaco code editor, web tools browser): only the surrounding chrome is real. +- Mobile pair / LAN-sync QR dialogs show the machine's real LAN IP. Before publishing, re-encode the QR with a placeholder address or crop it out; otherwise note it in the PR. +- Terminal sharing (multiplayer) and anything needing a second client are not covered. +- Real AI providers are never called (no key); RDP/VNC need the containers running and a window that stays awake (the script runs `caffeinate`). -`integration_test/feature_screenshots_test.dart`: -1. Backs up user's real host data -2. Seeds demo hosts + port forward rules into SharedPreferences -3. Launches `app.main()` via Flutter integration test harness -4. Navigates each sidebar section by tapping the nav label text -5. Captures frames via `RendererBinding.instance.renderViews.first` -6. Restores user data in `finally` +## Do not use the legacy path by default -`integration_test/rdp_screenshots_test.dart`: -- Requires `docker run -d --name yourssh-rdp-demo -p 3389:3389 scottyhardy/docker-remote-desktop:latest` -- Connects to a real xrdp container; captures fullscreen + TOFU dialog screenshots +`app/integration_test/feature_screenshots_test.dart` and `rdp_screenshots_test.dart` back up and seed the user's REAL SharedPreferences (hosts, known hosts, port forwards) and restore them afterwards. A crash mid-run can leave demo data in the real profile. Use them only if the user explicitly asks; the journey above replaces them. + +```bash +# legacy, only on request +cd app && flutter test integration_test/feature_screenshots_test.dart -d macos +cd app && flutter test integration_test/rdp_screenshots_test.dart -d macos # needs the RDP container +``` ## Mobile (Android) capture @@ -79,7 +105,7 @@ Emulator gotchas: a full debug APK is ~185 MB, so `INSTALL_FAILED_INSUFFICIENT_S means the AVD's `/data` is full — reboot the emulator to reclaim cache. Biometric app-lock is force-disabled in setup because an emulator has no enrolled fingerprint. -## Adding a New Screen +## Adding a screen (legacy test only) 1. Open `app/integration_test/feature_screenshots_test.dart` 2. Navigate to the screen with `_navTo(tester, 'Label')` or tap the relevant widget @@ -88,28 +114,7 @@ app-lock is force-disabled in setup because an emulator has no enrolled fingerpr 5. Run the test to verify 6. Add the `` entry to README under the correct section -## Updating README - -The `## Screenshots` section in `README.md` is organized by feature groups matching the folder structure. Each group uses an HTML `
` with 2-column rows: - -```html -### Group Name -
- - - - -
Screen Title
Screen Title
-``` - -After updating, verify all paths exist: -```bash -grep -o 'screenshots/[^"]*\.png' README.md | while read p; do - [ -f "$p" ] && echo "OK: $p" || echo "MISSING: $p" -done -``` - -## Key Implementation Details +## Legacy test implementation details - **Storage keys**: `yourssh.hosts`, `yourssh.known_hosts`, `yourssh.port_forwards` (not bare `hosts`) - **Nav tap**: `find.text('Port Forwarding')`, `find.text('Known Hosts')`, etc. — matches sidebar label text @@ -117,7 +122,7 @@ done - **Debounce update check**: set `last_update_check` to `DateTime.now().millisecondsSinceEpoch` to prevent update banner polluting shots - **PortForward JSON**: stored as a flat list, `type` is the enum name (`local`, `remote`, `dynamic`) -## Common Mistakes +## Common mistakes (legacy test) | Problem | Fix | |---|---| diff --git a/CHANGELOG.md b/CHANGELOG.md index 59b4a6be..5cc44413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,28 @@ 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). +## [0.4.1] — 2026-11-13 + +Security and polish fixes found while writing the documentation (now at https://yoursshlabs.com). + +### Security +- **Android: the app lock now covers every screen.** The lock used to sit under any open screen, so a terminal, SFTP browser or dialog stayed visible above **YourSSH is locked** (and in the app switcher) after the app locked. The lock now covers the whole app; open screens and sessions survive the unlock. + +### Fixed +- Deleting a port-forwarding rule asks **Delete rule?** first, like every other destructive action. +- Removing a key from the Keychain also deletes the passphrase YourSSH saved for it, and a removed `~/.ssh` key no longer reappears at the next launch (import it again to bring it back). +- Script plugins: the documented `ui.*`, `ssh.*` and `storage.*` globals now exist (they used to fail with `'ui' is not defined`); `ui.notify` writes to the plugin console. +- Android: the pair-device screen says what actually syncs (hosts and their passwords — not keys or snippets), the Auto-lock row describes the real behaviour (**Immediately when you leave the app**), and the misleading per-host **Unlock with biometrics** switch is gone from the host form (the app lock lives in Settings → Security). +- The terminal-sharing dialog says sessions are end-to-end encrypted with the share code (it said "Shared over TLS"). + +### Documentation +- New documentation site: https://yoursshlabs.com. The README's macOS section reflects that releases are signed and notarized. + +### Added +- **Homebrew:** `brew install --cask yoursshlabs/tap/yourssh` (tap [YoursshLabs/homebrew-tap](https://github.com/YoursshLabs/homebrew-tap); the cask follows new releases automatically). + +--- + ## [0.4.0] — 2026-11-13 A new look (forui "Amber Brand" design system on desktop and mobile), a `yourssh` command-line client with `yourssh://` links, and a round of fixes found by driving the finished app end to end. diff --git a/CLAUDE.md b/CLAUDE.md index 24ddb41f..35c1ef23 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -226,10 +226,10 @@ Loaded at runtime from a plugins directory via `packages/yourssh_script_engine`. - `PluginUiRegistry` — plugins can register Flutter widgets by calling the `ui.register(id, widgetSpec)` JS API; the app renders these in the plugin manager **Bridges (Dart APIs exposed to JS):** -- `SshBridge` — `ssh.exec(sessionId, cmd)`, `ssh.write(sessionId, data)` -- `SftpBridge` — `sftp.list(sessionId, path)`, `sftp.readFile`, `sftp.writeFile` -- `StorageBridge` — `storage.get/set/delete(key)` (namespaced per plugin) -- `UiBridge` — `ui.showNotification(msg)`, `ui.register(id, spec)`; panel `postMessage` types handled natively in Dart (`ssh-exec`, `ssh-sessions`, `sftp-list`, `sftp-read`) enforce the same permissions as the bridges (`ssh.exec`, `session.observe`|`ssh.exec`, `sftp.read`) — a panel is plugin-controlled HTML +- Plugin globals come from a JS prelude (`_kPrelude` in `script_engine_service.dart`) that wraps the raw `_x` host functions (JSON in/out); a wrapper throws `Permission denied` when the bridge did not register the function, so `PermissionGuard` stays the only gate. Raw `_x.*` functions keep working. Documented in `docs/plugin-authoring-guide.md` section 5. +- `SshBridge` — `ssh.sessions()` (`session.observe`|`ssh.exec`); `TerminalInjectBridge` — `ssh.inject(sessionId, text)` (`terminal.inject`). No JS `ssh.exec`/`sftp` (the raw `_ssh.exec` and `_sftp.*` are stubs; use the panel messages below) +- `StorageBridge` — `storage.get/set/delete(key)` (sync, string values, namespaced per plugin, no permission) +- `UiBridge` — `ui.notify(msg, {type})` (host `onNotify`), `ui.statusbar.add/update/remove`, `ui.panel.register({title, icon, webviewEntry, onMessage})`, `ui.clipboard.copy`, `ui.addCommand` (handler not invoked yet); panel `postMessage` types handled natively in Dart (`ssh-exec`, `ssh-sessions`, `sftp-list`, `sftp-read`) enforce the same permissions as the bridges (`ssh.exec`, `session.observe`|`ssh.exec`, `sftp.read`) — a panel is plugin-controlled HTML **UI screens:** - `plugin_consent_dialog.dart` — shown on first load; user must accept declared permissions diff --git a/README.md b/README.md index 57276c39..ae55229d 100644 --- a/README.md +++ b/README.md @@ -19,32 +19,34 @@ A professional, open-source SSH client for **macOS**, **Windows**, and **Linux** ## Download -Get the latest release from the [Releases page](https://github.com/YoursshLabs/yourssh/releases). +Get the latest release from the [Releases page](https://github.com/YoursshLabs/yourssh/releases). Documentation: **https://yoursshlabs.com** (source: [YoursshLabs/docs](https://github.com/YoursshLabs/docs)). -YourSSH also checks for new releases on launch and from **Settings → Updates**; when a newer version is available it shows a banner and can download the right build for your OS and open the installer for you. Because the app is not code-signed, this is an assisted flow (it never silently replaces itself); if no matching build exists for your platform it opens the Releases page instead. +YourSSH also checks for new releases on launch and from **Settings → Updates**; when a newer version is available it shows a banner and can download the right build for your OS and open the installer for you. Because the installers are not silently swapped in, this is an assisted flow (it never silently replaces itself); if no matching build exists for your platform it opens the Releases page instead. | Platform | File | |---|---| -| macOS (Apple Silicon & Intel) | `YourSSH-x.x.x-macOS-universal.dmg` | +| macOS (Apple Silicon & Intel) | `YourSSH-x.x.x-macOS-universal.dmg` — or `brew install --cask yoursshlabs/tap/yourssh` | | Windows (x64) | `YourSSH.Setup.x.x.x-Windows-x64.exe` | | Windows (ARM64 — Surface, Snapdragon) | `YourSSH.Setup.x.x.x-Windows-arm64.exe` | | 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` | -### macOS — First Launch +### macOS — Homebrew -macOS may block the app on first open because it is not yet notarized with Apple. To open it: +```bash +brew tap yoursshlabs/tap +brew trust yoursshlabs/tap # Homebrew asks you to trust third-party taps once +brew install --cask yoursshlabs/tap/yourssh +``` -1. **Right-click** (or Control-click) the app → **Open** -2. Click **Open** in the dialog that appears +The cask ([YoursshLabs/homebrew-tap](https://github.com/YoursshLabs/homebrew-tap)) installs the same signed, notarized universal DMG from the Releases page and follows new releases automatically. YourSSH also updates itself from inside the app; `brew upgrade --cask yourssh` works too. -You only need to do this once. After that, the app opens normally. +### macOS — Signed and notarized -Alternatively, run this in Terminal: -```bash -xattr -dr com.apple.quarantine /Applications/YourSSH.app -``` +The DMG and zip are signed with an Apple Developer ID (**SENPRINTS LLC, team 84T567KMYD**) and notarized + stapled by Apple, so YourSSH opens normally: drag it to **Applications** and launch it. You can check a download with `spctl -a -t open --context context:primary-signature -vv YourSSH-x.x.x-macOS-universal.dmg` (expect `source=Notarized Developer ID`). The in-app updater only opens a macOS installer that carries this team's Developer ID signature. + +> Building from source, or using an unsigned fork? macOS may block the app on first open. Right-click the app → **Open**, or run `xattr -dr com.apple.quarantine /Applications/YourSSH.app`. ### Windows — Installation @@ -81,7 +83,7 @@ sudo dpkg -r yourssh - **In-app RDP client** — connect to Windows, xrdp, and any RDP-compatible server directly from a tab alongside your SSH sessions; supports NLA, TLS, and auto security modes; optional SSH tunnel via a saved jump host; server-certificate TOFU with pre-auth pin enforcement (a changed certificate aborts before your credentials are sent); **fullscreen mode** with an mstsc-style hover bar at the top edge; full keyboard and mouse support (including Ctrl+Alt+Del); bidirectional clipboard; RDP tabs excluded from terminal-only features (recording, split view, input bar, snippets) - **In-app VNC client** — connect to Linux VNC servers (TigerVNC, x11vnc, TightVNC) as first-class tabs too; RFB with None / VNC-password auth, framebuffer rendering, full mouse + keyboard, bidirectional clipboard, server-driven auto-resize, optional SSH tunnel through a saved jump host, and the same fullscreen hover-bar UX as RDP - **Multi-tab SSH sessions** with named tabs, per-tab connection state, distro icons (detected via `/etc/os-release`), and middle-click to close -- **Terminal sharing (multiplayer)** — share a live SSH session with a session code; guests join via the Command Palette and watch or interact in real time; built on Supabase Realtime +- **Terminal sharing (multiplayer)** — share a live SSH session with a session code; guests join via the Command Palette and watch or interact in real time; built on Supabase Realtime; every message is end-to-end encrypted (AES-256-GCM) with a key derived from the share code - **Split terminal view** — horizontal/vertical pane splitting within a session - **Search-in-scrollback (Cmd/Ctrl+F)** — regex-powered search across the full terminal buffer; highlights all matches, navigate with Enter / Shift+Enter - **Copy & paste that just works** — `Ctrl+C` copies when text is selected and stays SIGINT otherwise (Windows Terminal behavior); `Cmd+C/V` on macOS, `Ctrl(+Shift)+V` to paste, right-click Copy/Paste/Select All menu, and middle-click paste diff --git a/app/lib/main.dart b/app/lib/main.dart index 89c334f4..7eb8e896 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -241,6 +241,7 @@ class _YourSSHAppState extends State with WindowListener { _hostProvider = HostProvider(_storage); _keyProvider = KeyProvider(); _keyProvider.savePassphrase = _storage.savePassphrase; + _keyProvider.deletePassphrase = _storage.deletePassphrase; _settingsProvider = SettingsProvider(); _ssh.isShellIntegrationEnabled = () => _settingsProvider.shellIntegrationEnabled; @@ -387,6 +388,9 @@ class _YourSSHAppState extends State with WindowListener { onLog: (pluginId, level, message) { _pluginEngineProvider.addLog(pluginId, '[$level] $message'); }, + onNotify: (pluginId, message, type) { + _pluginEngineProvider.addLog(pluginId, '[notify:$type] $message'); + }, ); // PluginEngineProvider must be created before PluginLoader because the // loader's onConsentRequired callback closes over _pluginEngineProvider. diff --git a/app/lib/mobile/mobile_app.dart b/app/lib/mobile/mobile_app.dart index e7dd3280..440ddccd 100644 --- a/app/lib/mobile/mobile_app.dart +++ b/app/lib/mobile/mobile_app.dart @@ -36,9 +36,14 @@ class _YourSSHMobileAppState extends State { debugShowCheckedModeBanner: false, themeMode: ThemeMode.dark, theme: buildMobileTheme(), - builder: ysRootBuilderTouch, + // The lock wraps the whole navigator, so pushed routes and dialogs are + // covered too. It sits outside ysRootBuilderTouch's FToaster so toasts + // stay under the lock as well. + builder: (c, child) => AppLockGate( + child: ysRootBuilderTouch(c, child), + ), navigatorObservers: [mobileRouteObserver], - home: const AppLockGate(child: MobileHomeShell()), + home: const MobileHomeShell(), ), ); } diff --git a/app/lib/mobile/mobile_bootstrap.dart b/app/lib/mobile/mobile_bootstrap.dart index 5ebcfe89..d006bee4 100644 --- a/app/lib/mobile/mobile_bootstrap.dart +++ b/app/lib/mobile/mobile_bootstrap.dart @@ -43,7 +43,9 @@ class MobileBootstrap { storage = StorageService(); ssh = SshService(storage); hostProvider = HostProvider(storage); - keyProvider = KeyProvider()..savePassphrase = storage.savePassphrase; + keyProvider = KeyProvider() + ..savePassphrase = storage.savePassphrase + ..deletePassphrase = storage.deletePassphrase; settings = SettingsProvider(); knownHosts = KnownHostsProvider(storage)..load(); sessions = SessionProvider(ssh, TabMetadataService()); diff --git a/app/lib/mobile/screens/mobile_add_host_screen.dart b/app/lib/mobile/screens/mobile_add_host_screen.dart index 3e1d76f1..6c7917e7 100644 --- a/app/lib/mobile/screens/mobile_add_host_screen.dart +++ b/app/lib/mobile/screens/mobile_add_host_screen.dart @@ -1,7 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; -import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh_ui/yourssh_ui.dart'; import '../../models/host.dart'; @@ -9,13 +8,11 @@ import '../../models/ssh_key.dart'; import '../../providers/host_provider.dart'; import '../../providers/key_provider.dart'; import '../../providers/session_provider.dart'; -import '../security/app_lock_gate.dart'; import '../theme/mobile_theme.dart'; import '../theme/mobile_tokens.dart'; import '../widgets/button_label.dart'; import '../widgets/list_group.dart'; import '../widgets/section_header.dart'; -import '../widgets/settings_row.dart'; /// Grouped add/edit host form for mobile (Design 02). /// @@ -348,7 +345,6 @@ class _MobileAddHostScreenState extends State { hint: _isEdit ? 'Leave blank to keep current' : null, textInputAction: TextInputAction.done, ), - const ListGroup(children: [_BiometricRow()]), ]); } @@ -560,45 +556,3 @@ class _CertAgentNoteRow extends StatelessWidget { ); } } - -/// Toggle row for Face ID / biometric app-lock (reads/writes -/// [kAppLockPrefKey] in SharedPreferences — same key as AppLockGate). -class _BiometricRow extends StatefulWidget { - const _BiometricRow(); - - @override - State<_BiometricRow> createState() => _BiometricRowState(); -} - -class _BiometricRowState extends State<_BiometricRow> { - bool _enabled = true; - bool _loaded = false; - - @override - void initState() { - super.initState(); - SharedPreferences.getInstance().then((p) { - if (!mounted) return; - setState(() { - _enabled = p.getBool(kAppLockPrefKey) ?? true; - _loaded = true; - }); - }); - } - - Future _toggle(bool v) async { - setState(() => _enabled = v); - final p = await SharedPreferences.getInstance(); - await p.setBool(kAppLockPrefKey, v); - } - - @override - Widget build(BuildContext context) { - if (!_loaded) return const SizedBox.shrink(); - return SettingsRow( - title: 'Unlock with biometrics', - toggle: _enabled, - onToggle: _toggle, - ); - } -} diff --git a/app/lib/mobile/screens/mobile_settings_screen.dart b/app/lib/mobile/screens/mobile_settings_screen.dart index 2a9b6ea4..17baa5e3 100644 --- a/app/lib/mobile/screens/mobile_settings_screen.dart +++ b/app/lib/mobile/screens/mobile_settings_screen.dart @@ -165,7 +165,7 @@ class _MobileSettingsScreenState extends State { SettingsRow( leading: const Icon(FLucideIcons.timer, color: MobileColors.textMuted, size: 20), title: 'Auto-lock', - value: 'After 1 min', + value: 'Immediately when you leave the app', ), ], ); diff --git a/app/lib/mobile/screens/mobile_sync_screen.dart b/app/lib/mobile/screens/mobile_sync_screen.dart index 76d575b1..f09dd3d7 100644 --- a/app/lib/mobile/screens/mobile_sync_screen.dart +++ b/app/lib/mobile/screens/mobile_sync_screen.dart @@ -271,11 +271,11 @@ class _MobileSyncScreenState extends State { Widget _buildHero() => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text('Sync with Supabase', style: mobileHeading(size: 22)), + Text('Sync between devices', style: mobileHeading(size: 22)), const SizedBox(height: MobileTokens.space2), Text( - 'No account needed. Your hosts, keys & snippets stay end-to-end ' - 'encrypted across devices.', + 'No account needed. Syncs your hosts and their passwords. ' + 'Keys and snippets are not synced.', style: mobileBody(size: 14, color: MobileColors.textMuted), ), ], diff --git a/app/lib/mobile/security/app_lock_gate.dart b/app/lib/mobile/security/app_lock_gate.dart index 37b96420..2039cf90 100644 --- a/app/lib/mobile/security/app_lock_gate.dart +++ b/app/lib/mobile/security/app_lock_gate.dart @@ -115,7 +115,23 @@ class _AppLockGateState extends State with WidgetsBindingObserver { @override Widget build(BuildContext context) { if (!_locked) return widget.child; - // Nothing of the app is built while locked: only this screen. + // 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 + // snapshot can show it. The lock screen is built outside the Navigator, so + // it brings its own FTheme (the gate sits above the app's FTheme/FToaster). + return Stack( + fit: StackFit.expand, + children: [ + Offstage( + child: TickerMode(enabled: false, child: widget.child), + ), + FTheme(data: ysThemeDataTouch(), child: _lockScreen()), + ], + ); + } + + Widget _lockScreen() { return Scaffold( backgroundColor: YsColors.background, body: Center( diff --git a/app/lib/providers/key_provider.dart b/app/lib/providers/key_provider.dart index 912340f3..11204f33 100644 --- a/app/lib/providers/key_provider.dart +++ b/app/lib/providers/key_provider.dart @@ -7,6 +7,7 @@ import '../models/ssh_key.dart'; class KeyProvider extends ChangeNotifier { static const _prefsKey = 'yourssh.keys'; + static const _dismissedKey = 'yourssh.keys.dismissed'; List _keys = []; List get keys => _keys; @@ -18,7 +19,11 @@ class KeyProvider extends ChangeNotifier { /// read the real home directory. final bool discoverSshKeys; - KeyProvider({this.discoverSshKeys = true}) { + /// Directory scanned by auto-discovery; defaults to `~/.ssh`. Tests inject a + /// temp dir. + final String? sshDirPath; + + KeyProvider({this.discoverSshKeys = true, this.sshDirPath}) { ready = _load(); } @@ -40,8 +45,10 @@ class KeyProvider extends ChangeNotifier { } Future _discoverSshKeys() async { - final sshDir = Directory(p.join(Platform.environment['HOME'] ?? '', '.ssh')); + final sshDir = Directory( + sshDirPath ?? p.join(Platform.environment['HOME'] ?? '', '.ssh')); if (!sshDir.existsSync()) return; + final dismissed = await _loadDismissed(); final knownPrivate = {'id_ed25519', 'id_rsa', 'id_ecdsa', 'id_dsa'}; for (final name in knownPrivate) { @@ -50,6 +57,8 @@ class KeyProvider extends ChangeNotifier { if (!keyFile.existsSync()) continue; // Skip already registered keys if (_keys.any((k) => k.privateKeyPath == keyFile.path)) continue; + // Skip keys the user removed earlier + if (dismissed.contains(keyFile.path)) continue; final algo = _algorithmFrom(name); final pubKey = pubFile.existsSync() ? pubFile.readAsStringSync().trim() : ''; @@ -78,6 +87,24 @@ class KeyProvider extends ChangeNotifier { /// main.dart — StorageService is not in the provider tree). Future Function(String keyId, String passphrase)? savePassphrase; + /// Deletes a key's stored passphrase (wired to + /// StorageService.deletePassphrase in main.dart / mobile bootstrap). + Future Function(String keyId)? deletePassphrase; + + Future> _loadDismissed() async { + final prefs = await SharedPreferences.getInstance(); + return (prefs.getStringList(_dismissedKey) ?? const []).toSet(); + } + + Future _saveDismissed(Set paths) async { + final prefs = await SharedPreferences.getInstance(); + if (paths.isEmpty) { + await prefs.remove(_dismissedKey); + } else { + await prefs.setStringList(_dismissedKey, paths.toList()); + } + } + Future addKeyFromFile(String path, String label) async { final file = File(path); if (!file.existsSync()) throw Exception('Key file not found: $path'); @@ -93,6 +120,9 @@ class KeyProvider extends ChangeNotifier { privateKeyPath: path, ); _keys.add(entry); + // Explicit re-import clears an earlier dismissal of this path. + final dismissed = await _loadDismissed(); + if (dismissed.remove(path)) await _saveDismissed(dismissed); final certFile = File('$path-cert.pub'); if (certFile.existsSync()) { _keys.last.certificatePath = certFile.path; @@ -103,8 +133,20 @@ class KeyProvider extends ChangeNotifier { } Future deleteKey(String id) async { + final removed = findById(id); _keys.removeWhere((k) => k.id == id); await _save(); + // Remember the path so auto-discovery doesn't re-add it next launch. + final path = removed?.privateKeyPath; + if (path != null && path.isNotEmpty) { + final dismissed = await _loadDismissed(); + if (dismissed.add(path)) await _saveDismissed(dismissed); + } + try { + await deletePassphrase?.call(id); + } catch (e) { + debugPrint('[KeyProvider] failed to delete passphrase for $id: $e'); + } notifyListeners(); } diff --git a/app/lib/services/storage_service.dart b/app/lib/services/storage_service.dart index ed9eb848..f5b68a5c 100644 --- a/app/lib/services/storage_service.dart +++ b/app/lib/services/storage_service.dart @@ -149,6 +149,8 @@ class StorageService { Future loadPassphrase(String keyId) => _loadSecret('pp_$keyId'); + Future deletePassphrase(String keyId) => _deleteSecret('pp_$keyId'); + /// Generic secret store for app-scoped secrets (e.g., sync passphrase). /// Caller is responsible for key namespacing. Future saveGenericSecret(String key, String value) => diff --git a/app/lib/widgets/port_forwarding_screen.dart b/app/lib/widgets/port_forwarding_screen.dart index 4704e23b..56567cc1 100644 --- a/app/lib/widgets/port_forwarding_screen.dart +++ b/app/lib/widgets/port_forwarding_screen.dart @@ -174,6 +174,14 @@ class _ForwardTileState extends State<_ForwardTile> { } Future _delete() async { + final ok = await showYsConfirm( + context, + title: 'Delete rule?', + message: '${widget.forward.label} (${widget.forward.summary})', + confirmLabel: 'Delete', + destructive: true, + ); + if (!ok || !mounted) return; final service = context.read(); final provider = context.read(); await service.stop(widget.forward.id); diff --git a/app/lib/widgets/share_session_dialog.dart b/app/lib/widgets/share_session_dialog.dart index 990741f1..e3d8e532 100644 --- a/app/lib/widgets/share_session_dialog.dart +++ b/app/lib/widgets/share_session_dialog.dart @@ -63,7 +63,7 @@ class _StartSharingView extends StatelessWidget { ), const SizedBox(height: YsSpace.s1), const Text( - 'Shared over TLS via your Supabase project.', + 'End-to-end encrypted with the share code.', style: TextStyle(color: YsColors.off, fontSize: 11), ), const SizedBox(height: YsSpace.s5 - 4), diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 546458bc..a00cdc62 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -1,7 +1,7 @@ name: yourssh description: YourSSH - A professional SSH client for macOS, Windows, and Linux with advanced features like SFTP, port forwarding, and a built-in code editor. publish_to: 'none' -version: 0.4.0+4 +version: 0.4.1+5 environment: sdk: ^3.13.0 diff --git a/app/test/mobile/app_lock_gate_test.dart b/app/test/mobile/app_lock_gate_test.dart index 598e8bb7..0291ec7a 100644 --- a/app/test/mobile/app_lock_gate_test.dart +++ b/app/test/mobile/app_lock_gate_test.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:yourssh/mobile/security/app_lock_gate.dart'; +import 'package:yourssh/theme/app_theme.dart'; import 'package:yourssh_ui/yourssh_ui.dart'; import '../helpers/ys_test_app.dart'; @@ -37,7 +38,7 @@ void main() { expect(find.text('Unlock'), findsOneWidget); }); - testWidgets('lock screen: wording, FButton >= 44 px, nothing behind it', + testWidgets('lock screen: wording, FButton >= 44 px, child offstage', (tester) async { await _pump(tester, enabled: true, auth: () async => false); expect(find.text('YourSSH is locked'), findsOneWidget); @@ -45,8 +46,9 @@ void main() { final size = tester.getSize(find.byType(FButton)); expect(size.height, greaterThanOrEqualTo(44)); expect(size.width, greaterThanOrEqualTo(44)); + // The child stays mounted (sessions/routes survive) but offstage. expect(find.byKey(_childKey), findsNothing); - expect(find.byKey(_childKey, skipOffstage: false), findsNothing); + expect(find.byKey(_childKey, skipOffstage: false), findsOneWidget); }); testWidgets('Unlock retries auth and unlocks on success', (tester) async { @@ -58,4 +60,89 @@ void main() { expect(calls, 2); expect(find.byKey(_childKey), findsOneWidget); }); + + group('gate in MaterialApp.builder covers every route', () { + final nav = GlobalKey(); + var calls = 0; + var allow = false; + + Future pumpApp(WidgetTester t) async { + calls = 0; + await t.pumpWidget(MaterialApp( + navigatorKey: nav, + theme: ysMaterialTheme(), + // Mirrors mobile_app.dart: gate outside the toaster so toasts stay + // under the lock too. + builder: (c, child) => AppLockGate( + enabledOverride: true, + authenticator: () async { + calls++; + return allow; + }, + child: ysRootBuilderTouch(c, child), + ), + home: const Text('home'), + )); + await t.pumpAndSettle(); + } + + testWidgets('pushed route is covered while locked and survives unlock', + (t) async { + allow = false; + await pumpApp(t); + nav.currentState! + .push(MaterialPageRoute(builder: (_) => const Text('terminal'))); + await t.pumpAndSettle(); + expect(find.text('YourSSH is locked'), findsOneWidget); + expect(find.text('terminal'), findsNothing); + 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, no prompt loop', + (t) async { + allow = true; + await pumpApp(t); + nav.currentState! + .push(MaterialPageRoute(builder: (_) => const Text('terminal'))); + await t.pumpAndSettle(); + expect(find.text('terminal'), findsOneWidget); + expect(calls, 1); + t.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + await t.pump(); + expect(find.text('terminal'), findsNothing); + expect(find.text('YourSSH is locked'), findsOneWidget); + t.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await t.pumpAndSettle(); + expect(find.text('terminal'), findsOneWidget); + expect(calls, 2); + }); + + testWidgets('a dialog on the root navigator is covered while locked', + (t) async { + allow = false; + await pumpApp(t); + showDialog( + context: nav.currentContext!, + builder: (_) => const AlertDialog(content: Text('secret dialog'))); + await t.pumpAndSettle(); + expect(find.text('YourSSH is locked'), findsOneWidget); + expect(find.text('secret dialog'), findsNothing); + expect(find.text('secret dialog', skipOffstage: false), findsOneWidget); + }); + + testWidgets('a toast shown while locked does not paint above the lock', + (t) async { + allow = false; + await pumpApp(t); + showFToast( + context: nav.currentContext!, title: const Text('secret toast')); + await t.pumpAndSettle(); + expect(find.text('YourSSH is locked'), findsOneWidget); + expect(find.text('secret toast'), findsNothing); + }); + }); } diff --git a/app/test/mobile/mobile_settings_screen_test.dart b/app/test/mobile/mobile_settings_screen_test.dart index 5a5216ee..f470c82f 100644 --- a/app/test/mobile/mobile_settings_screen_test.dart +++ b/app/test/mobile/mobile_settings_screen_test.dart @@ -68,7 +68,7 @@ void main() { await tester.pump(const Duration(milliseconds: 200)); // MobileSyncScreen heading must be visible. - expect(find.text('Sync with Supabase'), findsOneWidget); + expect(find.text('Sync between devices'), findsOneWidget); expect(find.byType(MobileSyncScreen), findsOneWidget); }); @@ -79,6 +79,6 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(find.byType(MobileSyncScreen), findsOneWidget); - expect(find.text('Sync with Supabase'), findsOneWidget); + expect(find.text('Sync between devices'), findsOneWidget); }); } diff --git a/app/test/mobile/screens/add_host_screen_test.dart b/app/test/mobile/screens/add_host_screen_test.dart index 4ad53b98..f93ceeba 100644 --- a/app/test/mobile/screens/add_host_screen_test.dart +++ b/app/test/mobile/screens/add_host_screen_test.dart @@ -4,7 +4,6 @@ import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:yourssh/mobile/screens/mobile_add_host_screen.dart'; -import 'package:yourssh/mobile/security/app_lock_gate.dart'; import 'package:yourssh/mobile/theme/mobile_theme.dart'; import 'package:yourssh/models/app_session.dart'; import 'package:yourssh/theme/app_theme.dart'; @@ -222,32 +221,16 @@ void main() { expect(_editable(tester, snippetField).controller.text, 'tmux attach'); }); - // ── Fix 1: biometric toggle uses the shared kAppLockPrefKey ───────────── + // The app lock lives in Settings -> Security, not in the per-host form. - testWidgets('biometric toggle persists under shared kAppLockPrefKey', - (tester) async { + testWidgets('host form has no app-lock / biometric switch', (tester) async { SharedPreferences.setMockInitialValues({}); final hosts = HostProvider(StorageService()); await tester.pumpWidget(_wrap(hosts, const MobileAddHostScreen())); await tester.pumpAndSettle(); - // The switch should be present and enabled by default (kAppLockPrefKey - // absent → defaults to true). - final switchFinder = find.byType(FSwitch); - expect(switchFinder, findsOneWidget); - expect(tester.widget(switchFinder).value, isTrue); - - // Toggle it off. - await tester.ensureVisible(switchFinder); - await tester.pumpAndSettle(); - await tester.tap(switchFinder); - await tester.pumpAndSettle(); - - final prefs = await SharedPreferences.getInstance(); - // Must write under the SHARED key, not a local orphan key. - expect(prefs.getBool(kAppLockPrefKey), isFalse); - // The old orphan key must not exist. - expect(prefs.getBool('yourssh.app_lock_enabled'), isNull); + expect(find.byType(FSwitch), findsNothing); + expect(find.text('Unlock with biometrics'), findsNothing); }); // ── Fix 2: "Save & connect" wires connectAny; plain "Save" does not ───── diff --git a/app/test/mobile/screens/settings_screen_test.dart b/app/test/mobile/screens/settings_screen_test.dart index 0164dac1..b55f92d4 100644 --- a/app/test/mobile/screens/settings_screen_test.dart +++ b/app/test/mobile/screens/settings_screen_test.dart @@ -135,7 +135,7 @@ void main() { for (final t in [ 'Biometric unlock', 'Auto-lock', - 'After 1 min', + 'Immediately when you leave the app', 'Shortcut key bar', 'Supabase sync', 'Pair new device', diff --git a/app/test/mobile/screens/sync_screen_test.dart b/app/test/mobile/screens/sync_screen_test.dart index c4f6a383..424c2244 100644 --- a/app/test/mobile/screens/sync_screen_test.dart +++ b/app/test/mobile/screens/sync_screen_test.dart @@ -64,9 +64,11 @@ Future _pump( void main() { setUp(() => SharedPreferences.setMockInitialValues({})); - testWidgets('renders heading "Sync with Supabase"', (tester) async { + testWidgets('renders heading "Sync between devices"', (tester) async { await _pump(tester); - expect(find.text('Sync with Supabase'), findsOneWidget); + expect(find.text('Sync between devices'), findsOneWidget); + expect(find.textContaining('Keys and snippets are not synced'), findsOneWidget); + expect(find.textContaining('end-to-end'), findsNothing); }); testWidgets('renders "Scan QR code" button', (tester) async { diff --git a/app/test/providers/key_provider_test.dart b/app/test/providers/key_provider_test.dart index e9487d4c..574aee57 100644 --- a/app/test/providers/key_provider_test.dart +++ b/app/test/providers/key_provider_test.dart @@ -7,6 +7,7 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUp(() => SharedPreferences.setMockInitialValues({})); + _keyRemovalTests(); group('KeyProvider certificate methods', () { test('setCertificate persists certificatePath on the key entry', () async { @@ -58,3 +59,72 @@ String _tmpKeyFile() { f.writeAsStringSync('placeholder'); return f.path; } + +void _keyRemovalTests() { + group('KeyProvider removal', () { + late Directory sshDir; + setUp(() { + SharedPreferences.setMockInitialValues({}); + sshDir = Directory.systemTemp.createTempSync('ssh_dir_'); + File('${sshDir.path}/id_ed25519').writeAsStringSync('k'); + File('${sshDir.path}/id_ed25519.pub').writeAsStringSync('pub'); + }); + tearDown(() => sshDir.deleteSync(recursive: true)); + + test('deleteKey deletes the stored passphrase', () async { + final provider = KeyProvider(discoverSshKeys: false); + await provider.ready; + final deleted = []; + provider.deletePassphrase = (id) async => deleted.add(id); + final entry = await provider.addKeyFromFile(_tmpKeyFile(), 'k'); + + await provider.deleteKey(entry.id); + + expect(deleted, [entry.id]); + }); + + test('a failing passphrase delete does not break removal', () async { + final provider = KeyProvider(discoverSshKeys: false); + await provider.ready; + provider.deletePassphrase = (id) async => throw Exception('boom'); + final entry = await provider.addKeyFromFile(_tmpKeyFile(), 'k'); + + await provider.deleteKey(entry.id); + + expect(provider.keys, isEmpty); + }); + + test('removed auto-discovered key is not re-added on next launch', () async { + final first = KeyProvider(sshDirPath: sshDir.path); + await first.ready; + expect(first.keys, hasLength(1)); + await first.deleteKey(first.keys.first.id); + + final second = KeyProvider(sshDirPath: sshDir.path); + await second.ready; + + expect(second.keys, isEmpty); + }); + + test('explicit re-import clears the dismissal', () async { + final first = KeyProvider(sshDirPath: sshDir.path); + await first.ready; + await first.deleteKey(first.keys.first.id); + + final second = KeyProvider(sshDirPath: sshDir.path); + await second.ready; + await second.addKeyFromFile('${sshDir.path}/id_ed25519', 'again'); + expect(second.keys, hasLength(1)); + await second.deleteKey(second.keys.first.id); + + // Re-import then (no) removal: dismissal was cleared, so re-importing + // and relaunching keeps the key. + final third = KeyProvider(sshDirPath: sshDir.path); + await third.ready; + await third.addKeyFromFile('${sshDir.path}/id_ed25519', 'again'); + final fourth = KeyProvider(sshDirPath: sshDir.path); + await fourth.ready; + expect(fourth.keys, hasLength(1)); + }); + }); +} diff --git a/app/test/widgets/port_forwarding_screen_test.dart b/app/test/widgets/port_forwarding_screen_test.dart index 772cd7cb..29e76607 100644 --- a/app/test/widgets/port_forwarding_screen_test.dart +++ b/app/test/widgets/port_forwarding_screen_test.dart @@ -210,6 +210,19 @@ void main() { await tester.tap(find.text('Delete')); await tester.pumpAndSettle(); + // Confirmation first: nothing is removed until Delete is confirmed. + expect(find.text('Delete rule?'), findsOneWidget); + expect(provider.forwards, hasLength(1)); + await tester.tap(find.widgetWithText(FButton, 'Cancel')); + await tester.pumpAndSettle(); + expect(provider.forwards, hasLength(1)); + expect(lastService.stopped, isEmpty); + + await rightClick(tester, find.text('delete via menu')); + await tester.tap(find.text('Delete')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(FButton, 'Delete')); + await tester.pumpAndSettle(); expect(provider.forwards, isEmpty); }); @@ -246,6 +259,9 @@ void main() { await hover(tester, find.text('tile buttons')); await tester.tap(find.byTooltip('Delete')); await tester.pumpAndSettle(); + expect(find.text('Delete rule?'), findsOneWidget); + await tester.tap(find.widgetWithText(FButton, 'Delete')); + await tester.pumpAndSettle(); expect(provider.forwards, isEmpty); expect(lastService.stopped, hasLength(2)); }); @@ -478,6 +494,9 @@ void main() { expect(focusedTooltip(), 'Delete'); await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); + expect(find.text('Delete rule?'), findsOneWidget); + await tester.tap(find.widgetWithText(FButton, 'Delete')); + await tester.pumpAndSettle(); expect(provider.forwards, isEmpty); }); } diff --git a/app/test/widgets/share_dialogs_test.dart b/app/test/widgets/share_dialogs_test.dart index 6a1b980c..1bba4921 100644 --- a/app/test/widgets/share_dialogs_test.dart +++ b/app/test/widgets/share_dialogs_test.dart @@ -142,7 +142,7 @@ void main() { findsOneWidget, ); expect( - find.text('Shared over TLS via your Supabase project.'), + find.text('End-to-end encrypted with the share code.'), findsOneWidget, ); diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 01dd470c..8a9911f3 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -35,8 +35,7 @@ App (Dart) Plugin (JavaScript) │ │──session opens──► plugin.on("session.connect", handler) │ │ - │──ssh.exec()────► ssh.exec(sessionId, "whoami") - │◄──result──────── Promise<{stdout, stderr, exitCode}> + │◄──ssh.inject()── ssh.inject(sessionId, "whoami\n") ``` --- @@ -275,25 +274,7 @@ ssh.inject(sessionId, "ls -la\n"); // \n submits the command ### `sftp` — File operations -> **Permission:** `sftp.read` (for list/read) or `sftp.write` (for write/delete/mkdir) - -```js -// List remote directory -const entries = await sftp.list(sessionId, "/var/log"); -// entries: [{ name, isDir, size, modified }] - -// Read remote file content -const content = await sftp.read(sessionId, "/etc/hostname"); - -// Write to remote file -await sftp.write(sessionId, "/tmp/test.txt", "hello world"); - -// Delete remote file -await sftp.delete(sessionId, "/tmp/test.txt"); - -// Create remote directory -await sftp.mkdir(sessionId, "/tmp/newdir"); -``` +> **Not available from plugin JavaScript.** The `sftp` global does not exist. Plugins with the `sftp.read` permission can list and read remote files from **panel HTML** through the [native panel messages](#6-api-native-panel-messages) `sftp-list` and `sftp-read`. Writing, deleting and creating remote files is not supported. --- @@ -302,15 +283,15 @@ await sftp.mkdir(sessionId, "/tmp/newdir"); > **Permission:** None — always available. Auto-namespaced by plugin id. ```js -// Save -await storage.set("mykey", "myvalue"); +// Save (values are stored as strings) +storage.set("mykey", "myvalue"); -// Load -const val = await storage.get("mykey"); +// Load: returns { value } or null when the key is missing +const val = storage.get("mykey"); if (val !== null) console.log(val.value); // Delete -await storage.delete("mykey"); +storage.delete("mykey"); ``` Keys are automatically namespaced as `plugin::::storage::` — no collision risk with other plugins. @@ -319,13 +300,14 @@ Keys are automatically namespaced as `plugin::::storage::` — no colli ### `ui` — User interface -#### `ui.notify(message, options)` — Desktop notification +#### `ui.notify(message, options)` — Notification > **Permission:** `ui.notify` ```js ui.notify("Upload complete!", { type: "info" }); // type: "info" | "warning" | "error" +// The app currently writes notifications to the plugin's Console. ``` #### `ui.statusbar.*` — Status bar items @@ -506,12 +488,12 @@ The app shows a consent dialog listing all requested permissions. The user appro | `terminal.intercept` | Cancel or modify user keystrokes before they reach SSH | | `session.observe` | Receive `session.connect` / `session.disconnect` events | | `session.control` | `session.connect.before` — can cancel a connection | -| `ssh.exec` | Call `ssh.exec()` to run commands on remote | +| `ssh.exec` | Run commands through the `ssh-exec` panel message; also allows `ssh.sessions()` | | `terminal.inject` | Send text directly into an active shell via `ssh.inject()` | -| `sftp.read` | `sftp.list()`, `sftp.read()` | -| `sftp.write` | `sftp.write()`, `sftp.delete()`, `sftp.mkdir()` | +| `sftp.read` | `sftp-list` / `sftp-read` panel messages | +| `sftp.write` | Reserved (no JS or panel API uses it yet) | | `command.intercept` | `command.before` / `command.after` hooks for SSH exec commands | -| `ui.notify` | Show desktop notifications | +| `ui.notify` | `ui.notify()` (shown in the plugin Console) | | `ui.statusbar` | Add items to the status bar | | `ui.clipboard` | Write to the system clipboard | | `ui.panel` | Register a sidebar panel with WebView UI | @@ -732,7 +714,7 @@ To re-enable: go to Plugin Manager and save the file (hot-reload resets the erro | Error | Cause | Fix | |-------|-------|-----| -| `Plugin "x" does not have permission: ssh.exec` | Missing permission in manifest | Add it to the `permissions` array | +| `Error: Permission denied: ui.panel not granted` | Missing permission in manifest | Add it to the `permissions` array | | `ManifestException: plugin.json missing required field: name` | Missing required field | Add the field to plugin.json | | `QuickJsException: SyntaxError` | JS syntax error | Fix index.js | | Plugin does not load | plugin.json cannot be parsed | Validate JSON at jsonlint.com | @@ -773,10 +755,11 @@ EOF | Limitation | Workaround | |-----------|------------| -| `ssh.exec()` does not work inside JS hook handlers (`session.connect`, `terminal.output`, etc.) — the JS runtime is synchronous | Use the **native panel message** `ssh-exec` from panel HTML instead | +| JS hook handlers (`session.connect`, `terminal.output`, etc.) are synchronous, so they cannot run SSH commands or await results | Use the **native panel message** `ssh-exec` from panel HTML instead | | `setInterval` / `setTimeout` are not available in the JS plugin context | Use `session.connect` hook to trigger logic; timer-based polling must run from panel HTML (the browser has native timers) | | `ui.addCommand` click handler is not invoked — commands appear in the palette but clicking them is a no-op | Known limitation — will be fixed in a future release | -| `sftp.write`, `sftp.delete`, `sftp.mkdir` in JS are not yet implemented | Use `ssh.inject(sessionId, "rm file\n")` to perform operations via the SSH shell | +| There is no `ssh.exec` or `sftp` global in plugin JS | Use the native panel messages `ssh-exec`, `sftp-list`, `sftp-read` from panel HTML, or `ssh.inject(sessionId, "rm file\n")` to run a command in the user's shell | +| `ui.notify` messages go to the plugin Console, not an on-screen toast | Use `ui.statusbar` for visible status | | Plugin panel WebView loads from `file://` — some browser security policies may block `fetch()` | Use native panel messages (`ssh-exec`, `sftp-read`) instead of `fetch()` in panel HTML | | Plugins cannot share state with each other | Use `storage.set/get` with a shared key prefix (there is no read-isolation between plugins) | diff --git a/packages/yourssh_script_engine/build/native_assets/macos/native_assets.json b/packages/yourssh_script_engine/build/native_assets/macos/native_assets.json deleted file mode 100644 index 7ff92ede..00000000 --- a/packages/yourssh_script_engine/build/native_assets/macos/native_assets.json +++ /dev/null @@ -1 +0,0 @@ -{"format-version":[1,0,0],"native-assets":{"macos_arm64":{"package:objective_c/objective_c.dylib":["absolute","/Users/thangnguyen/Documents/Personal/yourssh/packages/yourssh_script_engine/build/native_assets/macos/objective_c.dylib"]}}} \ No newline at end of file diff --git a/packages/yourssh_script_engine/build/native_assets/macos/objective_c.dylib b/packages/yourssh_script_engine/build/native_assets/macos/objective_c.dylib deleted file mode 100755 index 6d4800e2..00000000 Binary files a/packages/yourssh_script_engine/build/native_assets/macos/objective_c.dylib and /dev/null differ diff --git a/packages/yourssh_script_engine/build/test_cache/build/e526d636a6238c5a01b25d33d78dd941.cache.dill.track.dill b/packages/yourssh_script_engine/build/test_cache/build/e526d636a6238c5a01b25d33d78dd941.cache.dill.track.dill deleted file mode 100644 index 0eec61c3..00000000 Binary files a/packages/yourssh_script_engine/build/test_cache/build/e526d636a6238c5a01b25d33d78dd941.cache.dill.track.dill and /dev/null differ diff --git a/packages/yourssh_script_engine/build/unit_test_assets/AssetManifest.bin b/packages/yourssh_script_engine/build/unit_test_assets/AssetManifest.bin deleted file mode 100644 index 86d111f0..00000000 Binary files a/packages/yourssh_script_engine/build/unit_test_assets/AssetManifest.bin and /dev/null differ diff --git a/packages/yourssh_script_engine/build/unit_test_assets/FontManifest.json b/packages/yourssh_script_engine/build/unit_test_assets/FontManifest.json deleted file mode 100644 index 0637a088..00000000 --- a/packages/yourssh_script_engine/build/unit_test_assets/FontManifest.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/packages/yourssh_script_engine/build/unit_test_assets/NOTICES.Z b/packages/yourssh_script_engine/build/unit_test_assets/NOTICES.Z deleted file mode 100644 index f9b7cf38..00000000 Binary files a/packages/yourssh_script_engine/build/unit_test_assets/NOTICES.Z and /dev/null differ diff --git a/packages/yourssh_script_engine/build/unit_test_assets/NativeAssetsManifest.json b/packages/yourssh_script_engine/build/unit_test_assets/NativeAssetsManifest.json deleted file mode 100644 index 7ff92ede..00000000 --- a/packages/yourssh_script_engine/build/unit_test_assets/NativeAssetsManifest.json +++ /dev/null @@ -1 +0,0 @@ -{"format-version":[1,0,0],"native-assets":{"macos_arm64":{"package:objective_c/objective_c.dylib":["absolute","/Users/thangnguyen/Documents/Personal/yourssh/packages/yourssh_script_engine/build/native_assets/macos/objective_c.dylib"]}}} \ No newline at end of file diff --git a/packages/yourssh_script_engine/build/unit_test_assets/shaders/ink_sparkle.frag b/packages/yourssh_script_engine/build/unit_test_assets/shaders/ink_sparkle.frag deleted file mode 100644 index ebd80664..00000000 Binary files a/packages/yourssh_script_engine/build/unit_test_assets/shaders/ink_sparkle.frag and /dev/null differ diff --git a/packages/yourssh_script_engine/build/unit_test_assets/shaders/stretch_effect.frag b/packages/yourssh_script_engine/build/unit_test_assets/shaders/stretch_effect.frag deleted file mode 100644 index 3c938de1..00000000 Binary files a/packages/yourssh_script_engine/build/unit_test_assets/shaders/stretch_effect.frag and /dev/null differ diff --git a/packages/yourssh_script_engine/lib/src/script_engine_service.dart b/packages/yourssh_script_engine/lib/src/script_engine_service.dart index 90683ac1..9361247a 100644 --- a/packages/yourssh_script_engine/lib/src/script_engine_service.dart +++ b/packages/yourssh_script_engine/lib/src/script_engine_service.dart @@ -72,6 +72,79 @@ var console = { }; '''; +// JS prelude evaluated after the host bridges are registered and before the +// plugin entry. Defines the documented friendly globals (`ui`, `ssh`, +// `storage`) as thin wrappers over the raw `_x` host functions. A wrapper only +// forwards to a host function the PermissionGuard-gated bridge registered; when +// it is missing the call throws "Permission denied: ", so no wrapper can +// reach a capability the plugin was not granted. Raw `_x` stays available. +const _kPrelude = r''' +(function(g) { + function host(obj, fn, perm) { + return function(arg) { + if (typeof obj === 'undefined' || typeof obj[fn] !== 'function') { + throw new Error('Permission denied: ' + perm + ' not granted'); + } + var r = obj[fn](JSON.stringify(arg === undefined ? null : arg)); + return typeof r === 'string' ? JSON.parse(r) : null; + }; + } + var _u = typeof _ui === 'undefined' ? undefined : _ui; + var _us = typeof _ui_statusbar === 'undefined' ? undefined : _ui_statusbar; + var _s = typeof _ssh === 'undefined' ? undefined : _ssh; + var _st = typeof _storage === 'undefined' ? undefined : _storage; + var notify = host(_u, 'notify', 'ui.notify'); + var register = host(_u, 'registerPanel', 'ui.panel'); + var copy = host(_u, 'copyToClipboard', 'ui.clipboard'); + var addCommand = host(_u, 'addCommand', 'ui.statusbar or ui.panel'); + var sbAdd = host(_us, 'add', 'ui.statusbar'); + var sbUpdate = host(_us, 'update', 'ui.statusbar'); + var sbRemove = host(_us, 'remove', 'ui.statusbar'); + var sessions = host(_s, 'sessions', 'session.observe'); + var inject = host(_s, 'inject', 'terminal.inject'); + var sGet = host(_st, 'get', 'storage'); + var sSet = host(_st, 'set', 'storage'); + var sDel = host(_st, 'delete', 'storage'); + g.ui = { + notify: function(message, options) { + notify({message: String(message), type: (options && options.type) || 'info'}); + }, + statusbar: { + add: function(id, o) { + o = o || {}; + sbAdd({id: id, label: o.label, tooltip: o.tooltip}); + }, + update: function(id, o) { + o = o || {}; + sbUpdate({id: id, label: o.label, tooltip: o.tooltip}); + }, + remove: function(id) { sbRemove({id: id}); } + }, + panel: { + register: function(c) { + register({title: c.title, icon: c.icon, webviewEntry: c.webviewEntry}); + if (typeof c.onMessage === 'function') plugin._setPanelMessage(c.onMessage); + } + }, + clipboard: { copy: function(text) { copy({text: String(text)}); } }, + addCommand: function(c) { + addCommand({id: c.id, label: c.label, keybinding: c.keybinding}); + } + }; + g.ssh = { + sessions: function() { return sessions(null) || []; }, + inject: function(sessionId, text) { + inject({sessionId: sessionId, text: String(text)}); + } + }; + g.storage = { + get: function(key) { return sGet({key: key}); }, + set: function(key, value) { sSet({key: key, value: String(value)}); }, + delete: function(key) { sDel({key: key}); } + }; +})(this); +'''; + class _LoadedPlugin { final String id; final PluginManifest manifest; @@ -93,6 +166,10 @@ class ScriptEngineService { final SftpBridgeDelegate? sftpDelegate; final void Function(String pluginId, String level, String message)? onLog; + /// Receives `ui.notify(message, {type})` calls from plugins holding the + /// `ui.notify` permission. `type` is `info`, `warning` or `error`. + final void Function(String pluginId, String message, String type)? onNotify; + VoidCallback? onChange; List get loadedManifests => @@ -112,6 +189,7 @@ class ScriptEngineService { required this.sshDelegate, required this.sftpDelegate, this.onLog, + this.onNotify, }); Future loadPlugin( @@ -148,7 +226,9 @@ class ScriptEngineService { } if (sftpDelegate != null) SftpBridge(guard, sftpDelegate!).register(rt); if (uiRegistry != null) { - UiBridge(manifest.id, guard, uiRegistry!, null, (msg) async { + UiBridge(manifest.id, guard, uiRegistry!, + onNotify == null ? null : (m, t) => onNotify!(manifest.id, m, t), + (msg) async { final type = msg['type'] as String? ?? ''; // Native operations bypass the JS bridges, so they must enforce the @@ -232,6 +312,9 @@ class ScriptEngineService { }).register(rt); } + // Documented friendly globals (ui / ssh / storage) over the raw bridges. + rt.eval(_kPrelude, filename: '', timeout: kLoadTimeout); + // Execute plugin entry point final src = await entryFile.readAsString(); rt.eval(src, filename: manifest.entry, timeout: kLoadTimeout); diff --git a/packages/yourssh_script_engine/test/plugin_api_prelude_test.dart b/packages/yourssh_script_engine/test/plugin_api_prelude_test.dart new file mode 100644 index 00000000..7d06debf --- /dev/null +++ b/packages/yourssh_script_engine/test/plugin_api_prelude_test.dart @@ -0,0 +1,141 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:yourssh_script_engine/src/bridge/ssh_bridge.dart'; +import 'package:yourssh_script_engine/src/bridge/storage_bridge.dart'; +import 'package:yourssh_script_engine/src/hook_bus.dart'; +import 'package:yourssh_script_engine/src/plugin_ui_registry.dart'; +import 'package:yourssh_script_engine/src/script_engine_service.dart'; + +class _FakeSsh implements SshBridgeDelegate { + final inputs = []; + @override + List> activeSessions() => [ + {'sessionId': 's1', 'host': 'h', 'username': 'u', 'port': 22, 'connected': true} + ]; + @override + Future> execCommand(String s, String c) async => + {'stdout': '', 'stderr': '', 'exitCode': 0}; + @override + void sendInput(String sessionId, String text) => inputs.add('$sessionId:$text'); +} + +void main() { + late Directory tmp; + late PluginUiRegistry registry; + late _FakeSsh ssh; + late List notes; + late List logs; + late ScriptEngineService svc; + + setUp(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + SharedPreferences.setMockInitialValues({}); + await StorageBridge.warmup(); + tmp = Directory.systemTemp.createTempSync('plugin_prelude_'); + registry = PluginUiRegistry(); + ssh = _FakeSsh(); + notes = []; + logs = []; + svc = ScriptEngineService( + hookBus: HookBus(), + uiRegistry: registry, + sshDelegate: ssh, + sftpDelegate: null, + onLog: (id, level, msg) => logs.add('$level:$msg'), + onNotify: (id, msg, type) => notes.add('$type:$msg'), + ); + }); + + tearDown(() { + svc.dispose(); + tmp.deleteSync(recursive: true); + }); + + Future load(String js, Set perms) async { + final dir = Directory('${tmp.path}/p')..createSync(); + File('${dir.path}/plugin.json').writeAsStringSync(json.encode({ + 'id': 'test.prelude', + 'name': 'P', + 'version': '1.0.0', + 'entry': 'index.js', + 'minAppVersion': '1.0.0', + 'permissions': perms.toList(), + })); + File('${dir.path}/index.js').writeAsStringSync(js); + await svc.loadPlugin(dir.path, grantedPermissions: perms); + } + + test('ui.panel.register registers a panel and routes onMessage', () async { + await load(''' +ui.panel.register({title: "T", icon: "note", webviewEntry: "panel/index.html", + onMessage: function(m) { return {type: "echo", got: m.type}; }}); +''', {'ui.panel'}); + expect(registry.panels.single.title, 'T'); + final r = await registry.panels.single.onMessage({'type': 'ping'}); + expect(json.decode(r!)['got'], 'ping'); + }); + + test('storage.set/get/delete round trip', () async { + await load(''' +storage.set("k", "v"); +var a = storage.get("k"); +console.log("a=" + (a && a.value)); +storage.delete("k"); +console.log("b=" + storage.get("k")); +''', {}); + expect(logs, ['log:a=v', 'log:b=null']); + }); + + test('ui.notify reaches the host callback', () async { + await load('ui.notify("hi", {type: "warning"}); ui.notify("yo");', + {'ui.notify'}); + expect(notes, ['warning:hi', 'info:yo']); + }); + + test('ui.statusbar add/update/remove, clipboard and addCommand', () async { + await load(''' +ui.statusbar.add("a", {label: "L", tooltip: "t"}); +ui.statusbar.update("a", {label: "L2"}); +ui.statusbar.add("b", {label: "B"}); +ui.statusbar.remove("b"); +ui.addCommand({id: "c", label: "Cmd"}); +''', {'ui.statusbar'}); + expect(registry.statusBarItems.map((i) => i.label), ['L2']); + expect(registry.commands.single.label, 'Cmd'); + }); + + test('ssh.sessions and ssh.inject use the delegate', () async { + await load(''' +var s = ssh.sessions(); +console.log("n=" + s.length + " " + s[0].sessionId); +ssh.inject("s1", "ls\\n"); +''', {'session.observe', 'terminal.inject'}); + expect(logs, ['log:n=1 s1']); + expect(ssh.inputs, ['s1:ls\n']); + }); + + test('wrappers do not bypass permissions', () async { + await load(''' +try { ui.panel.register({title: "x", webviewEntry: "p"}); console.log("allowed"); } +catch (e) { console.log("denied:" + e.message); } +try { ssh.inject("s1", "x"); console.log("allowed"); } +catch (e) { console.log("denied:" + e.message); } +''', {'ui.notify'}); + expect(logs.length, 2); + expect(logs.every((l) => l.startsWith('log:denied:')), isTrue); + expect(logs[0], contains('ui.panel')); + expect(logs[1], contains('terminal.inject')); + expect(registry.panels, isEmpty); + expect(ssh.inputs, isEmpty); + }); + + test('plugin using only raw _x API still loads', () async { + await load(''' +_ui.registerPanel(JSON.stringify({title: "Raw", icon: "x", webviewEntry: "p"})); +_storage.set(JSON.stringify({key: "k", value: "v"})); +''', {'ui.panel'}); + expect(registry.panels.single.title, 'Raw'); + }); +} diff --git a/tool/docs_journey.sh b/tool/docs_journey.sh index a5e24e4b..e811accf 100755 --- a/tool/docs_journey.sh +++ b/tool/docs_journey.sh @@ -1,22 +1,84 @@ #!/usr/bin/env bash # Builds and runs the docs screenshot journey with FULL isolation. -# tool/docs_journey.sh [build|run|all] (default: all) +# tool/docs_journey.sh [setup|build|run|all|teardown] (default: all) +# setup generate a client key, build the demo image, create the network and 5 demo containers (idempotent) +# build build the integration-test macOS app +# run launch the app against the demo containers, capture PNGs +# all build + run (containers must already exist: run `setup` first) +# teardown stop + remove only the containers/network/image created by `setup` # The integration-test app is built once with the real HOME (flutter tool needs # it), then the built binary is launched directly with HOME=. -# Env: SECTIONS="01,02,..." limits the sections; DOCS_OUT overrides the output dir. +# Env: SECTIONS="01,02,..." limits sections; MODES="desktop mobile" picks launches; +# DOCS_OUT overrides the output dir; DOCS_KEY_DIR holds the generated client key +# (default ~/.local/state/yourssh-docs-journey, never inside the repo). +# DOCS_PREFIX (default yourssh-docs) names containers/network/image; +# SSH_PORT/BASTION_PORT/RDP_PORT/VNC_PORT override host ports. The app harness +# expects the defaults 2222/2223/3389/5900, so override them only to test setup. set -euo pipefail -export PATH="$HOME/development/flutter/bin:$PATH" +command -v flutter >/dev/null 2>&1 || export PATH="$HOME/development/flutter/bin:$PATH" ROOT="$(cd "$(dirname "$0")/.." && pwd)" MODE="${1:-all}" OUT="${DOCS_OUT:-$ROOT/screenshots/docs}" +PREFIX="${DOCS_PREFIX:-yourssh-docs}" +SSH_PORT="${SSH_PORT:-2222}"; BASTION_PORT="${BASTION_PORT:-2223}" +RDP_PORT="${RDP_PORT:-3389}"; VNC_PORT="${VNC_PORT:-5900}" +KEY_DIR="${DOCS_KEY_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/yourssh-docs-journey}" +KEY="$KEY_DIR/client_ed25519" +NET="$PREFIX-net"; IMAGE="$PREFIX-ssh:latest" +CONTAINERS=("$PREFIX-ssh" "$PREFIX-bastion" "$PREFIX-db" "$PREFIX-rdp" "$PREFIX-vnc") + +is_running() { [[ "$(docker container inspect -f '{{.State.Running}}' "$1" 2>/dev/null)" == true ]]; } +exists() { docker container inspect "$1" >/dev/null 2>&1; } +ensure() { # name, then `docker run` args: reuse a running one, start a stopped one, else create + local n="$1"; shift + if is_running "$n"; then echo "reuse running $n" + elif exists "$n"; then echo "start $n"; docker start "$n" >/dev/null + else echo "create $n"; docker run -d --name "$n" "$@" >/dev/null; fi +} + +setup() { + mkdir -p "$KEY_DIR"; chmod 700 "$KEY_DIR" + [[ -f "$KEY" ]] || ssh-keygen -q -t ed25519 -N '' -C yourssh-docs-demo -f "$KEY" + docker build -q -t "$IMAGE" "$ROOT/tool/docs_journey" >/dev/null + docker network inspect "$NET" >/dev/null 2>&1 || docker network create "$NET" >/dev/null + ensure "$PREFIX-ssh" --network "$NET" --network-alias yourssh-demo --hostname yourssh-demo -p "127.0.0.1:$SSH_PORT:22" "$IMAGE" + ensure "$PREFIX-bastion" --network "$NET" --network-alias bastion --hostname bastion -p "127.0.0.1:$BASTION_PORT:22" "$IMAGE" + ensure "$PREFIX-db" --network "$NET" --network-alias db-internal --hostname db-internal "$IMAGE" + local c + for c in ssh bastion db; do # install the client public key (idempotent overwrite) + docker exec -i "$PREFIX-$c" sh -c 'cat > /home/demo/.ssh/authorized_keys && chown demo:demo /home/demo/.ssh/authorized_keys && chmod 600 /home/demo/.ssh/authorized_keys' < "$KEY.pub" + done + ensure "$PREFIX-rdp" --hostname win-demo -p "127.0.0.1:$RDP_PORT:3389" scottyhardy/docker-remote-desktop:latest + ensure "$PREFIX-vnc" -e VNC_PW=demo12345 -p "127.0.0.1:$VNC_PORT:5900" dorowu/ubuntu-desktop-lxde-vnc:latest + # RDP login demo / demo12345 (idempotent) + for _ in $(seq 1 20); do docker exec "$PREFIX-rdp" true 2>/dev/null && break; sleep 1; done + docker exec "$PREFIX-rdp" bash -c "id demo >/dev/null 2>&1 || useradd -m -s /bin/bash demo; echo 'demo:demo12345' | chpasswd" + echo "setup done. client key: $KEY (host ports ssh=$SSH_PORT bastion=$BASTION_PORT rdp=$RDP_PORT vnc=$VNC_PORT)" +} + +teardown() { + local c + for c in "${CONTAINERS[@]}"; do exists "$c" && { docker rm -f "$c" >/dev/null; echo "removed $c"; }; done + docker network inspect "$NET" >/dev/null 2>&1 && { docker network rm "$NET" >/dev/null; echo "removed network $NET"; } + docker image inspect "$IMAGE" >/dev/null 2>&1 && { docker rmi "$IMAGE" >/dev/null; echo "removed image $IMAGE"; } + echo "teardown done (client key in $KEY_DIR kept; delete it manually if unwanted)" +} + +case "$MODE" in + setup) setup; exit 0 ;; + teardown) teardown; exit 0 ;; + build|run|all) ;; + *) echo "usage: $0 [setup|build|run|all|teardown]" >&2; exit 2 ;; +esac RUN_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/yourssh-docs-run.XXXXXX")" DEMO_HOME="$RUN_ROOT/yourssh-docs-home" -KEY="${DEMO_KEY:-/private/tmp/claude-501/-Users-thangnm-Documents-Personal/249a95bd-233f-499c-b54b-eb14f3c0d9dd/scratchpad/journey/sshd/client_ed25519}" if [[ "$MODE" == build || "$MODE" == all ]]; then (cd "$ROOT/app" && flutter build macos --debug -t integration_test/docs_journey_test.dart) fi [[ "$MODE" == build ]] && exit 0 +[[ -f "$KEY" ]] || { echo "no client key at $KEY: run '$0 setup' first" >&2; exit 1; } +for c in "${CONTAINERS[@]}"; do is_running "$c" || { echo "$c is not running: run '$0 setup' first" >&2; exit 1; }; done APP="$ROOT/app/build/macos/Build/Products/Debug/yourssh.app/Contents/MacOS/yourssh" [[ -x "$APP" ]] || APP="$(ls "$ROOT"/app/build/macos/Build/Products/Debug/*.app/Contents/MacOS/* | head -1)" diff --git a/tool/docs_journey/Dockerfile b/tool/docs_journey/Dockerfile new file mode 100644 index 00000000..99e7a736 --- /dev/null +++ b/tool/docs_journey/Dockerfile @@ -0,0 +1,19 @@ +# Demo SSH server image for the docs screenshot journey (see tool/docs_journey.sh). +# No secrets baked in: the client public key is installed at `setup` time. +# The demo/demo1234 password is a throwaway for a loopback-only demo container. +FROM alpine:latest +RUN apk add --no-cache openssh bash python3 py3-aiosmtpd htop git curl less vim tmux ncurses \ + && ssh-keygen -A \ + && adduser -D -s /bin/bash demo && echo 'demo:demo1234' | chpasswd \ + && mkdir -p /home/demo/.ssh /home/demo/projects/webapp/src /home/demo/logs /home/demo/backups \ + && printf 'server {\n listen 80;\n server_name demo.local;\n}\n' > /home/demo/projects/webapp/nginx.conf \ + && printf '# Web app\n\nDemo project used in the YourSSH docs.\n' > /home/demo/projects/webapp/README.md \ + && printf 'console.log("hello from yourssh-demo");\n' > /home/demo/projects/webapp/src/index.js \ + && for i in 1 2 3; do echo "2026-11-1$i 10:0$i:00 INFO request served in ${i}2ms" >> /home/demo/logs/app.log; done \ + && head -c 2097152 /dev/urandom > /home/demo/backups/db-2026-11-12.sql.gz \ + && printf 'export PS1="\\[\\e[1;32m\\]\\u@\\h\\[\\e[0m\\]:\\[\\e[1;34m\\]\\w\\[\\e[0m\\]\\$ "\nalias ll="ls -la"\n' > /home/demo/.bashrc \ + && printf '[ -f ~/.bashrc ] && . ~/.bashrc\n' > /home/demo/.bash_profile \ + && chown -R demo:demo /home/demo && chmod 700 /home/demo/.ssh \ + && sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/; s/^#\?AllowTcpForwarding.*/AllowTcpForwarding yes/; s/^#\?AllowAgentForwarding.*/AllowAgentForwarding yes/; s/^#\?GatewayPorts.*/GatewayPorts no/' /etc/ssh/sshd_config +EXPOSE 22 +CMD ["/usr/sbin/sshd","-D","-e"]