Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6a7d51ddd | ||
|
|
e59f0243ba | ||
|
|
5acb41158c | ||
|
|
1c590f47ff | ||
|
|
32890c6415 | ||
|
|
0fc9451583 | ||
|
|
1990fb5da9 | ||
|
|
469acb1203 | ||
|
|
f80fc876dd | ||
|
|
1fcb5fa575 | ||
|
|
58cb531e32 | ||
|
|
455d8fa6da | ||
|
|
ae2b07db4b | ||
|
|
2fa56e0723 | ||
|
|
b798422735 | ||
|
|
6476ccff28 | ||
|
|
4256d45633 | ||
|
|
fda804e3f5 | ||
|
|
aacd44a275 | ||
|
|
02bd237636 | ||
|
|
b149fb3b38 | ||
|
|
15612a629e |
@@ -26,7 +26,7 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libxkbcommon-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libwayland-dev libgtk-3-dev openssh-server
|
||||
sudo apt-get install -y libxkbcommon-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libwayland-dev libgtk-3-dev libasound2-dev openssh-server
|
||||
- run: cargo test --locked --workspace
|
||||
- run: cargo fmt --all --check
|
||||
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
name: Fuzz
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 3 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
fuzz:
|
||||
name: Fuzz (${{ matrix.target }})
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
target: [telnet, irc, vnc, sshconfig, updater]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: rust/fuzz
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||
- run: sudo apt-get update && sudo apt-get install -y libasound2-dev
|
||||
- run: rustup toolchain install nightly --profile minimal
|
||||
- run: cargo +nightly install cargo-fuzz --locked
|
||||
- run: cargo +nightly fuzz run ${{ matrix.target }} -- -max_total_time=120 -rss_limit_mb=2048
|
||||
- name: Upload crashing inputs
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
with:
|
||||
name: fuzz-${{ matrix.target }}
|
||||
path: rust/fuzz/artifacts
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libxkbcommon-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libwayland-dev libgtk-3-dev zip
|
||||
sudo apt-get install -y libxkbcommon-dev libgl1-mesa-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libwayland-dev libgtk-3-dev libasound2-dev zip
|
||||
|
||||
- name: Test
|
||||
run: cargo test --locked --workspace
|
||||
|
||||
@@ -17,7 +17,7 @@ The toolchain is pinned in `rust/rust-toolchain.toml`; `rustup` installs it on f
|
||||
|
||||
```bash
|
||||
sudo apt-get install -y build-essential pkg-config libxkbcommon-dev libgl1-mesa-dev \
|
||||
libx11-dev libxcursor-dev libxrandr-dev libxi-dev libwayland-dev libgtk-3-dev zip
|
||||
libx11-dev libxcursor-dev libxrandr-dev libxi-dev libwayland-dev libgtk-3-dev libasound2-dev zip
|
||||
```
|
||||
|
||||
- **macOS:** Xcode command-line tools (`xcode-select --install`).
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
\shortcut{Next / previous match}{\kbd{Enter} / \keys{Shift+Enter}}
|
||||
\shortcut{Scroll a page}{\keys{Shift+PageUp}}
|
||||
\shortcut{Top / bottom}{\keys{Shift+Home} / \kbd{End}}
|
||||
\shortcut{Previous / next prompt}{\keys{\mod+Shift+Up} / \kbd{Down}}
|
||||
\shortcut{Open link}{\kbd{Ctrl}/\kbd{\ph{E1C4}} + click}}
|
||||
|
||||
\sheet{pink}{\iMap\enspace Mouse moves}{%
|
||||
@@ -63,8 +64,11 @@
|
||||
--data-dir DIR & Use another data folder (portable installs, demos, testing).\\
|
||||
--theme pro|midnight|light & Start with this theme.\\
|
||||
--connect NAME & Connect to a saved profile by name at startup. Repeat it for several.\\
|
||||
--open WINDOW & Open a window at startup: \code{settings}, \code{settings:security}, \code{snippets},
|
||||
\code{keys}, \code{recordings}, \code{palette}, \code{quick}…\\
|
||||
--open WINDOW & Open a window at startup: \code{settings}, \code{settings:security},
|
||||
\code{settings:diagnostics}, \code{snippets}, \code{keys}, \code{recordings}, \code{palette},
|
||||
\code{quick}…\\
|
||||
--run-local CMD & Open a local shell and run a command in it.\\
|
||||
RUST\_LOG=debug & (environment) More detail in \code{nexus.log}, and on the terminal you started from.\\
|
||||
--version & Print the version and exit.\\
|
||||
\bottomrule
|
||||
\end{tabularx}
|
||||
@@ -87,13 +91,18 @@ rerun the script, rebuild the guide.
|
||||
\item[Bastion / jump host] A server you go \emph{through} to reach the ones behind it.
|
||||
\item[Baud rate] How fast a serial line talks. Both ends must agree.
|
||||
\item[Broadcast] Typing into several sessions at once.
|
||||
\item[Certificate authority] A key that vouches for other keys, so servers signed by it are trusted without a prompt.
|
||||
\item[DTR / RTS] Serial control lines. Some boards use them for reset or flashing.
|
||||
\item[Fingerprint] A short summary of a server's host key, used to spot imposters.
|
||||
\item[Host key] A server's identity. Changes when it's rebuilt, or when someone's pretending.
|
||||
\item[Keychain] Your operating system's password store.
|
||||
\item[NLA] Network Level Authentication: Windows checks your password before building a desktop.
|
||||
\item[OSC 133] The escape codes a shell uses to mark its prompts, which powers shell integration.
|
||||
\item[Port forward] A tunnel carrying one TCP port through SSH.
|
||||
\item[Profile] A saved connection.
|
||||
\item[RAW TCP] A plain socket: bytes in, bytes out, no terminal rules.
|
||||
\item[RDP] Microsoft's Remote Desktop Protocol, for Windows (and xrdp) desktops.
|
||||
\item[SASL] How IRC networks log you in while you connect, instead of messaging NickServ afterwards.
|
||||
\item[SFTP] File transfer over SSH.
|
||||
\item[Snippet] A saved command, optionally with blanks to fill in.
|
||||
\item[TOTP] Time-based one-time passwords: the six digits from your authenticator app.
|
||||
|
||||
@@ -40,10 +40,9 @@ The first time you open Nexus Terminal you get a calm, empty welcome screen. Thr
|
||||
|
||||
\shot{welcome.png}{The welcome screen. Your saved connections will live down the left; here there are a few already.}
|
||||
|
||||
\begin{headsup}[Coming from Alchementary Link?]
|
||||
Nexus Terminal spots your old data on first run and copies your profiles, vault and recordings across
|
||||
automatically. You'll see a little toast saying so. Your old data is left exactly where it was.
|
||||
The details are in \hyperref[ch:move]{Moving house} on p.\,\pageref{ch:move}.
|
||||
\begin{headsup}[Got more than one computer?]
|
||||
Point \ui{Profile sync} at a shared folder and your connections follow you around. See
|
||||
\hyperref[ch:move]{Moving house} on p.\,\pageref{ch:move}.
|
||||
\end{headsup}
|
||||
|
||||
\section{Make your first connection}
|
||||
@@ -51,7 +50,7 @@ The details are in \hyperref[ch:move]{Moving house} on p.\,\pageref{ch:move}.
|
||||
\begin{enumerate}
|
||||
\item Click \ui{New Connection}, or press \keys{\mod+N}.
|
||||
\item Pick the protocol along the top: \proto[teal]{SSH}, \proto[amber]{Telnet}, \proto[violet]{RAW TCP},
|
||||
\proto[slate]{GitHub}, \proto[rose]{VNC}, \proto[amber]{IRC} or \proto[accent]{Serial}.
|
||||
\proto[slate]{GitHub}, \proto[rose]{VNC}, \proto[rose]{RDP}, \proto[amber]{IRC} or \proto[accent]{Serial}.
|
||||
\item Fill in the \ui{General} bit: a \ui{Display Name} you'll recognise, the \ui{Host}, the \ui{Port}
|
||||
and your \ui{Username}.
|
||||
\item Click \ui{Create \& Connect}.
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
\guidepart{teal}{Connect}{Connect to all the things}
|
||||
{Eight ways in. Pick the one you need; skip the rest.}
|
||||
{Nine ways in. Pick the one you need; skip the rest.}
|
||||
{\partitem{\iTerminal}{SSH: the big one}
|
||||
\partitem{\iUsb}{Serial: cables and consoles}
|
||||
\partitem{\iPlug}{Telnet and RAW TCP}
|
||||
\partitem{\iDesktop}{VNC remote desktops}
|
||||
\partitem{\iDesktop}{RDP: Windows desktops}
|
||||
\partitem{\iChat}{IRC}
|
||||
\partitem{\iGithub}{GitHub}}
|
||||
|
||||
@@ -47,6 +48,10 @@ Under \ui{Authentication}, tick which \ui{Auth Methods} to try: \ui{Public key},
|
||||
\ui{Keyboard-interactive}. Under \ui{SSH Agent}, tick \ui{Use SSH Agent for Authentication} to use keys already
|
||||
loaded into \code{ssh-agent} (or Pageant, or the Windows OpenSSH agent).
|
||||
|
||||
Got an SSH \emph{user certificate}? Put it next to the key with the usual name (\code{id\_ed25519-cert.pub} beside
|
||||
\code{id\_ed25519}) and Nexus Terminal presents it automatically. Servers that hand out \emph{host} certificates are
|
||||
covered in \hyperref[ch:hostkeys]{Host keys} (p.\,\pageref{ch:hostkeys}).
|
||||
|
||||
Every password and passphrase has a \emph{mode}: save it securely, remember it until you quit, or ask every time.
|
||||
That's all explained in \hyperref[ch:secrets]{Passwords \& the vault} (p.\,\pageref{ch:secrets}).
|
||||
|
||||
@@ -221,6 +226,60 @@ Turn on \ui{VNC viewers may control screen with password} in macOS Screen Sharin
|
||||
standard VNC password authentication, not Apple's own login method.
|
||||
\end{headsup}
|
||||
|
||||
% =========================================================================================
|
||||
\chapter{RDP: Windows desktops}\label{ch:rdp}
|
||||
\chapmeta{4 minutes}{You'll be on a Windows (or xrdp) desktop without leaving Nexus Terminal}
|
||||
|
||||
\begin{tldr}
|
||||
Host, username, password. Nexus Terminal logs on with NLA, pins the server's certificate like an SSH host key, and
|
||||
can go through a proxy, an SSH tunnel or an RD Gateway.
|
||||
\end{tldr}
|
||||
|
||||
\begin{glance}{rose}{RDP}
|
||||
Default port & 3389\\
|
||||
Logs in with & NLA (NTLM, or Kerberos with a KDC); \ui{Allow servers without NLA} for xrdp\\
|
||||
Display & \ui{Scale to Fit}, fixed size, \ui{Resize With Tab}\\
|
||||
Extras & Clipboard both ways, remote audio, printer, shared folder\\
|
||||
Getting there & SOCKS5 or HTTP proxy, SSH tunnel, RD Gateway (experimental)\\
|
||||
\end{glance}
|
||||
|
||||
\shot{rdp.png}{An xrdp desktop in a tab. Ctrl+Alt+Del and Paste Clipboard sit on the toolbar.}
|
||||
|
||||
\section{Setting it up}
|
||||
|
||||
\begin{enumerate}
|
||||
\item \keys{\mod+N}, protocol \proto[rose]{RDP}.
|
||||
\item \ui{Host} and \ui{Username}; add a \ui{Domain} if your account has one.
|
||||
\item Pick how the password is kept (save it, remember it until you quit, or ask every time).
|
||||
\item \ui{Create \& Connect}. The first time, you're shown the server's certificate fingerprint. Accept it if
|
||||
it's the machine you meant.
|
||||
\end{enumerate}
|
||||
|
||||
Windows checks your password \emph{before} it builds a desktop (Network Level Authentication), so a typo fails fast.
|
||||
Linux machines running xrdp don't speak NLA: tick \ui{Allow servers without NLA} for those. In an Active Directory
|
||||
shop, set a \ui{Kerberos KDC} (\code{host} or \code{host:port}) and use your realm as the domain.
|
||||
|
||||
\begin{headsup}[A changed certificate]
|
||||
RDP servers mostly use self-signed certificates, so Nexus Terminal remembers the fingerprint in
|
||||
\ui{Known Hosts}. If it changes you get \ui{Reject}, \ui{Accept Once} or \ui{Accept \& Update}, and nothing (not even your
|
||||
password) is sent until you choose.
|
||||
\end{headsup}
|
||||
|
||||
\section{While you're connected}
|
||||
|
||||
It works like the VNC viewer: click the desktop to give it your keyboard, \ui{Ctrl+Alt+Del} sends exactly that, and
|
||||
text you copy on either side turns up on the other. With \ui{Resize With Tab} the remote desktop follows the tab's
|
||||
size (Windows does this; other servers are scaled).
|
||||
|
||||
Under \ui{Devices}: \ui{Play Remote Audio}; \ui{Redirect Printer}, which adds a \emph{Nexus Terminal} printer whose jobs
|
||||
land as PostScript files in your Downloads folder; and (Linux and macOS) a \ui{Shared Folder} that shows up remotely as
|
||||
a drive called Nexus. The server can read and change that folder, and nothing outside it.
|
||||
|
||||
\section{Getting through}
|
||||
|
||||
Pick \emph{one} of: a \ui{Proxy} (SOCKS5 or HTTP CONNECT), an \ui{SSH Tunnel} (same as VNC), or an \ui{RD Gateway}
|
||||
(experimental: the gateway needs a proper public certificate and Basic authentication over HTTPS).
|
||||
|
||||
% =========================================================================================
|
||||
\chapter{IRC}\label{ch:irc}
|
||||
\chapmeta{3 minutes}{You'll be chatting in your project's channels from the same window as your servers}
|
||||
@@ -231,7 +290,8 @@ Nick, server, rooms to join. Tabs for each room, \code{/commands} as you'd expec
|
||||
|
||||
\begin{glance}{amber}{IRC}
|
||||
Default port & 6667, or 6697 with \ui{Use TLS} (use TLS!)\\
|
||||
Extras & NickServ identify on connect, auto-join rooms, room browser, SSH tunnel\\
|
||||
Logs in with & SASL PLAIN (most networks want this now), or NickServ identify\\
|
||||
Extras & Auto-join rooms, room browser, real message times (IRCv3 server-time), SSH tunnel\\
|
||||
\end{glance}
|
||||
|
||||
\shot{irc.png}{Chatting in \#nexus. Rooms down the right, users in the room below them.}
|
||||
|
||||
@@ -30,7 +30,9 @@ Right-click a tab for everything. \keys{\mod+Shift+D} splits right, \keys{\mod+S
|
||||
\item[Switch] \keys{\mod+Tab} and \keys{\mod+Shift+Tab}, or \keys{\mod+1} to \keys{\mod+9}.
|
||||
\end{description}
|
||||
|
||||
Lots of tabs? Scroll the tab strip with your mouse wheel or trackpad.
|
||||
Lots of tabs? Scroll the tab strip with your mouse wheel or trackpad. Quit with a dozen open and they're all back next
|
||||
time: \ui{Restore tabs at launch} (on by default) reconnects saved profiles and reopens local shells, splits and all,
|
||||
in the folder they were in.
|
||||
|
||||
\section{Split panes}
|
||||
|
||||
@@ -62,9 +64,10 @@ Select to copy, \keys{\mod+F} to search, Ctrl/\ph{E1C4}-click links. Right-click
|
||||
\toprule
|
||||
Copy & Select text, then \keys{\mod+C}. Nothing selected? \keys{Ctrl+C} interrupts the program as usual.\\
|
||||
Paste & \keys{\mod+V}. Pastes are bracketed when the program asks for it, so editors won't auto-indent your paste
|
||||
into a staircase.\\
|
||||
into a staircase. Pasting several lines into a shell asks first (turn that off in Settings).\\
|
||||
Select & Drag for a range, double-click a word, triple-click a line, \kbd{Shift}-click to extend.\\
|
||||
Links & Hold \kbd{Ctrl} (\kbd{\ph{E1C4}}) and click a URL to open it in your browser.\\
|
||||
Links & Hold \kbd{Ctrl} (\kbd{\ph{E1C4}}) and click a URL to open it in your browser. Real hyperlinks that
|
||||
programs print (\code{ls --hyperlink}, compilers) get a dotted underline; hover to see where they really go.\\
|
||||
Scroll & Mouse wheel, or \keys{Shift+PageUp}, \keys{Shift+PageDown}, \keys{Shift+Home}, \keys{Shift+End}.\\
|
||||
\bottomrule
|
||||
\end{tabularx}
|
||||
@@ -77,8 +80,34 @@ wheel sends arrow keys instead of scrolling. Programs with mouse support (\code{
|
||||
|
||||
\section{The right-click menu}
|
||||
|
||||
\ui{Copy}, \ui{Paste}, \ui{Select All}, \ui{Find}, \ui{Send Snippet}, \ui{Port Forwards} (SSH), \ui{Split Right},
|
||||
\ui{Split Down}, \ui{Export Output} (saves the whole scrollback as a text file), \ui{Clear} and \ui{Reset}.
|
||||
\ui{Copy}, \ui{Paste}, \ui{Select All}, \ui{Find}, \ui{Previous Prompt} / \ui{Next Prompt}, \ui{Copy Last Command
|
||||
Output}, \ui{Send Snippet}, \ui{Port Forwards} (SSH), \ui{Split Right}, \ui{Split Down}, \ui{Export Output} (saves the
|
||||
whole scrollback as a text file), \ui{Clear} and \ui{Reset}.
|
||||
|
||||
\section{Shell integration}
|
||||
|
||||
If your shell marks its prompts (fish 4, Starship and Powerlevel10k do already), Nexus Terminal knows where every
|
||||
command starts and stops. \keys{\mod+Shift+Up} and \keys{\mod+Shift+Down} jump from prompt to prompt,
|
||||
\ui{Copy Last Command Output} grabs just what the last command printed, and a thin bar beside each prompt shows how it
|
||||
went: green for success, red for failure. Hover the bar for the exit code and how long it took.
|
||||
|
||||
\shot{shell-integration.png}{\code{make test} failed (red bar), \code{ls} worked (green bar).}
|
||||
|
||||
For bash, add this to \code{\textasciitilde/.bashrc} on the machine the shell runs on (the user manual has the zsh
|
||||
version):
|
||||
|
||||
\begin{verbatim}
|
||||
PS0='\[\e]133;C\a\]'
|
||||
PROMPT_COMMAND='printf "\033]133;D;%s\007" "$?"; '"${PROMPT_COMMAND}"
|
||||
PS1='\[\e]133;A\a\]'"$PS1"'\[\e]133;B\a\]'
|
||||
\end{verbatim}
|
||||
|
||||
\section{Pictures in the terminal}
|
||||
|
||||
Programs that print images the iTerm2 way (\code{imgcat}, \code{wezterm imgcat}, \code{chafa -f iterm}) show PNG,
|
||||
JPEG and GIF images right in the scrollback. They scroll with the text and never spill past the edge.
|
||||
|
||||
\shot{inline-image.png}{An image printed by a script, with the text carrying on underneath.}
|
||||
|
||||
\section{Find}
|
||||
|
||||
@@ -168,7 +197,8 @@ Click the \iFolder{} on an SSH tab. Or drop a file onto the terminal and choose
|
||||
\section{The SFTP browser}
|
||||
|
||||
Click the \iFolder{} folder icon on an SSH tab, \menu{Session\then SFTP browser}, or type ``sftp'' in the palette.
|
||||
It opens in the side dock next to your terminal.
|
||||
It opens in the side dock next to your terminal, in the folder your shell is in if the shell reports it
|
||||
(fish does; bash and zsh need a one-line hook, see the user manual).
|
||||
|
||||
\shot{sftp.png}{Browsing the server's files next to the terminal.}
|
||||
|
||||
|
||||
@@ -72,6 +72,12 @@ Every password, passphrase, token or TOTP secret has its own setting:
|
||||
When Nexus Terminal needs a secret it doesn't have, it asks. Press \kbd{Esc} or \ui{Cancel} to give up on that
|
||||
connection.
|
||||
|
||||
\section{Seeing and changing what's saved}
|
||||
|
||||
\ui{Stored credentials} on the Security page lists every saved password, passphrase and token by profile, and whether
|
||||
it's in the keychain or the vault. \ui{Forget} deletes one. \ui{Change Master Password…} re-encrypts the whole vault
|
||||
under a new password in one go.
|
||||
|
||||
\begin{sidequest}[What gets written down?]
|
||||
Connections, disconnections, profile changes, credential access, imports and exports go into an audit log in the
|
||||
database. Secrets themselves never do. TOTP secrets live in the keychain or vault too, never in the profile.
|
||||
@@ -82,7 +88,7 @@ database. Secrets themselves never do. TOTP secrets live in the keychain or vaul
|
||||
\chapmeta{3 minutes}{You'll understand the scary fingerprint dialog and what to do about it}
|
||||
|
||||
\begin{tldr}
|
||||
Every SSH server has a fingerprint. Nexus Terminal remembers it the first time and shouts if it ever changes.
|
||||
Every SSH server (and every RDP server, via its certificate) has a fingerprint. Nexus Terminal remembers it the first time and shouts if it ever changes.
|
||||
A changed fingerprint means a reinstalled server, or someone in the middle. Find out which before carrying on.
|
||||
\end{tldr}
|
||||
|
||||
@@ -92,20 +98,30 @@ Pick a policy per SSH profile under \ui{Host Verification}:
|
||||
\begin{tabularx}{\linewidth}{@{}>{\leavevmode\heavy\color{ink}}p{48mm}X@{}}
|
||||
\toprule
|
||||
Strict (known hosts only) & Only connects to servers you've already trusted.\\
|
||||
Ask on new or changed keys & Shows the fingerprint and asks. \ui{Accept \& Save} or \ui{Reject}. The default.\\
|
||||
Ask on new or changed keys & Shows the fingerprint and asks. New: \ui{Accept \& Save} or \ui{Reject}. Changed:
|
||||
\ui{Reject}, \ui{Accept Once} or \ui{Accept \& Update}. The default.\\
|
||||
Accept new, reject changed & Trusts first-time servers silently, still refuses changed keys.\\
|
||||
Insecure (accept anything) & Exactly what it says. Lab use only.\\
|
||||
\bottomrule
|
||||
\end{tabularx}
|
||||
|
||||
Under every policy except \emph{Insecure}, a key that differs from the saved one is rejected.
|
||||
Under \emph{Strict} and \emph{Accept new}, a key that differs from the saved one is rejected outright.
|
||||
|
||||
\crop{settings-knownhosts.png}{581}{253}{576}{285}{0.8\linewidth}{Known hosts. Click a fingerprint to copy it; \ui{Remove} to forget a server.}
|
||||
|
||||
\begin{headsup}
|
||||
Nexus Terminal keeps its own list of known hosts. It doesn't read \code{\textasciitilde/.ssh/known\_hosts}, so the
|
||||
first connection to each server asks once, even if your command-line \code{ssh} already knows it.
|
||||
\end{headsup}
|
||||
\begin{quickwin}
|
||||
Nexus Terminal keeps its own list, but \ui{Import \textasciitilde/.ssh/known\_hosts} brings in everything your
|
||||
command-line \code{ssh} already trusts (hashed names can't be read back, so those are skipped). \ui{Export…} goes the
|
||||
other way, in OpenSSH format.
|
||||
\end{quickwin}
|
||||
|
||||
\section{Certificate authorities}
|
||||
|
||||
Big estates sign host keys with an SSH certificate authority instead of handing out fingerprints. \ui{Trust a CA…}
|
||||
adds the CA's public key for a host pattern in OpenSSH style (\code{*.corp.example}, \code{[jump.example]:2222},
|
||||
\code{!old.corp.example}); \code{@cert-authority} lines in an imported \code{known\_hosts} do the same. A server the CA
|
||||
covers must then show a certificate the CA signed, naming that host and in date. It's trusted without a prompt, and
|
||||
anything else is refused.
|
||||
|
||||
% =========================================================================================
|
||||
\chapter{SSH keys}\label{ch:keys}
|
||||
@@ -118,6 +134,6 @@ public key to the clipboard (ready to paste into GitHub or \code{authorized\_key
|
||||
\crop{keys.png}{725}{523}{725}{546}{0.75\linewidth}{The SSH key manager.}
|
||||
|
||||
\begin{protip}
|
||||
Not sure which type? Pick Ed25519. It's small, fast and secure. Key generation uses your system's
|
||||
\code{ssh-keygen}, which comes with macOS, Linux and Windows 10 and later.
|
||||
Not sure which type? Pick Ed25519. It's small, fast and secure. Keys are generated inside Nexus Terminal and
|
||||
saved in the usual OpenSSH format, so \code{ssh} and \code{git} can use them too.
|
||||
\end{protip}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
\guidepart{pink}{Make it yours}{Make it yours}
|
||||
{Settings, backups, and moving in from Alchementary Link.}
|
||||
{Settings, backups, and keeping several computers in step.}
|
||||
{\partitem{\iGear}{Settings}
|
||||
\partitem{\iUpload}{Import and export}
|
||||
\partitem{\iPlane}{Moving house}}
|
||||
@@ -14,18 +14,24 @@ then click \ui{Save}.
|
||||
\begin{center}\begin{minipage}[t]{0.49\linewidth}\crop{settings-general.png}{581}{253}{576}{285}{\linewidth}{General}\end{minipage}\hfill\begin{minipage}[t]{0.49\linewidth}\crop{settings-terminal.png}{581}{253}{576}{285}{\linewidth}{Terminal}\end{minipage}\end{center}
|
||||
|
||||
\begin{description}
|
||||
\item[General] App theme (Pro, Midnight, Light), default protocol for new profiles, whether to ask before closing or
|
||||
disconnecting, status bar on or off, sidebar width, and the local shell (leave it empty for the system default,
|
||||
or \ui{Browse…} for one).
|
||||
\item[General] App theme (Pro, Midnight, Light), default protocol for new profiles, \ui{Restore tabs at launch}
|
||||
(saved connections reconnect, local shells reopen in the folder they were in), whether to ask before closing or
|
||||
disconnecting, whether remote programs may write to your clipboard, a confirmation before pasting several lines,
|
||||
the update check, status bar, sidebar width, and the local shell (empty for the system default, or
|
||||
\ui{Browse…}).
|
||||
\item[Terminal] Colour scheme, font, size, scrollback and cursor style. These are the defaults for new profiles;
|
||||
each profile can override them.
|
||||
\item[Security] Keychain and vault status; set up, unlock or lock the vault.
|
||||
\item[Known Hosts] Saved server fingerprints, with first-seen and last-seen times.
|
||||
\item[Security] Keychain and vault status; set up, unlock or lock the vault; change the master password; your
|
||||
stored credentials; profile sync.
|
||||
\item[Known Hosts] Saved server fingerprints, with first-seen and last-seen times; import and export
|
||||
\code{known\_hosts}; trusted SSH certificate authorities.
|
||||
\item[Diagnostics] Version, platform, where your data and log live, and the state of the keychain, vault and sync.
|
||||
\ui{Copy Diagnostics} for bug reports (never includes credentials).
|
||||
\item[Help] Built-in help: connection types, shortcuts and troubleshooting, when this guide isn't to hand.
|
||||
\item[About] Version, \ui{Check for Updates} and \ui{Import \textasciitilde/.ssh/config}.
|
||||
\end{description}
|
||||
|
||||
\crop{settings-help.png}{581}{253}{576}{285}{0.8\linewidth}{The built-in help, for when this guide isn't to hand.}
|
||||
\crop{settings-diagnostics.png}{604}{600}{604}{20}{0.8\linewidth}{Diagnostics: everything a bug report needs, nothing secret.}
|
||||
|
||||
\section{Updates}
|
||||
|
||||
@@ -44,48 +50,57 @@ reads it back. Already have an \code{\textasciitilde/.ssh/config}? Import that t
|
||||
\begin{description}
|
||||
\item[Encrypted export] Choose the profiles, set a password, save a \code{.nexus} file. Saved passwords aren't
|
||||
included, so the file is safe to email to yourself.
|
||||
\item[Encrypted import] Pick a \code{.nexus} (or an old \code{.link}) file, enter its password and decide what happens to
|
||||
\item[Encrypted import] Pick a \code{.nexus} file, enter its password and decide what happens to
|
||||
profiles that already exist: \ui{Skip existing}, \ui{Overwrite existing} or \ui{Create duplicates}.
|
||||
\item[JSON] \ui{Export Profiles (JSON)} and \ui{Import Profiles (JSON)} are in the palette. Tick
|
||||
\ui{Include secrets} to keep proxy passwords and TOTP secrets, which are otherwise left out.
|
||||
\ui{Include secrets} to keep passwords typed by login scripts, which are otherwise blanked. Proxy passwords and
|
||||
TOTP secrets live in the keychain or vault, so no export carries them.
|
||||
\item[OpenSSH config] \menu{File\then Import \textasciitilde/.ssh/config} turns your \code{Host} blocks into profiles,
|
||||
with host names, users, ports, identity files and jump hosts.
|
||||
\end{description}
|
||||
|
||||
\crop{export.png}{894}{357}{872}{380}{0.55\linewidth}{Exporting profiles. Everything's ticked to start with; untick what you don't want.}
|
||||
\crop{export.png}{906}{388}{904}{390}{0.55\linewidth}{Exporting profiles. Everything's ticked to start with; untick what you don't want.}
|
||||
|
||||
\begin{danger}[JSON with secrets is not encrypted]
|
||||
A JSON export with \ui{Include secrets} ticked has those secrets in plain text. Use the encrypted \code{.nexus} export to
|
||||
A JSON export with \ui{Include secrets} ticked has those login-script passwords in plain text. Use the encrypted \code{.nexus} export to
|
||||
move things between machines.
|
||||
\end{danger}
|
||||
|
||||
% =========================================================================================
|
||||
\chapter{Moving house}\label{ch:move}
|
||||
\chapmeta{2 minutes}{You'll know what came over from Alchementary Link and what didn't}
|
||||
\chapmeta{3 minutes}{Your connections will follow you from laptop to desktop to work machine}
|
||||
|
||||
\begin{tldr}
|
||||
It's automatic. First run copies your Alchementary Link profiles, vault and recordings. Your old folder is left
|
||||
alone. Recreate trigger rules and SFTP bookmarks by hand.
|
||||
Pick a folder every machine can see, set the same sync password on each, done. Profiles stay in step; passwords
|
||||
stay put on each machine.
|
||||
\end{tldr}
|
||||
|
||||
When Nexus Terminal starts for the first time and finds an \code{AlchementaryLink} folder next to where its own data
|
||||
goes, it \emph{copies} \code{link.db} to \code{nexus.db}, along with the \code{vault/} and \code{recordings/} folders,
|
||||
and shows a toast saying where they came from.
|
||||
\section{Profile sync}
|
||||
|
||||
\menu{Settings\then Security\then Profile sync}. \ui{Choose…} a folder your machines share (Dropbox, iCloud Drive,
|
||||
OneDrive, Nextcloud, a network share, or a git checkout you commit) and set the same \ui{Sync password} everywhere.
|
||||
Nexus Terminal keeps one encrypted file there, \code{nexus-profiles.nexus}, and merges it at launch, a few seconds
|
||||
after you change a profile, every ten minutes and whenever you click \ui{Sync Now}.
|
||||
|
||||
\begin{checklist}
|
||||
\item[\color{green}\iCheck] Profiles, groups, favourites, known hosts, snippets and preferences
|
||||
\item[\color{green}\iCheck] Vault (same master password as before)
|
||||
\item[\color{green}\iCheck] Recordings
|
||||
\item[\color{green}\iCheck] Keychain passwords: picked up the first time each one is needed, then copied across
|
||||
\item[\color{green}\iCheck] Old \code{.link} export files still import
|
||||
\item[\color{rose}\ph{E4F6}] Trigger rules and SFTP bookmarks (they lived in the old app's web storage)
|
||||
\item[\color{green}\iCheck] Edited on two machines? The newer change wins, profile by profile.
|
||||
\item[\color{green}\iCheck] Deleted on one machine? It goes from the others too (unless someone edited it afterwards).
|
||||
\item[\color{rose}\ph{E4F6}] Passwords, keys and tokens never sync. Each machine keeps its own in its keychain or vault.
|
||||
\end{checklist}
|
||||
|
||||
\crop{settings-security.png}{581}{253}{576}{285}{0.8\linewidth}{Profile sync lives on the Security page, under your stored credentials.}
|
||||
|
||||
\begin{headsup}
|
||||
If a \code{NexusTerminal/nexus.db} already exists (say, from before the Alchementary Link rebrand), it's used as it is
|
||||
and nothing is copied.
|
||||
Lose the sync password and the sync file can't be read, just like an encrypted export. Your local profiles are
|
||||
fine.
|
||||
\end{headsup}
|
||||
|
||||
\section{One-off moves}
|
||||
|
||||
Not worth setting up sync? \menu{File\then Export profiles…} on the old machine, \menu{File\then Import profiles…}
|
||||
on the new one (see \hyperref[ch:transfer]{Import and export}). Known hosts travel the same way through
|
||||
\ui{Export…} and \ui{Import} on the Known Hosts page.
|
||||
|
||||
\section{Where everything lives}
|
||||
|
||||
\renewcommand\arraystretch{1.45}
|
||||
@@ -98,7 +113,8 @@ and nothing is copied.
|
||||
\end{tabularx}
|
||||
|
||||
Inside: \code{nexus.db} (profiles, known hosts, preferences, snippets, IRC state and the audit log),
|
||||
\code{vault/vault.json}, \code{recordings/}, \code{triggers.json} and \code{sftp-bookmarks.json}. Keychain entries are
|
||||
\code{vault/vault.json}, \code{recordings/}, \code{triggers.json}, \code{sftp-bookmarks.json} and \code{nexus.log}, the
|
||||
diagnostic log. Keychain entries are
|
||||
stored under the service name \code{NexusTerminal}.
|
||||
|
||||
\begin{protip}[Try things without touching your real data]
|
||||
|
||||
@@ -25,7 +25,8 @@ password, or the baud rate.
|
||||
\fix{``Host key verification failed''}{%
|
||||
The server's fingerprint changed since you last connected. That happens when a server is rebuilt, but it's also exactly
|
||||
what an attack looks like. \textbf{Check with whoever runs the server.} If it's legitimate:
|
||||
\menu{Settings\then Known Hosts}, \ui{Remove} the entry, reconnect and accept the new key.}
|
||||
choose \ui{Accept \& Update} in the warning (or \ui{Accept Once} to defer the decision). Under a Strict or Accept-new
|
||||
policy there's no prompt: \menu{Settings\then Known Hosts}, \ui{Remove} the entry and reconnect.}
|
||||
|
||||
\fix{It just says ``Connecting…'' forever}{%
|
||||
\begin{itemize}
|
||||
@@ -61,6 +62,15 @@ Check the network and the credentials, then the profile's auto-reconnect setting
|
||||
\item Connecting to a Mac? Turn on password access in macOS Screen Sharing settings (see p.\,\pageref{ch:vnc}).
|
||||
\end{itemize}}
|
||||
|
||||
\fix{RDP won't connect}{%
|
||||
\begin{itemize}
|
||||
\item Linux box running xrdp? Tick \ui{Allow servers without NLA}.
|
||||
\item ``Logon failed''? Check the domain. Kerberos users: the KDC must be reachable directly, not through the proxy.
|
||||
\item Certificate warning after a server rebuild? That's expected once; compare the fingerprint, then
|
||||
\ui{Accept \& Update}.
|
||||
\item Going through an RD Gateway? It needs a certificate from a public CA and Basic authentication over HTTPS.
|
||||
\end{itemize}}
|
||||
|
||||
\section{Files}
|
||||
|
||||
\fix{Upload is greyed out or fails}{%
|
||||
@@ -86,3 +96,11 @@ normally.}
|
||||
Start Nexus Terminal with \code{--data-dir} pointing at an empty folder and try the same connection there. If it
|
||||
works, something in your profile is off; duplicate the working one and compare.
|
||||
\end{quickwin}
|
||||
|
||||
\section{Still stuck?}
|
||||
|
||||
\fix{Something odd that isn't on this list}{%
|
||||
Look at \code{nexus.log} in your data folder (\menu{Settings\then Diagnostics} shows where): connections, reconnects,
|
||||
host-key checks and errors, never passwords or what's on screen. Start Nexus Terminal with \code{RUST\_LOG=debug} for
|
||||
more detail. Reporting a bug? \ui{Copy Diagnostics} and paste it in.}
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 122 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 129 KiB After Width: | Height: | Size: 127 KiB |
|
Before Width: | Height: | Size: 124 KiB After Width: | Height: | Size: 129 KiB |
|
Before Width: | Height: | Size: 138 KiB After Width: | Height: | Size: 138 KiB |
|
Before Width: | Height: | Size: 125 KiB After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 125 KiB After Width: | Height: | Size: 125 KiB |
|
Before Width: | Height: | Size: 135 KiB After Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 123 KiB After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 128 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 122 KiB After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 112 KiB |
|
Before Width: | Height: | Size: 93 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 71 KiB After Width: | Height: | Size: 72 KiB |
|
Before Width: | Height: | Size: 138 KiB After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 87 KiB |
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 153 KiB After Width: | Height: | Size: 154 KiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 118 KiB |
|
Before Width: | Height: | Size: 92 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 134 KiB After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 92 KiB After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 123 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 116 KiB |
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 177 KiB After Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 285 KiB After Width: | Height: | Size: 284 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 76 KiB After Width: | Height: | Size: 78 KiB |
@@ -194,7 +194,7 @@
|
||||
before skip=6pt, after skip=12pt, fontupper=\small,
|
||||
overlay={\node[anchor=north east, font=\heavy\tiny, text=#1!80!black, inner sep=8pt] at (frame.north east) {AT A GLANCE};}]
|
||||
{\heavy\Large\color{#1!85!black}#2}\par\vspace{4pt}
|
||||
\renewcommand\arraystretch{1.35}\begin{tabular}{@{}>{\leavevmode\color{muted}}p{0.24\linewidth}p{0.72\linewidth}@{}}}
|
||||
\renewcommand\arraystretch{1.35}\begin{tabular}{@{}>{\leavevmode\color{muted}}p{0.24\linewidth}>{\leavevmode}p{0.72\linewidth}@{}}}
|
||||
{\end{tabular}\end{tcolorbox}}
|
||||
|
||||
% --- Headings --------------------------------------------------------------------------
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
\usepackage{nexus-guide}
|
||||
|
||||
\hypersetup{pdftitle={Nexus Terminal: The User Guide}, pdfauthor={Andy Dixon},
|
||||
pdfsubject={SSH, Telnet, RAW, Serial, VNC, IRC and GitHub in one native app}}
|
||||
pdfsubject={SSH, Telnet, RAW, Serial, VNC, RDP, IRC and GitHub in one native app}}
|
||||
|
||||
\begin{document}
|
||||
\frontmatter
|
||||
@@ -29,13 +29,13 @@
|
||||
{Every terminal you need. One window.\\Zero faff.};
|
||||
\node[anchor=north west, text=white!65!ink, font=\normalsize, text width=150mm]
|
||||
at ([xshift=22mm, yshift=-110mm]pg.north west)
|
||||
{SSH\enspace·\enspace Telnet\enspace·\enspace RAW TCP\enspace·\enspace Serial\enspace·\enspace VNC\enspace·\enspace IRC\enspace·\enspace GitHub\enspace·\enspace Local shells};
|
||||
{SSH\enspace·\enspace Telnet\enspace·\enspace RAW TCP\enspace·\enspace Serial\enspace·\enspace VNC\enspace·\enspace RDP\enspace·\enspace IRC\enspace·\enspace GitHub\enspace·\enspace Local shells};
|
||||
\node[anchor=south west, inner sep=0pt] at ([xshift=22mm, yshift=22mm]pg.south west)
|
||||
{\begin{tikzpicture}
|
||||
\node[inner sep=0pt, draw=white!25!ink, line width=0.6pt, rounded corners=4pt] {\includegraphics[width=166mm]{img/ssh.png}};
|
||||
\end{tikzpicture}};
|
||||
\node[anchor=south east, text=white!55!ink, font=\footnotesize, align=right]
|
||||
at ([xshift=-22mm, yshift=24mm]pg.south east) {Version 0.1\\October 2026\\dixon.cx};
|
||||
at ([xshift=-22mm, yshift=24mm]pg.south east) {Version 3.0.1\\October 2026\\dixon.cx};
|
||||
}\null
|
||||
\cleardoublepage
|
||||
|
||||
@@ -61,7 +61,7 @@ what you'll be able to do afterwards, and a \textbf{TL;DR} if you only want the
|
||||
…copy files to and from a server & \hyperref[ch:files]{Files}, p.\,\pageref{ch:files}\\
|
||||
…type the same thing into ten servers at once & \hyperref[ch:repeat]{Never type it twice}, p.\,\pageref{ch:repeat}\\
|
||||
…keep my passwords safe & \hyperref[ch:secrets]{Passwords \& the vault}, p.\,\pageref{ch:secrets}\\
|
||||
…move over from Alchementary Link & \hyperref[ch:move]{Moving house}, p.\,\pageref{ch:move}\\
|
||||
…keep two computers in step & \hyperref[ch:move]{Moving house}, p.\,\pageref{ch:move}\\
|
||||
…fix something that's broken & \hyperref[part:fix]{When things go wrong}, p.\,\pageref{ch:trouble}\\
|
||||
…just see the keyboard shortcuts & \hyperref[app:keys]{The cheat sheet}, p.\,\pageref{app:keys}\\
|
||||
\bottomrule
|
||||
|
||||
@@ -90,9 +90,10 @@ shot editor-serial --open editor:serial
|
||||
shot editor-telnet --open editor:telnet
|
||||
shot editor-raw --open editor:raw
|
||||
shot editor-vnc --open editor:vnc
|
||||
shot editor-rdp --open editor:rdp
|
||||
shot editor-irc --open editor:irc
|
||||
shot editor-github --open editor:github
|
||||
for t in general terminal security knownhosts help about; do shot "settings-$t" --open "settings:$t"; done
|
||||
for t in general terminal security knownhosts diagnostics help about; do shot "settings-$t" --open "settings:$t"; done
|
||||
shot keys --open keys
|
||||
shot snippets --open snippets
|
||||
shot triggers --open triggers
|
||||
|
||||
@@ -41,6 +41,7 @@ Use Nexus Terminal when you need to:
|
||||
- Multi-select profiles with Ctrl/Cmd-click for bulk connect, disconnect, tagging, moving between groups and deleting.
|
||||
- Test basic host and port reachability before connecting.
|
||||
- Import existing OpenSSH config entries from `~/.ssh/config`, including hostnames, usernames, ports, identity files and jump hosts.
|
||||
- Sync profiles between machines through any shared folder, as one encrypted file (newest change wins; deletions propagate; credentials stay local).
|
||||
- Export and import profiles using encrypted `.nexus` bundles.
|
||||
- Plain JSON export and import, with secrets redacted unless you choose to include them.
|
||||
- Choose import behaviour for duplicates: skip, overwrite or duplicate.
|
||||
@@ -69,14 +70,20 @@ Use Nexus Terminal when you need to:
|
||||
- Find in terminal output, with case-sensitive and regular-expression options and a match counter.
|
||||
- Copy with Ctrl/Cmd+C when text is selected (otherwise it sends an interrupt), paste with Ctrl/Cmd+V.
|
||||
- Double-click selects a word, triple-click selects a line, Shift-click extends a selection.
|
||||
- Ctrl/Cmd-click a web link to open it in your browser.
|
||||
- Ctrl/Cmd-click a web link to open it in your browser, including OSC 8 hyperlinks (from `ls --hyperlink`, `git`, compilers…), which are underlined with a dotted line and show their real target on hover. Only http(s) links open.
|
||||
- Shift+PageUp/PageDown/Home/End and the mouse wheel scroll the scrollback; on the alternate screen the wheel sends arrow keys, so `tmux`, `screen` and `byobu` scroll naturally.
|
||||
- Context menu with Copy, Paste, Select All, Find, Send Snippet, Port Forwards, Split Right, Split Down, Export Output, Clear and Reset.
|
||||
- Export the whole scrollback as plain text.
|
||||
- Tabs and split panes are restored at the next launch: connections reconnect and local shells reopen in their last directory.
|
||||
- Inline images in the iTerm2 format (`imgcat`, `wezterm imgcat`, `chafa -f iterm`…): PNG, JPEG and GIF, sized in cells, pixels or percent, scrolling with the text.
|
||||
- Shell integration (OSC 133): jump between prompts, copy the last command's output, and see each command's exit status and duration beside its prompt.
|
||||
- Status-bar latency for the active SSH session.
|
||||
- Settings → Diagnostics summarises versions, paths, credential storage and sync status for bug reports; Settings → Security lists stored credentials per profile and changes the vault master password.
|
||||
|
||||
### SSH capabilities
|
||||
|
||||
- SSH certificates: host certificates from trusted CAs (by OpenSSH host pattern) skip the first-use prompt; user certificates (`*-cert.pub`) are used for login.
|
||||
- Import and export `~/.ssh/known_hosts`, including `@cert-authority` lines.
|
||||
- Password, public key, keyboard-interactive and SSH agent authentication.
|
||||
- SSH agent forwarding.
|
||||
- Private key suggestions from `~/.ssh`, with a key file check.
|
||||
@@ -144,10 +151,11 @@ Use Nexus Terminal when you need to:
|
||||
|
||||
- Native RDP viewer (IronRDP) with Network Level Authentication (CredSSP/NTLM) and optional TLS-only logon for servers such as xrdp.
|
||||
- Server certificate pinned by fingerprint in Known Hosts, checked before credentials are sent.
|
||||
- Direct, SOCKS5, HTTP CONNECT or SSH-tunnelled connections.
|
||||
- Direct, SOCKS5, HTTP CONNECT, SSH-tunnelled or (experimental) RD Gateway connections.
|
||||
- Scale-to-fit or 1:1, a fixed resolution or one that follows the tab (Display Control).
|
||||
- Keyboard (scancodes for keys and shortcuts, Unicode for text), mouse and wheel; Ctrl+Alt+Del; type the clipboard into the session.
|
||||
- Password storage modes and domain logon.
|
||||
- Keyboard (scancodes for keys and shortcuts, Unicode for text), mouse and wheel; Ctrl+Alt+Del; text clipboard sharing in both directions.
|
||||
- Password storage modes, domain logon, and Kerberos through a configured KDC.
|
||||
- Remote audio playback, a printer whose jobs are saved as PostScript files, and a shared folder redirected as a drive (Linux and macOS), confined to that folder.
|
||||
|
||||
### VNC capabilities
|
||||
|
||||
@@ -162,6 +170,7 @@ Use Nexus Terminal when you need to:
|
||||
|
||||
### IRC capabilities
|
||||
|
||||
- IRCv3 capability negotiation with SASL PLAIN login and server-time timestamps.
|
||||
- Nick, real name, TLS and an optional server password.
|
||||
- NickServ identification on connect.
|
||||
- Auto-join rooms.
|
||||
|
||||
@@ -166,20 +166,23 @@ Use SSH tunnelling for VNC whenever possible. If a VNC profile has no tunnel, Ne
|
||||
|
||||
- **RDP**: domain (optional), password storage mode, **Certificate Policy** and **Allow servers without NLA**. The username, host and port (3389) are the profile's own.
|
||||
- **Display**: **Scale to Fit**, a fixed **Width** and **Height** (0 × 0 fits the tab) and **Resize With Tab**.
|
||||
- **RD Gateway** (experimental): reach the desktop through a Remote Desktop Gateway (`host` or `host:port`) with its own username and password. The gateway's certificate must be valid for its name (public CA); only gateways that accept Basic authentication over HTTPS work.
|
||||
- **Proxy**: **SOCKS5** or **HTTP CONNECT**, with an optional username and password.
|
||||
- **Devices**: **Play Remote Audio**; **Redirect Printer**, which adds a *Nexus Terminal* printer on the remote desktop whose jobs are saved as PostScript files in your Downloads folder (up to 256 MiB per job); and on Linux and macOS a **Shared Folder** that appears on the remote desktop as a drive named Nexus. The server can read and change everything in that folder and nothing outside it: paths that try to leave it (`..`, or symlinks pointing elsewhere) are refused.
|
||||
- **SSH Tunnel**: carry RDP through SSH, as for VNC. Use either a proxy or a tunnel, not both.
|
||||
|
||||
Nexus Terminal logs on with Network Level Authentication (CredSSP, NTLM), so your password is checked before a session is set up. Servers without NLA, such as xrdp, need **Allow servers without NLA**; the password is then passed to the server's own logon. Kerberos and smart cards are not supported.
|
||||
Nexus Terminal logs on with Network Level Authentication (CredSSP), so your password is checked before a session is set up. It uses NTLM unless you set a **Kerberos KDC** (`host` or `host:port`), in which case it gets a Kerberos ticket from that KDC over TCP; the KDC must be reachable directly (not through the profile's proxy or tunnel). Use your Kerberos realm as the domain. Servers without NLA, such as xrdp, need **Allow servers without NLA**; the password is then passed to the server's own logon. Smart cards are not supported.
|
||||
|
||||
RDP servers usually present self-signed certificates, so the certificate is pinned like an SSH host key: its SHA-256 fingerprint is shown the first time and stored in **Known Hosts**, and a changed certificate offers Reject, Accept Once or Accept & Update. The check happens before any credentials are sent.
|
||||
|
||||
The viewer works like the VNC one: click the desktop to give it keyboard focus, **Ctrl+Alt+Del** sends the key combination, and **Paste Clipboard** types your clipboard's text into the remote desktop (clipboard sharing is not supported yet). With **Resize With Tab**, the remote desktop follows the tab's size on servers that support it (Windows); otherwise the picture is scaled.
|
||||
The viewer works like the VNC one: click the desktop to give it keyboard focus, **Ctrl+Alt+Del** sends the key combination, and text is shared through the clipboard both ways: text you copy on the remote desktop arrives on your clipboard (subject to the remote-clipboard setting), and your clipboard is offered to the remote desktop whenever you click into it, press Ctrl+V or use **Paste Clipboard**. Files and images are not shared. With **Resize With Tab**, the remote desktop follows the tab's size on servers that support it (Windows); otherwise the picture is scaled.
|
||||
|
||||
### IRC
|
||||
|
||||
- **IRC**: nick, real name, **Use TLS** (port 6697 for most TLS networks) and an optional server password.
|
||||
- **SASL**: log in during registration with SASL PLAIN (account defaults to your nick), which most networks now expect; use TLS or an SSH tunnel so the password isn't sent in the clear. If the network doesn't offer SASL or rejects the login, the Server tab says so and the connection carries on.
|
||||
- **NickServ**: identify on connect, with an optional account name and password.
|
||||
- **Rooms**: rooms to join automatically, one per line or comma-separated.
|
||||
- **Rooms**: rooms to join automatically, one per line or comma-separated. Networks that support IRCv3 server-time stamp messages with the time they were sent, so replayed history shows its real times.
|
||||
- **SSH Tunnel** and **Reconnection** settings.
|
||||
|
||||
The IRC view has a **Server** tab and a tab per room or conversation, with a dot on tabs that have unread messages. Type messages or `/commands` in the composer (`/join`, `/part`, `/msg`, `/me`, `/notice`, `/nick`, `/topic`, `/list`, `/names`, `/whois`, `/who`, `/raw`, `/quit`, `/help`). Press **Tab** to complete a nick, or click a nick to mention it. The side panel lists joined rooms, a room browser with a filter (click a room to join it), and the users in the current room.
|
||||
@@ -216,12 +219,42 @@ A new pane offers **Local Machine** and your terminal profiles (SSH, Telnet and
|
||||
|
||||
## 6. Terminal actions and search
|
||||
|
||||
### Inline images
|
||||
|
||||
Programs that print images in the iTerm2 format (`imgcat`, `wezterm imgcat`, `chafa -f iterm`) show PNG, JPEG and GIF (first frame) images inline, sized as the program asks and never wider than the terminal; the text continues below the image. Images scroll with the text and are dropped with the scrollback. Very large images (over 8192 pixels a side) are ignored, and each terminal keeps at most 32 megapixels of images, dropping the oldest. Sixel and kitty graphics aren't supported.
|
||||
|
||||
### Shell integration
|
||||
|
||||
When the shell marks its prompts and commands (the OSC 133 sequences), Nexus Terminal knows where each command starts and ends:
|
||||
|
||||
- **Ctrl+Shift+Up / Ctrl+Shift+Down** (**Cmd+Shift** on macOS), or **Previous Prompt** / **Next Prompt** in the right-click menu, jump between prompts in the scrollback.
|
||||
- **Copy Last Command Output** in the right-click menu copies what the last finished command printed.
|
||||
- A thin bar beside each finished command's prompt shows how it ended: green for success, red for a non-zero exit. Hover it for the exit code and how long the command took.
|
||||
|
||||
fish 4 and several prompt themes (Starship, Powerlevel10k with its shell integration option) send the marks already. For bash, add this to `~/.bashrc` on the machine the shell runs on:
|
||||
|
||||
```bash
|
||||
PS0='\[\e]133;C\a\]'
|
||||
PROMPT_COMMAND='printf "\033]133;D;%s\007" "$?"; '"${PROMPT_COMMAND}"
|
||||
PS1='\[\e]133;A\a\]'"$PS1"'\[\e]133;B\a\]'
|
||||
```
|
||||
|
||||
For zsh, add to `~/.zshrc`:
|
||||
|
||||
```zsh
|
||||
precmd() { print -Pn "\e]133;D;$?\a\e]133;A\a" }
|
||||
preexec() { print -n "\e]133;C\a" }
|
||||
PS1="$PS1%{\e]133;B\a%}"
|
||||
```
|
||||
|
||||
Shells that also report their working directory (OSC 7; fish, and zsh/bash with the usual `printf '\e]7;file://%s%s\a' "$HOSTNAME" "$PWD"` hook) let **SFTP Browser** open in that directory.
|
||||
|
||||
### Keyboard and mouse
|
||||
|
||||
- **Copy**: select text and press **Cmd+C** / **Ctrl+C**. With nothing selected, **Ctrl+C** sends an interrupt as usual.
|
||||
- **Paste**: **Cmd+V** / **Ctrl+V**. Pastes are bracketed when the remote application asks for it.
|
||||
- **Select**: drag to select, double-click for a word, triple-click for a line, Shift-click to extend.
|
||||
- **Links**: hold **Cmd** / **Ctrl** and click a web link to open it in your browser.
|
||||
- **Links**: hold **Cmd** / **Ctrl** and click a web link to open it in your browser. Programs can also print real hyperlinks (OSC 8, as `ls --hyperlink` and many build tools do); these have a dotted underline, and hovering one shows where it really points. Only http(s) links are opened.
|
||||
- **Scroll**: the mouse wheel, or **Shift+PageUp**, **Shift+PageDown**, **Shift+Home** and **Shift+End**. On the alternate screen (for example in `tmux`, `screen`, `byobu` or `less`) the wheel sends arrow keys instead.
|
||||
- Applications that use the mouse (such as `htop`, `vim` or `tmux` with mouse mode) receive mouse clicks and the wheel directly.
|
||||
|
||||
@@ -373,6 +406,10 @@ Choose one of the following policies per SSH profile:
|
||||
- **Accept new, reject changed**: trust first-time keys automatically.
|
||||
- **Insecure (accept anything)**: accept any key (not recommended).
|
||||
|
||||
**Settings → Known Hosts** can **Import ~/.ssh/known_hosts** (hashed host names can't be read back and are skipped) and **Export…** the list in OpenSSH format, so Nexus Terminal and `ssh` can share what they trust.
|
||||
|
||||
**SSH certificates.** **Trust a CA…** adds a certificate authority for a host pattern in OpenSSH syntax (`*.example.com`, `[host]:2222`, `!excluded.example.com`; `@cert-authority` lines in an imported known_hosts work too). Servers covered by a trusted CA are asked for their host certificate, and a certificate that the CA signed, that names the host and that is in date is trusted without a first-use prompt; any other certificate is refused. For logging in, a user certificate next to your key (`id_ed25519-cert.pub` beside `id_ed25519`) is used automatically.
|
||||
|
||||
Under every policy except Insecure, a key that differs from the saved one is rejected. Nexus Terminal keeps its own known-hosts list and does not read `~/.ssh/known_hosts`. Review and remove entries in **Settings → Known Hosts**; click a fingerprint to copy it.
|
||||
|
||||
### TOTP / 2FA
|
||||
@@ -391,6 +428,15 @@ Connections, disconnections, profile changes, credential access, imports and exp
|
||||
|
||||
## 13. Import and export
|
||||
|
||||
### Profile sync
|
||||
|
||||
**Settings → Security → Profile sync** keeps connection profiles the same on several machines. Choose a folder all of them can reach (a Dropbox, iCloud Drive, OneDrive or Nextcloud folder, a network share, or a git checkout you commit), and set the same **sync password** on each. Nexus Terminal keeps one encrypted file there, `nexus-profiles.nexus` (Argon2id + AES-256-GCM, like an encrypted export), and merges it at launch, a few seconds after you change a profile, every ten minutes and when you click **Sync Now**:
|
||||
|
||||
- for a profile changed on both sides, the more recent change wins;
|
||||
- a profile deleted on one machine is deleted on the others (unless it was edited after the deletion);
|
||||
- passwords, keys and other credentials are never synced; each machine keeps its own in its keychain or vault.
|
||||
|
||||
|
||||
- **Encrypted export**: **File → Export profiles…**, the sidebar footer, the command palette, or **Export…** on a profile's right-click menu. Choose the profiles, set a password and save a `.nexus` file. Credentials saved in the keychain or vault are not included.
|
||||
- **Encrypted import**: **File → Import profiles…** or the sidebar footer. Choose a `.nexus` file, enter its password, and choose what happens when a profile already exists: **Skip existing**, **Overwrite existing** or **Create duplicates**.
|
||||
- **JSON export and import**: **Export Profiles (JSON)** and **Import Profiles (JSON)** in the command palette. JSON export includes every profile; passwords in login-script `send` steps that answer a password prompt are blanked unless you tick **Include secrets**. Proxy passwords and TOTP secrets live in the keychain or vault, never in the profile, so no export carries them.
|
||||
@@ -402,10 +448,11 @@ Connections, disconnections, profile changes, credential access, imports and exp
|
||||
|
||||
Open settings with **Cmd+,** (macOS) or **Ctrl+,** (Windows/Linux), the sidebar footer, or **File → Settings**. Click **Save** to apply changes.
|
||||
|
||||
- **General**: app theme (Pro, Midnight or Light), default protocol, confirm on close, confirm on disconnect, remote clipboard writes (OSC 52 and VNC; a toast shows what was copied), multi-line paste confirmation, the launch-time update check, status bar, sidebar width, and local shell (leave empty for the system default; **Browse…** to pick one).
|
||||
- **General**: app theme (Pro, Midnight or Light), default protocol, restore tabs at launch (reopens the last session's tabs and split panes: saved connections reconnect, local shells start in the directory they were in; Quick Connect tabs aren't restored), confirm on close, confirm on disconnect, remote clipboard writes (OSC 52 and VNC; a toast shows what was copied), multi-line paste confirmation, the launch-time update check, status bar, sidebar width, and local shell (leave empty for the system default; **Browse…** to pick one).
|
||||
- **Terminal**: colour scheme, font family, font size, scrollback lines and cursor style. These are the defaults for new profiles; profiles can override them.
|
||||
- **Security**: keychain and vault status; initialise, unlock or lock the secret store.
|
||||
- **Known Hosts**: saved host keys with first-seen and last-seen times, and **Remove**.
|
||||
- **Security**: keychain and vault status; initialise, unlock or lock the secret store; **Change Master Password…** (re-encrypts every saved credential under the new password in one step); **Stored credentials**, listing each profile's saved passwords, passphrases and tokens and whether they're in the keychain or the vault, with **Forget**; and profile sync.
|
||||
- **Known Hosts**: saved host keys with first-seen and last-seen times, and **Remove**; import/export `~/.ssh/known_hosts` and trusted SSH certificate authorities.
|
||||
- **Diagnostics**: version, platform, data, database and log locations, keychain and vault state, counts and sync status, with **Copy Diagnostics** for bug reports (no credentials are included).
|
||||
- **Help**: built-in help topics, including connection types, shortcuts and troubleshooting.
|
||||
- **About**: version, **Check for Updates**, and **Import ~/.ssh/config**.
|
||||
|
||||
@@ -434,6 +481,7 @@ The directory holds:
|
||||
- `recordings/` — session recordings
|
||||
- `triggers.json` — trigger rules
|
||||
- `sftp-bookmarks.json` — SFTP bookmarks
|
||||
- `nexus.log` — the diagnostic log (owner-only, rotated to `nexus.log.1` at 5 MiB): connections, reconnects, host-key and certificate checks and errors. Credentials and terminal contents are never logged. Set `RUST_LOG` (for example `RUST_LOG=debug`) for more detail; it then also goes to the terminal you started Nexus Terminal from.
|
||||
|
||||
Credentials saved in the OS keychain are stored under the service name `NexusTerminal`.
|
||||
|
||||
|
||||
@@ -264,6 +264,28 @@ dependencies = [
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alsa"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"
|
||||
dependencies = [
|
||||
"alsa-sys",
|
||||
"bitflags 2.13.2",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "alsa-sys"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android-activity"
|
||||
version = "0.6.1"
|
||||
@@ -273,7 +295,7 @@ dependencies = [
|
||||
"android-properties",
|
||||
"bitflags 2.13.2",
|
||||
"cc",
|
||||
"jni",
|
||||
"jni 0.22.4",
|
||||
"libc",
|
||||
"log",
|
||||
"ndk",
|
||||
@@ -949,6 +971,12 @@ dependencies = [
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cesu8"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
@@ -1073,6 +1101,12 @@ dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "color_quant"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
|
||||
|
||||
[[package]]
|
||||
name = "combine"
|
||||
version = "4.6.8"
|
||||
@@ -1154,6 +1188,50 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "coreaudio-rs"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"libc",
|
||||
"objc2-audio-toolbox",
|
||||
"objc2-core-audio",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpal"
|
||||
version = "0.17.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d8942da362c0f0d895d7cac616263f2f9424edc5687364dfd1d25ef7eba506d7"
|
||||
dependencies = [
|
||||
"alsa",
|
||||
"coreaudio-rs",
|
||||
"dasp_sample",
|
||||
"jni 0.21.1",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"mach2 0.5.0",
|
||||
"ndk",
|
||||
"ndk-context",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"objc2 0.6.5",
|
||||
"objc2-audio-toolbox",
|
||||
"objc2-avf-audio",
|
||||
"objc2-core-audio",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
@@ -1362,6 +1440,12 @@ dependencies = [
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dasp_sample"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
@@ -2255,6 +2339,16 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gif"
|
||||
version = "0.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
|
||||
dependencies = [
|
||||
"color_quant",
|
||||
"weezl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gl_generator"
|
||||
version = "0.14.0"
|
||||
@@ -2553,6 +2647,29 @@ dependencies = [
|
||||
"itoa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-body-util"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
@@ -2577,6 +2694,39 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
|
||||
dependencies = [
|
||||
"atomic-waker",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
"tokio",
|
||||
"want",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper-util"
|
||||
version = "0.1.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http",
|
||||
"http-body",
|
||||
"hyper",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
@@ -2713,6 +2863,8 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"byteorder-lite",
|
||||
"color_quant",
|
||||
"gif",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
@@ -2758,7 +2910,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"mach2",
|
||||
"mach2 0.4.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2767,6 +2919,7 @@ version = "0.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f910b8dc8e7b8e001c61fd742be442e8604fb2499ded713cadf911e7645ade4"
|
||||
dependencies = [
|
||||
"ironrdp-cliprdr",
|
||||
"ironrdp-connector",
|
||||
"ironrdp-core",
|
||||
"ironrdp-displaycontrol",
|
||||
@@ -2774,6 +2927,8 @@ dependencies = [
|
||||
"ironrdp-graphics",
|
||||
"ironrdp-input",
|
||||
"ironrdp-pdu",
|
||||
"ironrdp-rdpdr",
|
||||
"ironrdp-rdpsnd",
|
||||
"ironrdp-session",
|
||||
"ironrdp-svc",
|
||||
]
|
||||
@@ -2797,6 +2952,19 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e548d9fd162558a5a8aaed72e528556ce88e77773634e3722b8d01d6f170388"
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-cliprdr"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb9050999a1e032f4313788ac5a6d06e897a4f672f1de2ed98683001fc1abf56"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"ironrdp-core",
|
||||
"ironrdp-pdu",
|
||||
"ironrdp-svc",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-connector"
|
||||
version = "0.10.0"
|
||||
@@ -2884,6 +3052,27 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-mstsgu"
|
||||
version = "0.0.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bitflags 2.13.2",
|
||||
"futures-util",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"ironrdp-core",
|
||||
"ironrdp-error",
|
||||
"log",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-tungstenite",
|
||||
"tokio-util",
|
||||
"uuid",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-pdu"
|
||||
version = "0.9.0"
|
||||
@@ -2907,6 +3096,59 @@ dependencies = [
|
||||
"x509-cert",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-rdpdr"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ece9e67ccf992eb8ce5ec0416d3950e2e199d4b1e2523f91af192205279fc970"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"ironrdp-core",
|
||||
"ironrdp-error",
|
||||
"ironrdp-pdu",
|
||||
"ironrdp-svc",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-rdpdr-native"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f3e964857871c3a49cf5e642320908a0be73c923f7f037c347c33f23001113e7"
|
||||
dependencies = [
|
||||
"ironrdp-core",
|
||||
"ironrdp-pdu",
|
||||
"ironrdp-rdpdr",
|
||||
"ironrdp-svc",
|
||||
"nix 0.31.3",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-rdpsnd"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d1a4f7092ae8fdc0a2f61be8e100277dc6f4ad51b85455dc9e8157979993ea2"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"ironrdp-core",
|
||||
"ironrdp-pdu",
|
||||
"ironrdp-svc",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-rdpsnd-native"
|
||||
version = "0.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d2d36d9bb45863f9bc5225bf3bccda125fafb1b225c1f99dbeaeebb258e7dc"
|
||||
dependencies = [
|
||||
"cpal",
|
||||
"ironrdp-error",
|
||||
"ironrdp-rdpsnd",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ironrdp-session"
|
||||
version = "0.11.0"
|
||||
@@ -2966,6 +3208,22 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "jni"
|
||||
version = "0.21.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
|
||||
dependencies = [
|
||||
"cesu8",
|
||||
"cfg-if",
|
||||
"combine",
|
||||
"jni-sys 0.3.1",
|
||||
"log",
|
||||
"thiserror 1.0.69",
|
||||
"walkdir",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jni"
|
||||
version = "0.22.4"
|
||||
@@ -3225,6 +3483,24 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mach2"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a1b95cd5421ec55b445b5ae102f5ea0e768de1f82bd3001e11f426c269c3aea"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||
dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
@@ -3434,28 +3710,32 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "nexus"
|
||||
version = "0.1.0"
|
||||
version = "3.0.1"
|
||||
dependencies = [
|
||||
"alacritty_terminal",
|
||||
"arboard",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"eframe",
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"image",
|
||||
"libc",
|
||||
"nexus-core",
|
||||
"parking_lot",
|
||||
"regex",
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"winresource",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nexus-core"
|
||||
version = "0.1.0"
|
||||
version = "3.0.1"
|
||||
dependencies = [
|
||||
"aes-gcm 0.10.3",
|
||||
"argon2 0.5.3",
|
||||
@@ -3467,6 +3747,9 @@ dependencies = [
|
||||
"image",
|
||||
"ironrdp",
|
||||
"ironrdp-blocking",
|
||||
"ironrdp-mstsgu",
|
||||
"ironrdp-rdpdr-native",
|
||||
"ironrdp-rdpsnd-native",
|
||||
"keyring",
|
||||
"libc",
|
||||
"parking_lot",
|
||||
@@ -3483,6 +3766,7 @@ dependencies = [
|
||||
"sha2 0.11.0",
|
||||
"tiny_http",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"ureq",
|
||||
"uuid",
|
||||
"webpki-roots",
|
||||
@@ -3554,6 +3838,15 @@ dependencies = [
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num"
|
||||
version = "0.4.3"
|
||||
@@ -3744,6 +4037,31 @@ dependencies = [
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-audio-toolbox"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"libc",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-audio",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-avf-audio"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-cloud-kit"
|
||||
version = "0.2.2"
|
||||
@@ -3768,6 +4086,29 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-audio"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"
|
||||
dependencies = [
|
||||
"dispatch2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-audio-types",
|
||||
"objc2-core-foundation",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-audio-types"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-data"
|
||||
version = "0.2.2"
|
||||
@@ -3787,7 +4128,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"dispatch2",
|
||||
"libc",
|
||||
"objc2 0.6.5",
|
||||
]
|
||||
|
||||
@@ -3855,6 +4198,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"libc",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-foundation",
|
||||
]
|
||||
@@ -5435,7 +5779,7 @@ dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"core-foundation-sys",
|
||||
"io-kit-sys",
|
||||
"mach2",
|
||||
"mach2 0.4.3",
|
||||
"nix 0.26.4",
|
||||
"scopeguard",
|
||||
"unescaper",
|
||||
@@ -5507,6 +5851,15 @@ dependencies = [
|
||||
"sponge-cursor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shared_library"
|
||||
version = "0.1.9"
|
||||
@@ -5984,6 +6337,15 @@ dependencies = [
|
||||
"syn 3.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiff"
|
||||
version = "0.11.3"
|
||||
@@ -6101,6 +6463,28 @@ dependencies = [
|
||||
"syn 3.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-rustls"
|
||||
version = "0.26.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
|
||||
dependencies = [
|
||||
"rustls",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-tungstenite"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"log",
|
||||
"tokio",
|
||||
"tungstenite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-util"
|
||||
version = "0.7.20"
|
||||
@@ -6198,6 +6582,44 @@ dependencies = [
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
|
||||
dependencies = [
|
||||
"matchers",
|
||||
"nu-ansi-term",
|
||||
"once_cell",
|
||||
"regex-automata",
|
||||
"sharded-slab",
|
||||
"thread_local",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "try-lock"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.29.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.9.5",
|
||||
"sha1 0.10.7",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "type-map"
|
||||
version = "0.5.1"
|
||||
@@ -6417,6 +6839,15 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "want"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
|
||||
dependencies = [
|
||||
"try-lock",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
@@ -6926,6 +7357,15 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.45.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
|
||||
dependencies = [
|
||||
"windows-targets 0.42.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
@@ -6962,6 +7402,21 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm 0.42.2",
|
||||
"windows_aarch64_msvc 0.42.2",
|
||||
"windows_i686_gnu 0.42.2",
|
||||
"windows_i686_msvc 0.42.2",
|
||||
"windows_x86_64_gnu 0.42.2",
|
||||
"windows_x86_64_gnullvm 0.42.2",
|
||||
"windows_x86_64_msvc 0.42.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
@@ -7004,6 +7459,12 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
@@ -7016,6 +7477,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -7028,6 +7495,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
@@ -7052,6 +7525,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
@@ -7064,6 +7543,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
@@ -7076,6 +7561,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
@@ -7088,6 +7579,12 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["core", "app"]
|
||||
exclude = ["fuzz"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
version = "3.0.1"
|
||||
edition = "2024"
|
||||
|
||||
[profile.dev.package."*"]
|
||||
@@ -21,3 +22,4 @@ lto = "thin"
|
||||
picky = { path = "vendor/picky" }
|
||||
sspi = { path = "vendor/sspi" }
|
||||
ironrdp-session = { path = "vendor/ironrdp-session" }
|
||||
ironrdp-mstsgu = { path = "vendor/ironrdp-mstsgu" }
|
||||
|
||||
@@ -14,9 +14,12 @@ eframe = { version = "0.36", default-features = false, features = ["default_font
|
||||
egui = "0.36"
|
||||
parking_lot = "0.12"
|
||||
zeroize = "1"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "env-filter", "std", "ansi"] }
|
||||
egui-phosphor = "0.14"
|
||||
rfd = "0.17"
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "gif"] }
|
||||
base64 = "0.22"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
regex = "1"
|
||||
@@ -26,3 +29,6 @@ arboard = "3.6.1"
|
||||
|
||||
[build-dependencies]
|
||||
winresource = "0.1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -121,6 +121,13 @@ pub enum InputThen {
|
||||
|
||||
pub struct App {
|
||||
pub s: Shared,
|
||||
/// The tab layout as last saved for restoring (see restore.rs), and when it was last checked.
|
||||
pub saved_layout: Option<String>,
|
||||
layout_checked: f64,
|
||||
/// A profile sync in flight; when the next automatic one is due; whether it was asked for.
|
||||
sync_job: Option<crate::settings::Job<Result<nexus_core::service::SyncReport, String>>>,
|
||||
sync_due: f64,
|
||||
sync_manual: bool,
|
||||
rx: mpsc::Receiver<Event>,
|
||||
pub theme: ThemeKind,
|
||||
pub editor: profile_editor::ProfileEditor,
|
||||
@@ -195,7 +202,16 @@ impl App {
|
||||
answers: opts.answers,
|
||||
run_local: opts.run_local.map(|c| (c, None)),
|
||||
resize_sidebar: false,
|
||||
saved_layout: None,
|
||||
layout_checked: 0.0,
|
||||
sync_job: None,
|
||||
sync_due: 0.0,
|
||||
sync_manual: false,
|
||||
};
|
||||
let restore = opts.connect.is_empty() && app.run_local.is_none() && opts.open.is_none() && app.s.prefs.restore_sessions;
|
||||
if restore {
|
||||
crate::restore::restore(&mut app);
|
||||
}
|
||||
for c in &opts.connect {
|
||||
match app.s.profiles.iter().find(|p| &p.id == c || &p.display_name == c).map(|p| p.id.clone()) {
|
||||
Some(id) => app.connect_profile(&id, true),
|
||||
@@ -236,6 +252,7 @@ impl App {
|
||||
"terminal" => SettingsTab::Terminal,
|
||||
"security" => SettingsTab::Security,
|
||||
"knownhosts" => SettingsTab::KnownHosts,
|
||||
"diagnostics" => SettingsTab::Diagnostics,
|
||||
"help" => SettingsTab::Help,
|
||||
"about" => SettingsTab::About,
|
||||
_ => SettingsTab::General,
|
||||
@@ -485,6 +502,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
Event::Warning { message, .. } => self.s.error(message),
|
||||
Event::Info { message, .. } => self.s.success(message),
|
||||
Event::Irc { session, event } => {
|
||||
if let Some(View::Irc(v)) = self.s.panes.get_mut(&session).map(|p| &mut p.view) {
|
||||
v.on_event(event);
|
||||
@@ -528,7 +546,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
Event::DesktopFrame { .. } => {}
|
||||
Event::VncClipboard { text, .. } => self.remote_clipboard(&text),
|
||||
Event::DesktopClipboard { text, .. } => self.remote_clipboard(&text),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -604,7 +622,15 @@ impl App {
|
||||
Err(e) => self.s.error(format!("Can't connect to {name}: {e}")),
|
||||
}
|
||||
}
|
||||
Request::ReloadProfiles => self.s.reload_profiles(),
|
||||
Request::ReloadProfiles => {
|
||||
self.s.reload_profiles();
|
||||
// A profile changed: sync it out shortly (batched with any further edits).
|
||||
self.sync_due = self.sync_due.min(self.s.now + 3.0);
|
||||
}
|
||||
Request::SyncProfiles => {
|
||||
self.sync_manual = true;
|
||||
self.sync_due = 0.0;
|
||||
}
|
||||
Request::ReloadPreferences => {
|
||||
self.s.prefs = self.s.svc.preferences();
|
||||
self.resize_sidebar = true;
|
||||
@@ -613,7 +639,13 @@ impl App {
|
||||
}
|
||||
Request::ExportEncrypted(ids) => self.transfer.export_encrypted(ids),
|
||||
Request::ImportEncrypted => self.transfer.import_encrypted(),
|
||||
Request::Sftp(id) => self.sftp.toggle(&id),
|
||||
Request::Sftp(id) => {
|
||||
let at = match self.s.pane(&id).map(|p| &p.view) {
|
||||
Some(View::Terminal(t)) => t.reported_cwd.as_ref().map(|c| c.1.clone()),
|
||||
_ => None,
|
||||
};
|
||||
self.sftp.toggle(&id, at);
|
||||
}
|
||||
Request::SendToActive(text) => match self.s.focused_session() {
|
||||
Some(id) if self.s.session_state(&id) == Some(SessionState::Connected) => self.send_input(&id, text.as_bytes()),
|
||||
_ => self.s.error("No active connected session"),
|
||||
@@ -768,6 +800,42 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Profile sync: at launch, a few seconds after a profile changes, every 10 minutes and on
|
||||
/// request, when a folder and password are set. Automatic runs stay quiet unless something
|
||||
/// changed or a manual one failed.
|
||||
fn drive_sync(&mut self, ctx: &egui::Context) {
|
||||
if let Some(r) = crate::settings::poll(&mut self.sync_job) {
|
||||
let manual = std::mem::take(&mut self.sync_manual);
|
||||
match r {
|
||||
Ok(rep) => {
|
||||
if rep.pulled + rep.removed > 0 {
|
||||
self.s.reload_profiles();
|
||||
self.s.info(format!("Profile sync: {} updated, {} removed", rep.pulled, rep.removed));
|
||||
} else if manual {
|
||||
self.s.success(if rep.pushed { "Profiles synced" } else { "Profiles already in sync" });
|
||||
}
|
||||
if rep.skipped > 0 {
|
||||
self.s.error(format!("Profile sync skipped {} invalid profile(s) from the shared file", rep.skipped));
|
||||
}
|
||||
}
|
||||
Err(e) if manual => self.s.error(format!("Profile sync failed: {e}")),
|
||||
Err(e) => tracing::warn!(error = %e, "profile sync failed"),
|
||||
}
|
||||
}
|
||||
if self.screenshot.is_some() || self.sync_job.is_some() || self.s.now < self.sync_due {
|
||||
return;
|
||||
}
|
||||
self.sync_due = self.s.now + 600.0;
|
||||
if self.s.prefs.sync_folder.trim().is_empty() {
|
||||
if std::mem::take(&mut self.sync_manual) {
|
||||
self.s.error("Choose a sync folder first");
|
||||
}
|
||||
return;
|
||||
}
|
||||
let svc = self.s.svc.clone();
|
||||
self.sync_job = Some(crate::settings::Job::spawn(ctx, move || svc.sync_profiles().map_err(|e| e.to_string())));
|
||||
}
|
||||
|
||||
pub fn toggle_broadcast(&mut self) {
|
||||
self.s.broadcast = !self.s.broadcast;
|
||||
if !self.s.broadcast {
|
||||
@@ -845,7 +913,8 @@ impl App {
|
||||
t.reset();
|
||||
}
|
||||
}
|
||||
MenuAction::Copy | MenuAction::SelectAll => {}
|
||||
// Handled inside the terminal view.
|
||||
MenuAction::Copy | MenuAction::SelectAll | MenuAction::PrevPrompt | MenuAction::NextPrompt | MenuAction::CopyOutput => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -931,7 +1000,7 @@ impl eframe::App for App {
|
||||
if self.palette.is_none() && self.dialog.is_none() && self.prompts.is_empty() {
|
||||
self.shortcuts(&ctx);
|
||||
}
|
||||
if ctx.input(|i| i.key_pressed(Key::Escape)) && ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) && self.palette.is_none() {
|
||||
if crate::chrome::modal_key(&ctx, Key::Escape) && ctx.input(|i| i.viewport().fullscreen.unwrap_or(false)) && self.palette.is_none() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false));
|
||||
}
|
||||
self.file_drops(&ctx);
|
||||
@@ -979,6 +1048,8 @@ impl eframe::App for App {
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.dock)).show(ui, |ui| tabs::workspace(self, ui));
|
||||
|
||||
// Floating windows and modals.
|
||||
let prompt_open = !self.prompts.is_empty();
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("nexus-prompt-open"), prompt_open));
|
||||
self.quick.ui(&ctx, &mut self.s);
|
||||
self.settings.ui(&ctx, &mut self.s);
|
||||
self.keys.ui(&ctx, &mut self.s);
|
||||
@@ -993,6 +1064,11 @@ impl eframe::App for App {
|
||||
chrome::palette(self, &ctx);
|
||||
chrome::toasts(self, &ctx);
|
||||
self.screenshot(&ctx);
|
||||
self.drive_sync(&ctx);
|
||||
if self.screenshot.is_none() && self.s.prefs.restore_sessions && self.s.now - self.layout_checked > 1.0 {
|
||||
self.layout_checked = self.s.now;
|
||||
crate::restore::save_if_changed(self);
|
||||
}
|
||||
chrome::resize_edges(&ctx);
|
||||
// Requests raised while drawing are handled on the next frame.
|
||||
if !self.s.requests.is_empty() {
|
||||
|
||||
@@ -132,7 +132,7 @@ pub fn title_bar(app: &mut App, ui: &mut Ui) {
|
||||
if item(ui, icon::FOLDER_OPEN, "SFTP browser", "")
|
||||
&& let Some(f) = focused.clone()
|
||||
{
|
||||
app.sftp.toggle(&f);
|
||||
app.s.request(crate::state::Request::Sftp(f));
|
||||
}
|
||||
if item(ui, icon::ARROWS_LEFT_RIGHT, "Port forwards", "")
|
||||
&& let Some(f) = focused.clone()
|
||||
@@ -598,14 +598,14 @@ pub fn palette(app: &mut App, ctx: &egui::Context) {
|
||||
let matches: Vec<_> = matches.into_iter().map(|(_, c)| c).collect();
|
||||
pal.sel = pal.sel.min(matches.len().saturating_sub(1));
|
||||
let mut chosen = None;
|
||||
let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
|
||||
let mut close = crate::chrome::modal_key(ctx, Key::Escape);
|
||||
if ctx.input(|i| i.key_pressed(Key::ArrowDown)) {
|
||||
pal.sel = (pal.sel + 1).min(matches.len().saturating_sub(1));
|
||||
}
|
||||
if ctx.input(|i| i.key_pressed(Key::ArrowUp)) {
|
||||
pal.sel = pal.sel.saturating_sub(1);
|
||||
}
|
||||
if ctx.input(|i| i.key_pressed(Key::Enter)) {
|
||||
if crate::chrome::modal_key(ctx, Key::Enter) {
|
||||
chosen = matches.get(pal.sel).map(|m| m.0.clone());
|
||||
}
|
||||
modal_backdrop(ctx);
|
||||
@@ -677,6 +677,15 @@ pub fn modal(ctx: &egui::Context, id: &str, width: f32, body: impl FnOnce(&mut U
|
||||
});
|
||||
}
|
||||
|
||||
/// Set each frame while a credential or host-key prompt is on screen.
|
||||
const PROMPT_OPEN: &str = "nexus-prompt-open";
|
||||
|
||||
/// Enter/Escape for any modal except the prompts: while a prompt is showing it takes those keys,
|
||||
/// so one key press can't also confirm or dismiss the dialog underneath.
|
||||
pub fn modal_key(ctx: &egui::Context, key: Key) -> bool {
|
||||
!ctx.data(|d| d.get_temp::<bool>(egui::Id::new(PROMPT_OPEN)).unwrap_or(false)) && ctx.input(|i| i.key_pressed(key))
|
||||
}
|
||||
|
||||
pub fn prompts(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(p) = app.prompts.front_mut() else {
|
||||
return;
|
||||
@@ -781,7 +790,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
|
||||
return;
|
||||
};
|
||||
let t = Tokens::get(ctx);
|
||||
let esc = ctx.input(|i| i.key_pressed(Key::Escape));
|
||||
let esc = crate::chrome::modal_key(ctx, Key::Escape);
|
||||
let mut keep = !esc;
|
||||
match &mut d {
|
||||
Dialog::Reuse { profile, existing } => {
|
||||
@@ -835,7 +844,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
|
||||
ui.label(format!("{name} is still connected."));
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::primary(ui, icon::X, "Close").clicked() || ctx.input(|i| i.key_pressed(Key::Enter)) {
|
||||
if widgets::primary(ui, icon::X, "Close").clicked() || crate::chrome::modal_key(ctx, Key::Enter) {
|
||||
let id = session.clone();
|
||||
app.close_session(&id);
|
||||
keep = false;
|
||||
@@ -869,7 +878,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
|
||||
let r = ui.add(egui::TextEdit::singleline(name).desired_width(f32::INFINITY));
|
||||
r.request_focus();
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::primary(ui, icon::CHECK, "Rename").clicked() || ctx.input(|i| i.key_pressed(Key::Enter)) {
|
||||
if widgets::primary(ui, icon::CHECK, "Rename").clicked() || crate::chrome::modal_key(ctx, Key::Enter) {
|
||||
let n = name.trim().to_string();
|
||||
if !n.is_empty() {
|
||||
let _ = app.s.svc.sessions.rename(session, &n);
|
||||
@@ -943,7 +952,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
keep = false;
|
||||
}
|
||||
if ui.button("Cancel").clicked() || ctx.input(|i| i.key_pressed(Key::Escape)) {
|
||||
if ui.button("Cancel").clicked() || crate::chrome::modal_key(ctx, Key::Escape) {
|
||||
keep = false;
|
||||
}
|
||||
});
|
||||
@@ -1012,7 +1021,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
|
||||
let r = ui.add(egui::TextEdit::singleline(value).desired_width(f32::INFINITY));
|
||||
r.request_focus();
|
||||
ui.horizontal(|ui| {
|
||||
submit = widgets::primary(ui, icon::CHECK, "OK").clicked() || ctx.input(|i| i.key_pressed(Key::Enter));
|
||||
submit = widgets::primary(ui, icon::CHECK, "OK").clicked() || crate::chrome::modal_key(ctx, Key::Enter);
|
||||
if ui.button("Cancel").clicked() {
|
||||
keep = false;
|
||||
}
|
||||
@@ -1093,3 +1102,26 @@ pub fn toasts(app: &mut App, ctx: &egui::Context) {
|
||||
app.s.toasts.remove(i);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod modal_key_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_open_prompt_takes_enter_and_escape() {
|
||||
let ctx = egui::Context::default();
|
||||
let press = |key| egui::RawInput {
|
||||
events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }],
|
||||
..Default::default()
|
||||
};
|
||||
for (prompt_open, want) in [(false, true), (true, false)] {
|
||||
let mut got = None;
|
||||
let mut out = ctx.run_ui(press(Key::Enter), |ui| {
|
||||
ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(PROMPT_OPEN), prompt_open));
|
||||
got = Some(modal_key(ui.ctx(), Key::Enter));
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(got, Some(want), "prompt open: {prompt_open}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,7 +284,7 @@ impl DesktopView {
|
||||
self.buttons = 0;
|
||||
}
|
||||
|
||||
/// VNC: sets the remote clipboard. RDP (no clipboard channel yet): types the text.
|
||||
/// Makes `text` the remote desktop's clipboard contents.
|
||||
fn paste(&self, s: &mut Shared, text: &str) {
|
||||
match &self.client {
|
||||
Some(Remote::Vnc(c)) => {
|
||||
@@ -292,12 +292,7 @@ impl DesktopView {
|
||||
s.error(format!("Clipboard: {e}"));
|
||||
}
|
||||
}
|
||||
Some(Remote::Rdp(c)) => c.input(
|
||||
text.chars()
|
||||
.filter(|c| !c.is_control() || *c == '\n')
|
||||
.flat_map(|ch| [Operation::UnicodeKeyPressed(ch), Operation::UnicodeKeyReleased(ch)])
|
||||
.collect(),
|
||||
),
|
||||
Some(Remote::Rdp(c)) => c.set_clipboard(text.to_string()),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -421,12 +416,10 @@ impl DesktopView {
|
||||
let _ = c.request_full_update();
|
||||
}
|
||||
if !self.view_only {
|
||||
let tip = if self.protocol == Protocol::Rdp {
|
||||
"Type the local clipboard's text into the remote desktop"
|
||||
} else {
|
||||
"Send the local clipboard to the remote desktop"
|
||||
};
|
||||
if widgets::button(ui, icon::CLIPBOARD_TEXT, "Paste Clipboard").on_hover_text(tip).clicked() {
|
||||
if widgets::button(ui, icon::CLIPBOARD_TEXT, "Paste Clipboard")
|
||||
.on_hover_text("Send the local clipboard to the remote desktop")
|
||||
.clicked()
|
||||
{
|
||||
match arboard::Clipboard::new().and_then(|mut c| c.get_text()) {
|
||||
Ok(text) if !text.is_empty() => {
|
||||
self.paste(s, &text);
|
||||
@@ -453,6 +446,15 @@ impl DesktopView {
|
||||
resp.request_focus();
|
||||
}
|
||||
let focused = resp.has_focus();
|
||||
// RDP shares the clipboard both ways: offer the local text whenever the desktop gains focus.
|
||||
if focused
|
||||
&& !self.had_focus
|
||||
&& let Some(Remote::Rdp(c)) = &self.client
|
||||
&& let Ok(text) = arboard::Clipboard::new().and_then(|mut c| c.get_text())
|
||||
&& !text.is_empty()
|
||||
{
|
||||
c.set_clipboard(text);
|
||||
}
|
||||
if focused {
|
||||
ui.painter().rect_stroke(img, 0.0, egui::Stroke::new(1.0, Tokens::get(ui.ctx()).accent.gamma_multiply(0.6)), egui::StrokeKind::Outside);
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }));
|
||||
|
||||
@@ -73,7 +73,7 @@ impl Forwards {
|
||||
}
|
||||
};
|
||||
let t = Tokens::get(ctx);
|
||||
let mut keep = !ctx.input(|i| i.key_pressed(Key::Escape));
|
||||
let mut keep = !crate::chrome::modal_key(ctx, Key::Escape);
|
||||
let mut stop = None;
|
||||
let mut start = false;
|
||||
let f = &mut self.form;
|
||||
|
||||
@@ -8,10 +8,12 @@ mod desktop_view;
|
||||
mod forwards;
|
||||
mod github_view;
|
||||
mod irc_view;
|
||||
mod osc;
|
||||
mod profile_editor;
|
||||
mod quick_connect;
|
||||
mod raw_view;
|
||||
mod recordings;
|
||||
mod restore;
|
||||
mod settings;
|
||||
mod sftp;
|
||||
mod sidebar;
|
||||
@@ -33,6 +35,7 @@ use nexus_core::service::Service;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
harden_process();
|
||||
// A panic on a worker thread (a session's reader, a transfer) ends only that thread; say so in
|
||||
// the UI rather than letting the session just stop.
|
||||
let default_hook = std::panic::take_hook();
|
||||
@@ -114,6 +117,8 @@ fn main() -> eframe::Result {
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
init_logging(&svc.config.data_dir);
|
||||
tracing::info!(version = nexus_core::service::VERSION, "starting");
|
||||
let headless = opts.screenshot.is_some();
|
||||
let native = eframe::NativeOptions {
|
||||
persist_window: !headless,
|
||||
@@ -139,3 +144,40 @@ fn window_icon() -> egui::IconData {
|
||||
let img = image::load_from_memory(chrome::LOGO_PNG).map(|i| i.to_rgba8()).unwrap_or_default();
|
||||
egui::IconData { width: img.width(), height: img.height(), rgba: img.into_raw() }
|
||||
}
|
||||
|
||||
/// Diagnostics go to `nexus.log` in the data directory (rotated at 5 MiB), and to stderr too when
|
||||
/// RUST_LOG is set. RUST_LOG also sets the level (default: info for Nexus, warn for libraries).
|
||||
/// Connection lifecycle, host-key checks and errors are logged; credentials and terminal data never.
|
||||
fn init_logging(data_dir: &std::path::Path) {
|
||||
use tracing_subscriber::prelude::*;
|
||||
let path = data_dir.join("nexus.log");
|
||||
if std::fs::metadata(&path).is_ok_and(|m| m.len() > 5 << 20) {
|
||||
let _ = std::fs::rename(&path, data_dir.join("nexus.log.1"));
|
||||
}
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.create(true).append(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600);
|
||||
let file = opts.open(&path).ok().map(|f| tracing_subscriber::fmt::layer().with_ansi(false).with_writer(std::sync::Mutex::new(f)));
|
||||
let stderr = std::env::var_os("RUST_LOG").map(|_| tracing_subscriber::fmt::layer().with_writer(std::io::stderr));
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn,nexus_terminal=info,nexus_core=info"));
|
||||
let _ = tracing_subscriber::registry().with(filter).with(file).with(stderr).try_init();
|
||||
}
|
||||
|
||||
/// Release builds keep secrets out of core dumps and away from same-user debuggers: no core
|
||||
/// files, and on Linux the process is non-dumpable (also blocks ptrace attach by other processes
|
||||
/// of the same user). Debug builds skip this so they can still be debugged.
|
||||
fn harden_process() {
|
||||
if cfg!(debug_assertions) {
|
||||
return;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
// SAFETY: plain syscalls on this process with valid arguments; failure is harmless.
|
||||
unsafe {
|
||||
let none = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
|
||||
libc::setrlimit(libc::RLIMIT_CORE, &none);
|
||||
#[cfg(target_os = "linux")]
|
||||
libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
//! Finds the OSC sequences the VT parser ignores but Nexus uses: OSC 133 (shell integration
|
||||
//! marks: prompt, command, output, finished with exit status) and OSC 7 (the shell's working
|
||||
//! directory). Sequences may be split across reads, so the scanner keeps state between chunks.
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Osc {
|
||||
/// 133;A — a prompt starts.
|
||||
Prompt,
|
||||
/// 133;C — the command's output starts.
|
||||
Output,
|
||||
/// 133;D[;status] — the command finished.
|
||||
Finished(Option<i32>),
|
||||
/// 7;file://host/path
|
||||
Cwd { host: String, path: String },
|
||||
/// 1337;File=…;inline=1:<base64> (iTerm2 inline image): the decoded file bytes and the
|
||||
/// requested width/height arguments (cells, `Npx`, `N%` or `auto`).
|
||||
Image { data: Vec<u8>, width: String, height: String },
|
||||
}
|
||||
|
||||
/// Longest OSC body collected; longer ones (not ours) are dropped.
|
||||
const MAX_OSC: usize = 4096;
|
||||
/// Inline images are bigger: up to 16 MiB of base64.
|
||||
const MAX_IMAGE_OSC: usize = 16 << 20;
|
||||
const IMAGE_PREFIX: &[u8] = b"1337;File=";
|
||||
|
||||
fn limit(body: &[u8]) -> usize {
|
||||
if body.len() >= IMAGE_PREFIX.len() && body.starts_with(IMAGE_PREFIX) { MAX_IMAGE_OSC } else { MAX_OSC }
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum State {
|
||||
#[default]
|
||||
Idle,
|
||||
Esc,
|
||||
Body(Vec<u8>),
|
||||
BodyEsc(Vec<u8>),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct OscScanner {
|
||||
state: State,
|
||||
}
|
||||
|
||||
impl OscScanner {
|
||||
/// The sequences that complete in `bytes`, each with the offset just past its terminator.
|
||||
pub fn scan(&mut self, bytes: &[u8]) -> Vec<(usize, Osc)> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let state = std::mem::take(&mut self.state);
|
||||
self.state = match state {
|
||||
State::Idle => match bytes[i..].iter().position(|&b| b == 0x1b) {
|
||||
Some(p) => {
|
||||
i += p;
|
||||
State::Esc
|
||||
}
|
||||
None => {
|
||||
i = bytes.len();
|
||||
State::Idle
|
||||
}
|
||||
},
|
||||
State::Esc if bytes[i] == b']' => State::Body(Vec::new()),
|
||||
State::Esc => State::Idle,
|
||||
State::Body(mut b) => match bytes[i] {
|
||||
0x07 => {
|
||||
if let Some(osc) = parse(&b) {
|
||||
out.push((i + 1, osc));
|
||||
}
|
||||
State::Idle
|
||||
}
|
||||
0x1b => State::BodyEsc(b),
|
||||
c if b.len() < limit(&b) => {
|
||||
b.push(c);
|
||||
State::Body(b)
|
||||
}
|
||||
_ => State::Idle,
|
||||
},
|
||||
State::BodyEsc(b) if bytes[i] == b'\\' => {
|
||||
if let Some(osc) = parse(&b) {
|
||||
out.push((i + 1, osc));
|
||||
}
|
||||
State::Idle
|
||||
}
|
||||
// An ESC that doesn't end the OSC starts a new sequence.
|
||||
State::BodyEsc(_) => {
|
||||
// Re-examine this byte as the one after an ESC.
|
||||
self.state = State::Esc;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(body: &[u8]) -> Option<Osc> {
|
||||
let s = std::str::from_utf8(body).ok()?;
|
||||
if let Some(rest) = s.strip_prefix("133;") {
|
||||
let mut parts = rest.split(';');
|
||||
return match parts.next()? {
|
||||
"A" => Some(Osc::Prompt),
|
||||
"C" => Some(Osc::Output),
|
||||
"D" => Some(Osc::Finished(parts.next().and_then(|c| c.parse().ok()))),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if let Some(rest) = s.strip_prefix("1337;File=") {
|
||||
let (args, data) = rest.split_once(':')?;
|
||||
let arg = |k: &str| args.split(';').find_map(|a| a.strip_prefix(k)?.strip_prefix('=')).map(str::to_string);
|
||||
if arg("inline").as_deref() != Some("1") {
|
||||
return None;
|
||||
}
|
||||
use base64::Engine;
|
||||
let data = base64::engine::general_purpose::STANDARD.decode(data.trim()).ok()?;
|
||||
return Some(Osc::Image { data, width: arg("width").unwrap_or_default(), height: arg("height").unwrap_or_default() });
|
||||
}
|
||||
let url = s.strip_prefix("7;")?.strip_prefix("file://")?;
|
||||
let (host, path) = url.split_at(url.find('/')?);
|
||||
Some(Osc::Cwd { host: host.into(), path: percent_decode(path) })
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
match (b[i], b.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(std::str::from_utf8(h).ok()?, 16).ok())) {
|
||||
(b'%', Some(v)) => {
|
||||
out.push(v);
|
||||
i += 3;
|
||||
}
|
||||
(c, _) => {
|
||||
out.push(c);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_marks_and_cwd_even_when_split() {
|
||||
let stream = b"hi\x1b]133;A\x07$ ls\x1b]133;C\x1b\\file\x1b]133;D;2\x07\x1b]7;file://box/home/me/My%20Dir\x07\x1b]0;title\x07\x1b[31mred";
|
||||
let whole = OscScanner::default().scan(stream);
|
||||
let want = [Osc::Prompt, Osc::Output, Osc::Finished(Some(2)), Osc::Cwd { host: "box".into(), path: "/home/me/My Dir".into() }];
|
||||
assert_eq!(whole.iter().map(|(_, o)| o).collect::<Vec<_>>(), want.iter().collect::<Vec<_>>());
|
||||
assert_eq!(whole[0].0, 10, "offset is just past the terminator");
|
||||
// Byte by byte gives the same sequences at the same absolute offsets.
|
||||
let mut s = OscScanner::default();
|
||||
let mut split = vec![];
|
||||
for (i, b) in stream.iter().enumerate() {
|
||||
split.extend(s.scan(std::slice::from_ref(b)).into_iter().map(|(end, o)| (i + end, o)));
|
||||
}
|
||||
assert_eq!(split, whole);
|
||||
// Unterminated and oversized bodies don't leak into later output.
|
||||
let mut s = OscScanner::default();
|
||||
let mut long = b"\x1b]133;A".to_vec();
|
||||
long.extend(std::iter::repeat_n(b'x', MAX_OSC + 10));
|
||||
long.extend(b"\x07\x1b]133;D\x07");
|
||||
assert_eq!(s.scan(&long).into_iter().map(|(_, o)| o).collect::<Vec<_>>(), vec![Osc::Finished(None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_images_need_inline_1_and_valid_base64() {
|
||||
let img = |args: &str, data: &str| {
|
||||
let seq = format!("\x1b]1337;File={args}:{data}\x07");
|
||||
OscScanner::default().scan(seq.as_bytes()).into_iter().map(|(_, o)| o).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(img("name=eA==;width=10;inline=1", "aGk="), vec![Osc::Image { data: b"hi".to_vec(), width: "10".into(), height: String::new() }]);
|
||||
assert!(img("inline=0", "aGk=").is_empty(), "downloads (inline=0) are ignored");
|
||||
assert!(img("inline=1", "!!!").is_empty());
|
||||
// A large image body is collected, past the 4 KiB cap for other OSCs.
|
||||
use base64::Engine;
|
||||
let big = base64::engine::general_purpose::STANDARD.encode(vec![7u8; 100_000]);
|
||||
assert!(matches!(&img("inline=1", &big)[..], [Osc::Image { data, .. }] if data.len() == 100_000));
|
||||
}
|
||||
}
|
||||
@@ -691,6 +691,7 @@ impl ProfileEditor {
|
||||
if c.secret_mode == SecretMode::Saved {
|
||||
secret(ui, "Password", secrets, SecretKind::RdpPassword, "Leave blank to keep the saved password");
|
||||
}
|
||||
text(ui, "Kerberos KDC", &mut c.kerberos_kdc, "kdc.corp.example (empty: NTLM)");
|
||||
let opts: Vec<_> = HostKeyPolicy::ALL.iter().map(|k| (*k, k.label())).collect();
|
||||
combo(ui, "Certificate Policy", &mut c.host_key_policy, &opts);
|
||||
check(
|
||||
@@ -700,6 +701,35 @@ impl ProfileEditor {
|
||||
"Plain TLS logon, e.g. xrdp. Less secure: the session is set up before you authenticate.",
|
||||
);
|
||||
});
|
||||
section(ui, "Devices", |ui| {
|
||||
check(ui, "Play Remote Audio", &mut c.audio, "");
|
||||
check(ui, "Redirect Printer", &mut c.redirect_printer, "Adds a \"Nexus Terminal\" printer; jobs are saved as PostScript files in Downloads");
|
||||
if cfg!(unix) {
|
||||
label(ui, "Shared Folder");
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::button(ui, icon::FOLDER_OPEN, "Choose…").clicked()
|
||||
&& let Some(dir) = rfd::FileDialog::new().set_title("Folder to share with the remote desktop").pick_folder()
|
||||
{
|
||||
c.shared_folder = dir.to_string_lossy().into_owned();
|
||||
}
|
||||
if !c.shared_folder.is_empty() && ui.button("Stop Sharing").clicked() {
|
||||
c.shared_folder.clear();
|
||||
}
|
||||
});
|
||||
err(ui, errs, "rdp.sharedFolder");
|
||||
widgets::hint(
|
||||
ui,
|
||||
&if c.shared_folder.is_empty() {
|
||||
"Nothing is shared.".to_string()
|
||||
} else {
|
||||
format!(
|
||||
"{} appears on the remote desktop as a drive named Nexus; the server can read and change everything in it, and nothing outside it.",
|
||||
c.shared_folder
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
section(ui, "Display", |ui| {
|
||||
check(ui, "Scale to Fit", &mut c.scale_to_fit, "");
|
||||
num(ui, "Width (0 = fit tab)", &mut c.width, 0..=8192);
|
||||
@@ -710,6 +740,19 @@ impl ProfileEditor {
|
||||
check(ui, "Resize With Tab", &mut c.dynamic_resolution, "Ask the server to match the tab's size as it changes");
|
||||
}
|
||||
});
|
||||
section(ui, "RD Gateway", |ui| {
|
||||
text(ui, "Gateway", &mut c.gateway_host, "gateway.example.com (empty: none)");
|
||||
err(ui, errs, "rdp.gatewayHost");
|
||||
if !c.gateway_host.trim().is_empty() {
|
||||
text(ui, "Gateway Username", &mut c.gateway_username, "DOMAIN\\user");
|
||||
err(ui, errs, "rdp.gatewayUsername");
|
||||
mode(ui, "Gateway Password Storage", &mut c.gateway_secret_mode);
|
||||
if c.gateway_secret_mode == SecretMode::Saved {
|
||||
secret(ui, "Gateway Password", secrets, SecretKind::RdpGatewayPassword, "Leave blank to keep the saved password");
|
||||
}
|
||||
widgets::hint(ui, "Experimental: gateways that accept Basic authentication over HTTPS (the gateway's certificate is verified).");
|
||||
}
|
||||
});
|
||||
section(ui, "Proxy", |ui| {
|
||||
combo_s(ui, "Proxy Type", &mut c.proxy_type, &[("none", "None (direct connection)"), ("socks5", "SOCKS5"), ("http", "HTTP CONNECT")]);
|
||||
err(ui, errs, "rdp.proxyType");
|
||||
@@ -769,6 +812,19 @@ impl ProfileEditor {
|
||||
}
|
||||
}
|
||||
});
|
||||
section(ui, "SASL", |ui| {
|
||||
check(ui, "Log In with SASL", &mut c.sasl, "Authenticates during registration (SASL PLAIN), as most networks now expect");
|
||||
if c.sasl {
|
||||
text(ui, "SASL Account", &mut c.sasl_account, "Defaults to your nick");
|
||||
mode(ui, "SASL Password Storage", &mut c.sasl_mode);
|
||||
if c.sasl_mode == SecretMode::Saved {
|
||||
secret(ui, "SASL Password", secrets, SecretKind::IrcSaslPassword, "Leave blank to keep the saved password");
|
||||
}
|
||||
if !c.use_tls && !c.ssh_tunnel {
|
||||
widgets::hint(ui, "Without TLS or an SSH tunnel the password crosses the network in the clear.");
|
||||
}
|
||||
}
|
||||
});
|
||||
section(ui, "NickServ", |ui| {
|
||||
check(ui, "Identify on Connect", &mut c.nick_serv_identify, "");
|
||||
if c.nick_serv_identify {
|
||||
|
||||
@@ -84,7 +84,7 @@ impl QuickConnect {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get(ctx);
|
||||
let (enter, esc) = ctx.input(|i| (i.key_pressed(Key::Enter), i.key_pressed(Key::Escape)));
|
||||
let (enter, esc) = (crate::chrome::modal_key(ctx, Key::Enter), crate::chrome::modal_key(ctx, Key::Escape));
|
||||
let mut connect = enter;
|
||||
let mut close = esc;
|
||||
let label = |ui: &mut egui::Ui, l: &str| ui.label(RichText::new(l).color(t.text_dim).size(12.0));
|
||||
|
||||
@@ -266,7 +266,7 @@ impl Recordings {
|
||||
let Some(r) = &self.confirm_delete else {
|
||||
return;
|
||||
};
|
||||
let (mut yes, mut no) = (false, ctx.input(|i| i.key_pressed(Key::Escape)));
|
||||
let (mut yes, mut no) = (false, crate::chrome::modal_key(ctx, Key::Escape));
|
||||
let name = if r.title.is_empty() { r.id.clone() } else { r.title.clone() };
|
||||
crate::chrome::modal(ctx, "rec-delete", 380.0, |ui| {
|
||||
ui.label(RichText::new("Delete recording?").font(theme::semibold(15.0)));
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Reopens the previous run's tabs and splits at launch: saved profiles reconnect, local shells
|
||||
//! start again in the directory they were in. The layout is saved whenever it changes (not only on
|
||||
//! exit), so it survives a crash. Quick Connect tabs aren't restored (they have no saved profile).
|
||||
|
||||
use crate::app::App;
|
||||
use crate::splits::{Dir, Split};
|
||||
use crate::state::Tab;
|
||||
use nexus_core::models::Protocol;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
const KEY: &str = "session_layout";
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug, Default)]
|
||||
pub struct Saved {
|
||||
tabs: Vec<SavedTab>,
|
||||
active: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
struct SavedTab {
|
||||
name: String,
|
||||
pinned: bool,
|
||||
layout: Layout,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
enum Layout {
|
||||
Profile {
|
||||
id: String,
|
||||
},
|
||||
Local {
|
||||
shell: String,
|
||||
cwd: Option<PathBuf>,
|
||||
},
|
||||
/// A split pane still showing the connection picker, or a session that can't be restored.
|
||||
Empty,
|
||||
Split {
|
||||
down: bool,
|
||||
ratio: f32,
|
||||
a: Box<Layout>,
|
||||
b: Box<Layout>,
|
||||
},
|
||||
}
|
||||
|
||||
fn session_layout(app: &App, id: &str) -> Layout {
|
||||
let Some(pane) = app.s.pane(id) else { return Layout::Empty };
|
||||
if pane.info.protocol == Protocol::Local {
|
||||
let (shell, cwd) = app.s.svc.sessions.local_state(id).unwrap_or_default();
|
||||
return Layout::Local { shell, cwd };
|
||||
}
|
||||
match app.s.profile(&pane.info.profile_id) {
|
||||
Some(p) => Layout::Profile { id: p.id.clone() },
|
||||
None => Layout::Empty,
|
||||
}
|
||||
}
|
||||
|
||||
fn split_layout(app: &App, sp: &Split) -> Layout {
|
||||
match sp {
|
||||
Split::Leaf(Some(id)) => session_layout(app, id),
|
||||
Split::Leaf(None) => Layout::Empty,
|
||||
Split::Node { dir, ratio, a, b } => {
|
||||
Layout::Split { down: *dir == Dir::Down, ratio: *ratio, a: Box::new(split_layout(app, a)), b: Box::new(split_layout(app, b)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capture(app: &App) -> Saved {
|
||||
let tabs: Vec<SavedTab> = app
|
||||
.s
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let info = app.s.pane(&t.id).map(|p| (p.info.tab_name.clone(), p.info.pinned)).unwrap_or_default();
|
||||
let layout = match &t.split {
|
||||
Some(sp) => split_layout(app, sp),
|
||||
None => session_layout(app, &t.id),
|
||||
};
|
||||
SavedTab { name: info.0, pinned: info.1, layout }
|
||||
})
|
||||
.filter(|t| t.layout != Layout::Empty)
|
||||
.collect();
|
||||
let active = app.s.tabs.iter().position(|t| Some(&t.id) == app.s.active.as_ref()).unwrap_or(0);
|
||||
Saved { active: active.min(tabs.len().saturating_sub(1)), tabs }
|
||||
}
|
||||
|
||||
/// Saves the layout if it changed since the last save (called each frame; cheap for a few tabs).
|
||||
pub fn save_if_changed(app: &mut App) {
|
||||
let Ok(json) = serde_json::to_string(&capture(app)) else { return };
|
||||
if app.saved_layout.as_deref() != Some(&json) {
|
||||
let _ = app.s.svc.store.set_setting(KEY, &json);
|
||||
app.saved_layout = Some(json);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens one session for a layout leaf; returns its id.
|
||||
fn open(app: &mut App, l: &Layout) -> Option<String> {
|
||||
let id = match l {
|
||||
Layout::Profile { id } => app.s.svc.connect_profile(id).ok()?,
|
||||
Layout::Local { shell, cwd } => app.s.svc.connect_local_in(shell, cwd.clone()),
|
||||
_ => return None,
|
||||
};
|
||||
app.add_session(&id, false);
|
||||
Some(id)
|
||||
}
|
||||
|
||||
fn build(app: &mut App, l: &Layout) -> Split {
|
||||
match l {
|
||||
Layout::Split { down, ratio, a, b } => Split::Node {
|
||||
dir: if *down { Dir::Down } else { Dir::Right },
|
||||
ratio: ratio.clamp(0.1, 0.9),
|
||||
a: Box::new(build(app, a)),
|
||||
b: Box::new(build(app, b)),
|
||||
},
|
||||
leaf => Split::Leaf(open(app, leaf)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn restore(app: &mut App) {
|
||||
let Some(saved) = app.s.svc.store.setting(KEY).and_then(|j| serde_json::from_str::<Saved>(&j).ok()) else { return };
|
||||
let mut ids = vec![];
|
||||
for t in &saved.tabs {
|
||||
let (id, split) = match &t.layout {
|
||||
Layout::Split { .. } => {
|
||||
let sp = build(app, &t.layout);
|
||||
let Some(first) = sp.sessions().first().cloned() else { continue };
|
||||
(first, Some(sp))
|
||||
}
|
||||
leaf => match open(app, leaf) {
|
||||
Some(id) => (id, None),
|
||||
None => continue,
|
||||
},
|
||||
};
|
||||
if !t.name.is_empty() {
|
||||
let _ = app.s.svc.sessions.rename(&id, &t.name);
|
||||
if let Some(p) = app.s.pane_mut(&id) {
|
||||
p.info.tab_name = t.name.clone();
|
||||
}
|
||||
}
|
||||
if t.pinned {
|
||||
let _ = app.s.svc.sessions.pin(&id, true);
|
||||
if let Some(p) = app.s.pane_mut(&id) {
|
||||
p.info.pinned = true;
|
||||
}
|
||||
}
|
||||
app.s.tabs.push(Tab { id: id.clone(), activity: false, split });
|
||||
ids.push(id);
|
||||
}
|
||||
if let Some(id) = ids.get(saved.active).or(ids.first()) {
|
||||
app.s.active = Some(id.clone());
|
||||
app.s.focused = Some(id.clone());
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
app.s.info(format!("Restored {} tab(s) from last time", ids.len()));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layouts_round_trip() {
|
||||
let saved = Saved {
|
||||
active: 1,
|
||||
tabs: vec![
|
||||
SavedTab { name: "web".into(), pinned: true, layout: Layout::Profile { id: "p1".into() } },
|
||||
SavedTab {
|
||||
name: String::new(),
|
||||
pinned: false,
|
||||
layout: Layout::Split {
|
||||
down: true,
|
||||
ratio: 0.3,
|
||||
a: Box::new(Layout::Local { shell: "/bin/zsh".into(), cwd: Some("/tmp".into()) }),
|
||||
b: Box::new(Layout::Empty),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
let json = serde_json::to_string(&saved).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Saved>(&json).unwrap(), saved);
|
||||
}
|
||||
}
|
||||
@@ -88,11 +88,16 @@ pub fn strength_meter(ui: &mut Ui, pw: &str) {
|
||||
/// Create or unlock the vault.
|
||||
struct MasterPrompt {
|
||||
new: bool,
|
||||
/// Changing the password: the current one (re-encrypts the vault under `pw`).
|
||||
change: Option<String>,
|
||||
pw: String,
|
||||
confirm: String,
|
||||
error: String,
|
||||
}
|
||||
|
||||
/// (profile id, profile name, kind, "keychain"/"vault") per stored credential.
|
||||
type Credentials = Vec<(String, String, nexus_core::secrets::SecretKind, &'static str)>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Settings {
|
||||
open: bool,
|
||||
@@ -102,6 +107,11 @@ pub struct Settings {
|
||||
prefs: AppPreferences,
|
||||
theme: ThemeKind,
|
||||
known: Vec<KnownHost>,
|
||||
/// Add-CA form: (host pattern, public key), shown when Some.
|
||||
new_ca: Option<(String, String)>,
|
||||
sync_password: String,
|
||||
creds: Option<Credentials>,
|
||||
creds_job: Option<Job<Credentials>>,
|
||||
default_shell: String,
|
||||
help_topic: usize,
|
||||
master: Option<MasterPrompt>,
|
||||
@@ -114,6 +124,7 @@ impl Settings {
|
||||
pub fn open(&mut self, tab: SettingsTab) {
|
||||
self.open = true;
|
||||
self.fresh = true;
|
||||
self.creds = None;
|
||||
self.tab = tab;
|
||||
}
|
||||
|
||||
@@ -152,6 +163,7 @@ impl Settings {
|
||||
SettingsTab::Terminal => self.terminal(ui),
|
||||
SettingsTab::Security => self.security(ui, s),
|
||||
SettingsTab::KnownHosts => self.known_hosts(ui, s),
|
||||
SettingsTab::Diagnostics => self.diagnostics(ui, s),
|
||||
SettingsTab::Help => self.help(ui),
|
||||
SettingsTab::About => self.about(ui, s),
|
||||
}
|
||||
@@ -207,6 +219,7 @@ impl Settings {
|
||||
(SettingsTab::Terminal, icon::TERMINAL_WINDOW, "Terminal"),
|
||||
(SettingsTab::Security, icon::SHIELD_CHECK, "Security"),
|
||||
(SettingsTab::KnownHosts, icon::FINGERPRINT, "Known Hosts"),
|
||||
(SettingsTab::Diagnostics, icon::STETHOSCOPE, "Diagnostics"),
|
||||
(SettingsTab::Help, icon::BOOK_OPEN, "Help"),
|
||||
(SettingsTab::About, icon::INFO, "About"),
|
||||
] {
|
||||
@@ -249,6 +262,9 @@ impl Settings {
|
||||
field(ui, "Confirm on disconnect");
|
||||
ui.checkbox(&mut p.confirm_on_disconnect, "Ask before disconnecting sessions");
|
||||
ui.end_row();
|
||||
field(ui, "Restore tabs");
|
||||
ui.checkbox(&mut p.restore_sessions, "Reopen last session's tabs and splits at launch");
|
||||
ui.end_row();
|
||||
field(ui, "Remote clipboard");
|
||||
ui.checkbox(&mut p.allow_remote_clipboard, "Let remote hosts set the clipboard (OSC 52, VNC)");
|
||||
ui.end_row();
|
||||
@@ -365,17 +381,131 @@ impl Settings {
|
||||
ui.label("Working…");
|
||||
} else if !init {
|
||||
if widgets::primary(ui, icon::SHIELD_PLUS, "Initialise Secret Store").clicked() {
|
||||
self.master = Some(MasterPrompt { new: true, pw: String::new(), confirm: String::new(), error: String::new() });
|
||||
self.master = Some(MasterPrompt { new: true, change: None, pw: String::new(), confirm: String::new(), error: String::new() });
|
||||
}
|
||||
} else if !unlocked {
|
||||
if widgets::primary(ui, icon::LOCK_OPEN, "Unlock").clicked() {
|
||||
self.master = Some(MasterPrompt { new: false, pw: String::new(), confirm: String::new(), error: String::new() });
|
||||
self.master = Some(MasterPrompt { new: false, change: None, pw: String::new(), confirm: String::new(), error: String::new() });
|
||||
}
|
||||
} else if widgets::button(ui, icon::LOCK, "Lock").clicked() {
|
||||
s.svc.secrets.vault.lock();
|
||||
s.info("Secret store locked");
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::button(ui, icon::LOCK, "Lock").clicked() {
|
||||
s.svc.secrets.vault.lock();
|
||||
s.info("Secret store locked");
|
||||
}
|
||||
if widgets::button(ui, icon::KEY, "Change Master Password…").clicked() {
|
||||
self.master =
|
||||
Some(MasterPrompt { new: true, change: Some(String::new()), pw: String::new(), confirm: String::new(), error: String::new() });
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
self.credentials_section(ui, s);
|
||||
self.sync_section(ui, s);
|
||||
}
|
||||
|
||||
/// Stored credentials per profile, with Forget. Loaded in the background (keychain probes).
|
||||
fn credentials_section(&mut self, ui: &mut Ui, s: &mut Shared) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.add_space(12.0);
|
||||
widgets::section(ui, "Stored credentials");
|
||||
if let Some(list) = poll(&mut self.creds_job) {
|
||||
self.creds = Some(list);
|
||||
}
|
||||
if self.creds.is_none() && self.creds_job.is_none() {
|
||||
let svc = s.svc.clone();
|
||||
self.creds_job = Some(Job::spawn(ui.ctx(), move || svc.credential_inventory()));
|
||||
}
|
||||
let Some(list) = &self.creds else {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui.label("Checking the keychain and vault…");
|
||||
});
|
||||
return;
|
||||
};
|
||||
if list.is_empty() {
|
||||
widgets::hint(ui, "No saved credentials (the vault must be unlocked to see what it holds).");
|
||||
return;
|
||||
}
|
||||
let mut forget = None;
|
||||
egui::Grid::new("stored-creds").num_columns(4).striped(true).spacing(vec2(14.0, 5.0)).show(ui, |ui| {
|
||||
for (id, name, kind, at) in list {
|
||||
ui.label(name);
|
||||
ui.label(RichText::new(kind.as_str()).font(theme::mono(11.5)));
|
||||
ui.label(RichText::new(*at).color(t.text_dim));
|
||||
if ui.button(RichText::new(format!("{} Forget", icon::TRASH)).color(t.danger)).clicked() {
|
||||
forget = Some((id.clone(), *kind));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
if let Some((id, kind)) = forget {
|
||||
s.svc.forget_credential(&id, kind);
|
||||
s.success(format!("Forgot the {} credential", kind.as_str()));
|
||||
self.creds = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_section(&mut self, ui: &mut Ui, s: &mut Shared) {
|
||||
ui.add_space(12.0);
|
||||
widgets::section(ui, "Profile sync");
|
||||
widgets::hint(
|
||||
ui,
|
||||
"Keep connection profiles in step across machines through a folder they share (a cloud drive, a network share, a git checkout). \
|
||||
Profiles are stored there encrypted with the sync password; passwords and keys are never synced.",
|
||||
);
|
||||
form(ui, "sync-form", |ui| {
|
||||
field(ui, "Folder");
|
||||
ui.horizontal(|ui| {
|
||||
let shown = if self.prefs.sync_folder.is_empty() { "Not set".to_string() } else { self.prefs.sync_folder.clone() };
|
||||
ui.label(RichText::new(shown).font(theme::mono(12.0)));
|
||||
if widgets::button(ui, icon::FOLDER_OPEN, "Choose…").clicked()
|
||||
&& let Some(dir) = rfd::FileDialog::new().set_title("Folder to sync profiles through").pick_folder()
|
||||
{
|
||||
self.set_sync_folder(s, dir.to_string_lossy().into_owned());
|
||||
}
|
||||
if !self.prefs.sync_folder.is_empty() && ui.button("Turn Off").clicked() {
|
||||
self.set_sync_folder(s, String::new());
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
field(ui, "Sync password");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut self.sync_password)
|
||||
.password(true)
|
||||
.hint_text(if s.svc.has_sync_password() { "Stored — type to replace" } else { "Same on every machine" })
|
||||
.desired_width(220.0),
|
||||
);
|
||||
if ui.add_enabled(!self.sync_password.is_empty(), egui::Button::new("Save")).clicked() {
|
||||
match s.svc.set_sync_password(&self.sync_password) {
|
||||
Ok(()) => s.success("Sync password stored"),
|
||||
Err(e) => s.error(format!("Couldn't store the sync password: {e}")),
|
||||
}
|
||||
self.sync_password.clear();
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
field(ui, "");
|
||||
if widgets::button(ui, icon::ARROWS_CLOCKWISE, "Sync Now").clicked() {
|
||||
s.request(Request::SyncProfiles);
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
|
||||
/// Saves just the sync folder (the rest of the form keeps its unsaved edits).
|
||||
fn set_sync_folder(&mut self, s: &mut Shared, folder: String) {
|
||||
let mut stored = s.svc.preferences();
|
||||
stored.sync_folder = folder.clone();
|
||||
match s.svc.save_preferences(&stored) {
|
||||
Ok(()) => {
|
||||
self.prefs.sync_folder = folder.clone();
|
||||
s.prefs.sync_folder = folder;
|
||||
s.request(Request::SyncProfiles);
|
||||
}
|
||||
Err(e) => s.error(format!("Failed to save: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn master_dialog(&mut self, ctx: &egui::Context, s: &mut Shared) {
|
||||
@@ -384,17 +514,29 @@ impl Settings {
|
||||
let mut cancel = false;
|
||||
let r = egui::Modal::new(egui::Id::new("master-password")).show(ctx, |ui| {
|
||||
ui.set_width(380.0);
|
||||
let title = if m.new { "Create Master Password" } else { "Unlock Secret Store" };
|
||||
let title = if m.change.is_some() {
|
||||
"Change Master Password"
|
||||
} else if m.new {
|
||||
"Create Master Password"
|
||||
} else {
|
||||
"Unlock Secret Store"
|
||||
};
|
||||
ui.label(RichText::new(format!("{} {title}", icon::KEY)).font(theme::semibold(15.0)));
|
||||
ui.label(if m.new {
|
||||
ui.label(if m.change.is_some() {
|
||||
"Every saved credential is re-encrypted under the new password."
|
||||
} else if m.new {
|
||||
"Choose a strong master password. This protects all saved credentials."
|
||||
} else {
|
||||
"Enter your master password to unlock the secret store."
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.label("Master password");
|
||||
if let Some(old) = &mut m.change {
|
||||
ui.label("Current password");
|
||||
ui.add(egui::TextEdit::singleline(old).password(true).desired_width(f32::INFINITY));
|
||||
}
|
||||
ui.label(if m.change.is_some() { "New password" } else { "Master password" });
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut m.pw).password(true).hint_text("Password…").desired_width(f32::INFINITY));
|
||||
if !r.has_focus() && m.pw.is_empty() && m.confirm.is_empty() {
|
||||
if m.change.is_none() && !r.has_focus() && m.pw.is_empty() && m.confirm.is_empty() {
|
||||
r.request_focus();
|
||||
}
|
||||
let mut enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
@@ -409,7 +551,14 @@ impl Settings {
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
submit = widgets::primary(ui, icon::CHECK, if m.new { "Create" } else { "Unlock" }).clicked() || enter;
|
||||
let label = if m.change.is_some() {
|
||||
"Change"
|
||||
} else if m.new {
|
||||
"Create"
|
||||
} else {
|
||||
"Unlock"
|
||||
};
|
||||
submit = widgets::primary(ui, icon::CHECK, label).clicked() || enter;
|
||||
cancel = ui.button("Cancel").clicked();
|
||||
});
|
||||
});
|
||||
@@ -419,11 +568,13 @@ impl Settings {
|
||||
} else if m.new && m.pw != m.confirm {
|
||||
m.error = "Passwords do not match.".into();
|
||||
} else {
|
||||
let (new, pw) = (m.new, std::mem::take(&mut m.pw));
|
||||
let (new, pw, change) = (m.new, std::mem::take(&mut m.pw), m.change.take());
|
||||
let svc = s.svc.clone();
|
||||
self.vault_job = Some(Job::spawn(ctx, move || {
|
||||
let v = &svc.secrets.vault;
|
||||
if new {
|
||||
if let Some(old) = change {
|
||||
v.change_password(&old, &pw).map(|_| "Master password changed").map_err(|e| format!("Couldn't change the master password: {e}"))
|
||||
} else if new {
|
||||
v.initialise(&pw).map(|_| "Secret store created").map_err(|e| format!("Failed to initialise: {e}"))
|
||||
} else {
|
||||
v.unlock(&pw).map(|_| "Secret store unlocked").map_err(|e| format!("Unlock failed: {e}"))
|
||||
@@ -441,6 +592,58 @@ impl Settings {
|
||||
|
||||
fn known_hosts(&mut self, ui: &mut Ui, s: &mut Shared) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::button(ui, icon::DOWNLOAD_SIMPLE, "Import ~/.ssh/known_hosts").clicked() {
|
||||
match s.svc.import_known_hosts(None) {
|
||||
Ok((n, ca, skipped)) => {
|
||||
let extra = if skipped > 0 { format!(" ({skipped} hashed or unsupported line(s) skipped)") } else { String::new() };
|
||||
s.success(format!("Imported {n} host key(s) and {ca} certificate authorit{}{extra}", if ca == 1 { "y" } else { "ies" }));
|
||||
self.known = s.svc.known_hosts();
|
||||
}
|
||||
Err(e) => s.error(format!("Import failed: {e}")),
|
||||
}
|
||||
}
|
||||
if widgets::button(ui, icon::UPLOAD_SIMPLE, "Export…").clicked()
|
||||
&& let Some(path) = rfd::FileDialog::new().set_file_name("known_hosts").save_file()
|
||||
{
|
||||
match s.svc.export_known_hosts(&path) {
|
||||
Ok(n) => s.success(format!("Wrote {n} line(s) to {}", path.display())),
|
||||
Err(e) => s.error(format!("Export failed: {e}")),
|
||||
}
|
||||
}
|
||||
if widgets::button(ui, icon::SEAL_CHECK, "Trust a CA…").on_hover_text("Trust SSH host certificates signed by a certificate authority").clicked() {
|
||||
self.new_ca = Some(Default::default());
|
||||
}
|
||||
});
|
||||
let (mut done, mut added) = (false, false);
|
||||
if let Some((pattern, key)) = &mut self.new_ca {
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.label(RichText::new("Trust an SSH certificate authority").font(theme::semibold(13.0)));
|
||||
widgets::hint(ui, "Servers whose host certificate this CA signed are trusted without a first-use prompt. Patterns use OpenSSH syntax: *.example.com, [host]:2222, !exclude.");
|
||||
ui.add(egui::TextEdit::singleline(pattern).hint_text("*.example.com").desired_width(320.0));
|
||||
ui.add(egui::TextEdit::multiline(key).hint_text("ssh-ed25519 AAAA… (the CA's public key)").desired_rows(2).desired_width(f32::INFINITY));
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::primary(ui, icon::CHECK, "Trust").clicked() {
|
||||
match s.svc.add_cert_authority(pattern, key) {
|
||||
Ok(()) => {
|
||||
s.success("Certificate authority trusted");
|
||||
(done, added) = (true, true);
|
||||
}
|
||||
Err(e) => s.error(e.to_string()),
|
||||
}
|
||||
} else if ui.button("Cancel").clicked() {
|
||||
done = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if done {
|
||||
self.new_ca = None;
|
||||
}
|
||||
if added {
|
||||
self.known = s.svc.known_hosts();
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
if self.known.is_empty() {
|
||||
widgets::empty(ui, icon::FINGERPRINT, "No known hosts recorded", "Host keys are recorded the first time you connect over SSH.");
|
||||
return;
|
||||
@@ -459,7 +662,7 @@ impl Settings {
|
||||
ui.end_row();
|
||||
for kh in &self.known {
|
||||
ui.label(&kh.host);
|
||||
ui.label(kh.port.to_string());
|
||||
ui.label(if kh.port == 0 { "—".to_string() } else { kh.port.to_string() });
|
||||
ui.label(RichText::new(&kh.key_type).font(theme::mono(11.5)));
|
||||
let short: String = kh.fingerprint.chars().take(24).collect();
|
||||
let fp = ui.add(egui::Label::new(RichText::new(format!("{short}…")).font(theme::mono(11.5))).sense(egui::Sense::click()));
|
||||
@@ -486,6 +689,68 @@ impl Settings {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Diagnostics ----------------------------------------------------------------------
|
||||
|
||||
/// What a bug report needs, without secrets: versions, paths, storage and sync status.
|
||||
fn diagnostics_report(s: &Shared) -> Vec<(&'static str, String)> {
|
||||
let cfg = &s.svc.config;
|
||||
let size = |p: &std::path::Path| std::fs::metadata(p).map_or("—".to_string(), |m| widgets::human_size(m.len()));
|
||||
let sec = &s.svc.secrets;
|
||||
let known = s.svc.known_hosts();
|
||||
let cas = known.iter().filter(|k| k.key_type == nexus_core::known_hosts::CA_KEY_TYPE).count();
|
||||
let yes = |b: bool| if b { "yes" } else { "no" }.to_string();
|
||||
vec![
|
||||
("Version", nexus_core::service::VERSION.to_string()),
|
||||
("Platform", format!("{} {}", std::env::consts::OS, std::env::consts::ARCH)),
|
||||
("Data folder", cfg.data_dir.display().to_string()),
|
||||
("Database", format!("{} ({})", cfg.db_path.display(), size(&cfg.db_path))),
|
||||
("Log", format!("{} ({})", cfg.data_dir.join("nexus.log").display(), size(&cfg.data_dir.join("nexus.log")))),
|
||||
("Recordings", cfg.recordings_dir.display().to_string()),
|
||||
("OS keychain", if sec.keychain_ok { "available".into() } else { "unavailable — credentials go to the vault".into() }),
|
||||
(
|
||||
"Vault",
|
||||
match (sec.vault.is_initialised(), sec.vault.is_unlocked()) {
|
||||
(false, _) => "not set up".into(),
|
||||
(true, false) => "locked".into(),
|
||||
(true, true) => format!("unlocked, {} entr{}", sec.vault.keys().len(), if sec.vault.keys().len() == 1 { "y" } else { "ies" }),
|
||||
},
|
||||
),
|
||||
("Profiles", s.profiles.len().to_string()),
|
||||
("Known hosts", format!("{} ({cas} SSH certificate authorit{})", known.len() - cas, if cas == 1 { "y" } else { "ies" })),
|
||||
("Open sessions", s.panes.len().to_string()),
|
||||
(
|
||||
"Profile sync",
|
||||
if s.prefs.sync_folder.is_empty() {
|
||||
"off".into()
|
||||
} else {
|
||||
format!("{} (password stored: {})", s.prefs.sync_folder, yes(s.svc.has_sync_password()))
|
||||
},
|
||||
),
|
||||
("Update check at launch", yes(s.prefs.check_for_updates)),
|
||||
("Restore tabs", yes(s.prefs.restore_sessions)),
|
||||
]
|
||||
}
|
||||
|
||||
fn diagnostics(&mut self, ui: &mut Ui, s: &mut Shared) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let report = Self::diagnostics_report(s);
|
||||
widgets::hint(ui, "Useful when reporting a problem. It contains paths and counts, never credentials.");
|
||||
ui.add_space(4.0);
|
||||
egui::Grid::new("diagnostics").num_columns(2).striped(true).spacing(vec2(16.0, 6.0)).show(ui, |ui| {
|
||||
for (k, v) in &report {
|
||||
ui.label(RichText::new(*k).color(t.text_dim));
|
||||
ui.add(egui::Label::new(RichText::new(v).font(theme::mono(12.0))).wrap());
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
if widgets::button(ui, icon::COPY, "Copy Diagnostics").clicked() {
|
||||
let text: String = report.iter().map(|(k, v)| format!("{k}: {v}\n")).collect();
|
||||
ui.ctx().copy_text(text);
|
||||
s.success("Diagnostics copied");
|
||||
}
|
||||
}
|
||||
|
||||
// --- Help -----------------------------------------------------------------------------
|
||||
|
||||
fn help(&mut self, ui: &mut Ui) {
|
||||
@@ -836,7 +1101,7 @@ TOTP secrets for SSH two-factor authentication are stored alongside your other c
|
||||
## Known Hosts
|
||||
When you connect to an SSH server for the first time, Nexus Terminal records the server's fingerprint. If the fingerprint changes on a later connection, you'll be warned — this protects against man-in-the-middle attacks.
|
||||
|
||||
You can review and remove known hosts in **Settings → Known Hosts**.
|
||||
You can review and remove known hosts in **Settings → Known Hosts**, import or export them in OpenSSH known_hosts format, and trust SSH certificate authorities for host patterns.
|
||||
## Encrypted Export
|
||||
When exporting profiles, encrypted export (a `.nexus` file) protects the file with a password, using the same AES-256-GCM encryption as the vault.",
|
||||
),
|
||||
|
||||
@@ -109,6 +109,8 @@ pub struct Sftp {
|
||||
/// Profile id (or host:port for quick connects) → bookmarked paths. Loaded on first use.
|
||||
bookmarks: Option<BTreeMap<String, Vec<String>>>,
|
||||
inbox: Arc<Mutex<Vec<Done>>>,
|
||||
/// Where a browser opened from a terminal should start: the directory its shell reported.
|
||||
start_at: HashMap<String, String>,
|
||||
}
|
||||
|
||||
// --- path helpers ---------------------------------------------------------------------------
|
||||
@@ -215,11 +217,16 @@ fn state_line(ui: &mut Ui, loading: bool, error: Option<&str>) -> bool {
|
||||
}
|
||||
|
||||
impl Sftp {
|
||||
pub fn toggle(&mut self, session: &str) {
|
||||
/// Opens (or closes) the browser for `session`; `at` is the shell's reported directory, which
|
||||
/// the browser goes to when it opens.
|
||||
pub fn toggle(&mut self, session: &str, at: Option<String>) {
|
||||
if self.open_for.as_deref() == Some(session) {
|
||||
self.close(session);
|
||||
} else {
|
||||
self.open_for = Some(session.into());
|
||||
if let Some(dir) = at.filter(|d| d.starts_with('/')) {
|
||||
self.start_at.insert(session.into(), dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,7 +495,11 @@ impl Sftp {
|
||||
let Some(session) = self.open_for.clone() else {
|
||||
return;
|
||||
};
|
||||
if !self.panels.contains_key(&session) {
|
||||
if let Some(dir) = self.start_at.remove(&session) {
|
||||
if self.panels.get(&session).is_none_or(|p| p.cwd != dir) {
|
||||
self.navigate(s, &session, Some(dir));
|
||||
}
|
||||
} else if !self.panels.contains_key(&session) {
|
||||
self.navigate(s, &session, None);
|
||||
}
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -772,8 +783,8 @@ impl Sftp {
|
||||
return;
|
||||
};
|
||||
let t = Tokens::get(ctx);
|
||||
let esc = ctx.input(|i| i.key_pressed(Key::Escape));
|
||||
let enter = ctx.input(|i| i.key_pressed(Key::Enter));
|
||||
let esc = crate::chrome::modal_key(ctx, Key::Escape);
|
||||
let enter = crate::chrome::modal_key(ctx, Key::Enter);
|
||||
let mut keep = !esc;
|
||||
match &mut d {
|
||||
Dialog::Input { session, kind, value } => {
|
||||
@@ -961,7 +972,7 @@ impl Sftp {
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.input(|i| i.key_pressed(Key::Enter)) && writable && !target.is_empty() {
|
||||
if crate::chrome::modal_key(ctx, Key::Enter) && writable && !target.is_empty() {
|
||||
chosen = Some(target.clone());
|
||||
}
|
||||
if back && pk.filter.is_empty() && !pk.cwd.is_empty() && pk.cwd != "/" {
|
||||
|
||||
@@ -291,7 +291,7 @@ impl Snippets {
|
||||
|
||||
fn var_form(&mut self, ctx: &egui::Context, s: &mut Shared) {
|
||||
let Some(f) = &mut self.vars else { return };
|
||||
let (mut send, mut cancel) = (false, ctx.input(|i| i.key_pressed(Key::Escape)));
|
||||
let (mut send, mut cancel) = (false, crate::chrome::modal_key(ctx, Key::Escape));
|
||||
crate::chrome::modal(ctx, "snippet-vars", 360.0, |ui| {
|
||||
ui.label(RichText::new("Snippet Variables").font(theme::semibold(15.0)));
|
||||
ui.add_space(4.0);
|
||||
@@ -304,7 +304,7 @@ impl Snippets {
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
send = widgets::primary(ui, icon::PAPER_PLANE_RIGHT, "Send").clicked() || ui.input(|i| i.key_pressed(Key::Enter));
|
||||
send = widgets::primary(ui, icon::PAPER_PLANE_RIGHT, "Send").clicked() || crate::chrome::modal_key(ui.ctx(), Key::Enter);
|
||||
cancel |= ui.button("Cancel").clicked();
|
||||
});
|
||||
});
|
||||
@@ -322,7 +322,7 @@ impl Snippets {
|
||||
return;
|
||||
};
|
||||
let name = self.list.iter().find(|x| x.id == id).map(|x| x.name.clone()).unwrap_or_default();
|
||||
let (mut yes, mut no) = (false, ctx.input(|i| i.key_pressed(Key::Escape)));
|
||||
let (mut yes, mut no) = (false, crate::chrome::modal_key(ctx, Key::Escape));
|
||||
crate::chrome::modal(ctx, "snippet-delete", 360.0, |ui| {
|
||||
ui.label(RichText::new("Delete snippet?").font(theme::semibold(15.0)));
|
||||
ui.label(format!("\u{201c}{name}\u{201d} will be permanently deleted."));
|
||||
|
||||
@@ -10,6 +10,8 @@ use std::sync::Arc;
|
||||
/// Things a feature asks the main window to do (handled once per frame, in order).
|
||||
#[allow(clippy::large_enum_variant)] // a per-frame queue; boxing buys nothing
|
||||
pub enum Request {
|
||||
/// Merge profiles with the sync folder (manual, or after a change).
|
||||
SyncProfiles,
|
||||
/// Open the profile editor for a new profile (optionally pre-set protocol / folder).
|
||||
NewProfile {
|
||||
protocol: Option<Protocol>,
|
||||
@@ -38,6 +40,7 @@ pub enum SettingsTab {
|
||||
Terminal,
|
||||
Security,
|
||||
KnownHosts,
|
||||
Diagnostics,
|
||||
Help,
|
||||
About,
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ fn empty_state(app: &mut App, ui: &mut Ui) {
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add(egui::Image::new(&crate::chrome::logo(ui.ctx())).fit_to_exact_size(vec2(84.0, 84.0)));
|
||||
ui.label(RichText::new("Nexus Terminal").font(theme::semibold(28.0)));
|
||||
ui.label(RichText::new("SSH · Telnet · RAW · Serial · VNC · IRC · GitHub").color(t.text_dim));
|
||||
ui.label(RichText::new("SSH · Telnet · RAW · Serial · VNC · RDP · IRC · GitHub").color(t.text_dim));
|
||||
ui.add_space(18.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space((ui.available_width() - 330.0).max(0.0) / 2.0);
|
||||
|
||||
@@ -40,6 +40,9 @@ pub enum MenuAction {
|
||||
Export,
|
||||
Clear,
|
||||
Reset,
|
||||
PrevPrompt,
|
||||
NextPrompt,
|
||||
CopyOutput,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -107,8 +110,47 @@ pub struct TermView {
|
||||
focus_requested: bool,
|
||||
/// Hold back multi-line pastes that would run unbracketed (set from preferences each frame).
|
||||
pub confirm_paste: bool,
|
||||
osc: crate::osc::OscScanner,
|
||||
/// Shell-integration prompts (OSC 133), oldest first.
|
||||
prompts: Vec<PromptMark>,
|
||||
/// Lines rotated out of a full scrollback since start, so marks keep pointing at their text.
|
||||
rotated: i64,
|
||||
max_history: usize,
|
||||
/// The working directory the shell last reported (OSC 7): (host, path).
|
||||
pub reported_cwd: Option<(String, String)>,
|
||||
/// Inline images (iTerm2 OSC 1337), oldest first.
|
||||
images: Vec<InlineImage>,
|
||||
/// Cell size in points from the last frame, for sizing images that arrive between frames.
|
||||
cell_px: (f32, f32),
|
||||
}
|
||||
|
||||
struct InlineImage {
|
||||
stable: i64,
|
||||
col: usize,
|
||||
cols: usize,
|
||||
rows: usize,
|
||||
pixels: Option<egui::ColorImage>,
|
||||
texture: Option<egui::TextureHandle>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// Pixels of inline images kept per terminal; the oldest go first.
|
||||
const MAX_IMAGE_PIXELS: usize = 32 << 20;
|
||||
|
||||
/// One command as shell integration reported it. Lines are stable indexes (see `stable`).
|
||||
#[derive(Clone, Debug)]
|
||||
struct PromptMark {
|
||||
prompt: i64,
|
||||
output: Option<i64>,
|
||||
end: Option<i64>,
|
||||
exit: Option<i32>,
|
||||
started: Option<std::time::Instant>,
|
||||
duration: Option<std::time::Duration>,
|
||||
}
|
||||
|
||||
/// Marks kept per terminal; older ones are dropped.
|
||||
const MAX_PROMPTS: usize = 5000;
|
||||
|
||||
const URL_RE: &str = r#"(?:https?|ftp)://[^\s<>"'`]+[^\s<>"'`.,;:!?)\]]"#;
|
||||
|
||||
fn rgb(c: [u8; 4]) -> Color32 {
|
||||
@@ -135,14 +177,207 @@ impl TermView {
|
||||
find: None,
|
||||
focus_requested: true,
|
||||
confirm_paste: false,
|
||||
osc: Default::default(),
|
||||
prompts: Vec::new(),
|
||||
rotated: 0,
|
||||
max_history: scrollback.min(100_000),
|
||||
reported_cwd: None,
|
||||
images: Vec::new(),
|
||||
cell_px: (8.0, 16.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn feed(&mut self, bytes: &[u8]) {
|
||||
self.parser.advance(&mut self.term, bytes);
|
||||
let mut start = 0;
|
||||
for (end, osc) in self.osc.scan(bytes) {
|
||||
self.advance(&bytes[start..end]);
|
||||
start = end;
|
||||
self.apply_osc(osc);
|
||||
}
|
||||
self.advance(&bytes[start..]);
|
||||
self.generation += 1;
|
||||
}
|
||||
|
||||
/// Feeds the VT parser, counting lines a full scrollback rotates out (one per line feed at the
|
||||
/// bottom of the screen) so shell-integration marks stay on their lines.
|
||||
fn advance(&mut self, bytes: &[u8]) {
|
||||
if (self.prompts.is_empty() && self.images.is_empty()) || self.term.mode().contains(TermMode::ALT_SCREEN) {
|
||||
self.parser.advance(&mut self.term, bytes);
|
||||
return;
|
||||
}
|
||||
let h0 = self.term.grid().history_size();
|
||||
if h0 < self.max_history {
|
||||
self.parser.advance(&mut self.term, bytes);
|
||||
} else {
|
||||
// ponytail: counts LF at the bottom row only; scroll-region and CSI S scrolling while
|
||||
// the history is full can leave marks a few lines off.
|
||||
let bottom = self.rows as i32 - 1;
|
||||
for piece in bytes.split_inclusive(|&b| b == b'\n') {
|
||||
let at_bottom = self.term.grid().cursor.point.line.0 == bottom;
|
||||
self.parser.advance(&mut self.term, piece);
|
||||
if at_bottom && piece.ends_with(b"\n") && self.term.grid().history_size() == self.max_history {
|
||||
self.rotated += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.term.grid().history_size() < h0 {
|
||||
// The scrollback was cleared: earlier marks point at nothing.
|
||||
self.prompts.clear();
|
||||
self.images.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable index of a grid line: unchanged as lines scroll into (and out of) the history.
|
||||
fn stable(&self, line: Line) -> i64 {
|
||||
self.term.grid().history_size() as i64 + line.0 as i64 + self.rotated
|
||||
}
|
||||
|
||||
fn line_of(&self, stable: i64) -> Line {
|
||||
Line((stable - self.rotated - self.term.grid().history_size() as i64) as i32)
|
||||
}
|
||||
|
||||
fn cursor_stable(&self) -> i64 {
|
||||
self.stable(self.term.grid().cursor.point.line)
|
||||
}
|
||||
|
||||
fn apply_osc(&mut self, osc: crate::osc::Osc) {
|
||||
use crate::osc::Osc;
|
||||
match osc {
|
||||
Osc::Prompt => {
|
||||
let line = self.cursor_stable();
|
||||
if self.prompts.last().is_some_and(|p| p.prompt == line) {
|
||||
return;
|
||||
}
|
||||
if self.prompts.len() >= MAX_PROMPTS {
|
||||
self.prompts.remove(0);
|
||||
}
|
||||
self.prompts.push(PromptMark { prompt: line, output: None, end: None, exit: None, started: None, duration: None });
|
||||
}
|
||||
Osc::Output => {
|
||||
let line = self.cursor_stable();
|
||||
if let Some(p) = self.prompts.last_mut() {
|
||||
p.output = Some(line);
|
||||
p.started = Some(std::time::Instant::now());
|
||||
}
|
||||
}
|
||||
Osc::Finished(code) => {
|
||||
let line = self.cursor_stable();
|
||||
if let Some(p) = self.prompts.last_mut().filter(|p| p.output.is_some() && p.end.is_none()) {
|
||||
p.end = Some(line);
|
||||
p.exit = code;
|
||||
p.duration = p.started.map(|t| t.elapsed());
|
||||
}
|
||||
}
|
||||
Osc::Cwd { host, path } => self.reported_cwd = Some((host, path)),
|
||||
Osc::Image { data, width, height } => self.place_image(&data, &width, &height),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes an inline image (PNG, JPEG or GIF, within size limits), anchors it at the cursor and
|
||||
/// moves the cursor below it, as iTerm2 does.
|
||||
fn place_image(&mut self, data: &[u8], width: &str, height: &str) {
|
||||
if self.term.mode().contains(TermMode::ALT_SCREEN) {
|
||||
return;
|
||||
}
|
||||
let decoded = (|| {
|
||||
let mut r = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_image_width = Some(8192);
|
||||
limits.max_image_height = Some(8192);
|
||||
limits.max_alloc = Some(256 << 20);
|
||||
r.limits(limits);
|
||||
Some(r.decode().ok()?.to_rgba8())
|
||||
})();
|
||||
let Some(img) = decoded else { return };
|
||||
let (cw, ch) = self.cell_px;
|
||||
let (iw, ih) = (img.width() as f32, img.height() as f32);
|
||||
let full_w = self.cols as f32 * cw;
|
||||
let dim = |arg: &str, full: f32, cell: f32| -> Option<f32> {
|
||||
let a = arg.trim();
|
||||
if a.is_empty() || a == "auto" {
|
||||
None
|
||||
} else if let Some(px) = a.strip_suffix("px") {
|
||||
px.parse().ok()
|
||||
} else if let Some(pc) = a.strip_suffix('%') {
|
||||
pc.parse::<f32>().ok().map(|p| full * p / 100.0)
|
||||
} else {
|
||||
a.parse::<f32>().ok().map(|n| n * cell)
|
||||
}
|
||||
};
|
||||
let (w, h) = match (dim(width, full_w, cw), dim(height, self.rows as f32 * ch, ch)) {
|
||||
(Some(w), Some(h)) => (w, h),
|
||||
(Some(w), None) => (w, w * ih / iw),
|
||||
(None, Some(h)) => (h * iw / ih, h),
|
||||
(None, None) => (iw, ih),
|
||||
};
|
||||
// Never wider than the terminal; keep the aspect ratio when shrinking.
|
||||
let scale = (full_w / w).min(1.0);
|
||||
let (w, h) = (w * scale, h * scale);
|
||||
let cols = ((w / cw).ceil() as usize).clamp(1, self.cols as usize);
|
||||
let rows = ((h / ch).ceil() as usize).clamp(1, 1000);
|
||||
let size = img.width() as usize * img.height() as usize;
|
||||
while !self.images.is_empty() && self.images.iter().map(|i| i.size).sum::<usize>() + size > MAX_IMAGE_PIXELS {
|
||||
self.images.remove(0);
|
||||
}
|
||||
let pixels = egui::ColorImage::from_rgba_unmultiplied([img.width() as usize, img.height() as usize], img.as_raw());
|
||||
let (stable, col) = (self.cursor_stable(), self.term.grid().cursor.point.column.0);
|
||||
self.images.push(InlineImage { stable, col, cols, rows, pixels: Some(pixels), texture: None, size });
|
||||
// Leave room: the cursor ends up on the line below the image.
|
||||
self.advance(&b"\r\n".repeat(rows));
|
||||
}
|
||||
|
||||
fn paint_images(&mut self, ui: &Ui, rect: Rect, origin: Pos2, cw: f32, ch: f32) {
|
||||
let top = self.term.grid().topmost_line().0;
|
||||
let offset = self.term.grid().display_offset() as i32;
|
||||
// Line of a stable index, without borrowing self (the loop below mutates the images).
|
||||
let (rotated, history) = (self.rotated, self.term.grid().history_size() as i64);
|
||||
let line_of = |stable: i64| (stable - rotated - history) as i32;
|
||||
// Images that scrolled out of the scrollback are gone with it.
|
||||
self.images.retain(|i| line_of(i.stable) + i.rows as i32 > top);
|
||||
let painter = ui.painter_at(rect);
|
||||
let rows = self.rows as i32;
|
||||
for img in &mut self.images {
|
||||
let vr = line_of(img.stable) + offset;
|
||||
if vr + img.rows as i32 <= 0 || vr >= rows {
|
||||
continue;
|
||||
}
|
||||
let at = Rect::from_min_size(origin + vec2(img.col as f32 * cw, vr as f32 * ch), vec2(img.cols as f32 * cw, img.rows as f32 * ch));
|
||||
let tex = img.texture.get_or_insert_with(|| {
|
||||
let px = img.pixels.take().unwrap_or_default();
|
||||
ui.ctx().load_texture("term-image", px, egui::TextureOptions::LINEAR)
|
||||
});
|
||||
// Fit inside the reserved cells, keeping the aspect ratio.
|
||||
let [tw, th] = tex.size();
|
||||
let s = (at.width() / tw as f32).min(at.height() / th as f32);
|
||||
let shown = Rect::from_min_size(at.min, vec2(tw as f32 * s, th as f32 * s));
|
||||
painter.image(tex.id(), shown, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrolls so the previous (or next) prompt is at the top. False when there is none.
|
||||
pub fn jump_prompt(&mut self, forward: bool) -> bool {
|
||||
let top = Line(-(self.term.grid().display_offset() as i32));
|
||||
let lines: Vec<i32> = self.prompts.iter().map(|p| self.line_of(p.prompt).0).filter(|&l| l >= self.term.grid().topmost_line().0).collect();
|
||||
let target = if forward { lines.iter().copied().find(|&l| l > top.0) } else { lines.iter().rev().copied().find(|&l| l < top.0) };
|
||||
let Some(line) = target else { return false };
|
||||
let want_offset = (-line).clamp(0, self.term.grid().history_size() as i32);
|
||||
self.term.scroll_display(Scroll::Delta(want_offset - self.term.grid().display_offset() as i32));
|
||||
true
|
||||
}
|
||||
|
||||
/// The output of the most recent command that finished (shell integration).
|
||||
pub fn last_output(&self) -> Option<String> {
|
||||
let p = self.prompts.iter().rev().find(|p| p.output.is_some() && p.end.is_some())?;
|
||||
let (from, to) = (self.line_of(p.output?).0.max(self.term.grid().topmost_line().0), self.line_of(p.end?).0);
|
||||
let text: Vec<String> = (from..to).map(|l| self.line_text(Line(l)).0.trim_end().to_string()).collect();
|
||||
Some(text.join("\n").trim_end_matches('\n').to_string())
|
||||
}
|
||||
|
||||
/// Whether the shell reports prompts (OSC 133), which enables the commands above.
|
||||
pub fn has_shell_integration(&self) -> bool {
|
||||
!self.prompts.is_empty()
|
||||
}
|
||||
|
||||
pub fn size(&self) -> (u16, u16) {
|
||||
(self.cols, self.rows)
|
||||
}
|
||||
@@ -306,6 +541,24 @@ impl TermView {
|
||||
}
|
||||
|
||||
self.paint(ui, rect, origin, &font, cw, ch, theme, focused);
|
||||
self.cell_px = (cw, ch);
|
||||
self.paint_images(ui, rect, origin, cw, ch);
|
||||
// Exit status of each finished command, as a bar beside its prompt (shell integration).
|
||||
let hover = ui.input(|i| i.pointer.hover_pos());
|
||||
for (bar, exit, took) in self.status_bars(rect, origin, ch) {
|
||||
let color = match exit {
|
||||
Some(0) => Color32::from_rgb(0x4c, 0xaf, 0x50),
|
||||
Some(_) => Color32::from_rgb(0xe5, 0x39, 0x35),
|
||||
None => Color32::GRAY,
|
||||
};
|
||||
ui.painter_at(rect).rect_filled(bar, 1.0, color);
|
||||
if hover.is_some_and(|p| bar.expand2(vec2(3.0, 0.0)).contains(p)) {
|
||||
let exit = exit.map_or("finished".to_string(), |c| format!("exit {c}"));
|
||||
let took = took.map_or(String::new(), |d| format!(" · {:.1?}", d));
|
||||
egui::Tooltip::always_open(ui.ctx().clone(), ui.layer_id(), egui::Id::new(("cmd-status", bar.min.y as i32)), egui::PopupAnchor::Pointer)
|
||||
.show(|ui| ui.label(format!("{exit}{took}")));
|
||||
}
|
||||
}
|
||||
|
||||
resp.context_menu(|ui| {
|
||||
let m = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl+" };
|
||||
@@ -322,6 +575,19 @@ impl TermView {
|
||||
(MenuAction::Clear, "Clear", String::new()),
|
||||
(MenuAction::Reset, "Reset", String::new()),
|
||||
];
|
||||
if self.has_shell_integration() {
|
||||
for (a, label, keys) in [
|
||||
(MenuAction::PrevPrompt, "Previous Prompt", format!("{m}Shift+↑")),
|
||||
(MenuAction::NextPrompt, "Next Prompt", format!("{m}Shift+↓")),
|
||||
(MenuAction::CopyOutput, "Copy Last Command Output", String::new()),
|
||||
] {
|
||||
if ui.add(egui::Button::new(label).shortcut_text(keys).min_size(vec2(200.0, 0.0))).clicked() {
|
||||
out.menu = Some(a);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
for (i, (a, label, keys)) in items.into_iter().enumerate() {
|
||||
if matches!(i, 3 | 5 | 6 | 8) {
|
||||
ui.separator();
|
||||
@@ -342,9 +608,38 @@ impl TermView {
|
||||
self.select_all();
|
||||
out.menu = None;
|
||||
}
|
||||
match out.menu {
|
||||
Some(a @ (MenuAction::PrevPrompt | MenuAction::NextPrompt)) => {
|
||||
self.jump_prompt(a == MenuAction::NextPrompt);
|
||||
out.menu = None;
|
||||
}
|
||||
Some(MenuAction::CopyOutput) => {
|
||||
if let Some(text) = self.last_output() {
|
||||
ui.ctx().copy_text(text);
|
||||
}
|
||||
out.menu = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where to draw each visible finished command's status bar, with its exit code and duration.
|
||||
fn status_bars(&self, rect: Rect, origin: Pos2, ch: f32) -> Vec<(Rect, Option<i32>, Option<std::time::Duration>)> {
|
||||
let offset = self.term.grid().display_offset() as i32;
|
||||
self.prompts
|
||||
.iter()
|
||||
.filter(|p| p.end.is_some())
|
||||
.filter_map(|p| {
|
||||
let vr = self.line_of(p.prompt).0 + offset;
|
||||
(0..self.rows as i32).contains(&vr).then(|| {
|
||||
let y = origin.y + vr as f32 * ch;
|
||||
(Rect::from_min_max(pos2(rect.left(), y + 1.0), pos2(rect.left() + 3.0, y + ch - 1.0)), p.exit, p.duration)
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn keyboard(&mut self, ui: &mut Ui, out: &mut TermResponse) {
|
||||
let events = ui.input(|i| i.events.clone());
|
||||
let mode = *self.term.mode();
|
||||
@@ -377,6 +672,11 @@ impl TermView {
|
||||
typed = true;
|
||||
}
|
||||
Event::Key { key, pressed: true, modifiers, .. } => {
|
||||
// Ctrl/Cmd+Shift+Up/Down jump between prompts (shell integration).
|
||||
if modifiers.command && modifiers.shift && matches!(key, Key::ArrowUp | Key::ArrowDown) && self.has_shell_integration() {
|
||||
self.jump_prompt(key == Key::ArrowDown);
|
||||
continue;
|
||||
}
|
||||
// Shift+PageUp/PageDown/Home/End scroll the local scrollback.
|
||||
if modifiers.shift && !modifiers.ctrl && !mode.contains(TermMode::ALT_SCREEN) {
|
||||
let page = self.rows as i32 - 1;
|
||||
@@ -488,7 +788,8 @@ impl TermView {
|
||||
if modifiers.command
|
||||
&& let Some(url) = self.url_at(origin, cw, ch, *pos)
|
||||
{
|
||||
ui.ctx().open_url(egui::OpenUrl::new_tab(url));
|
||||
// Only web links: text from a remote host must not launch file: or custom-scheme handlers.
|
||||
crate::widgets::open_web_url(ui.ctx(), &url);
|
||||
continue;
|
||||
}
|
||||
let now = ui.input(|i| i.time);
|
||||
@@ -542,9 +843,20 @@ impl TermView {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// An OSC 8 link's text can say anything, so its real target is always shown on hover.
|
||||
if let Some(p) = hover
|
||||
&& let Some(link) = self.hyperlink_at(self.point_at(origin, cw, ch, p).0)
|
||||
{
|
||||
egui::Tooltip::always_open(ui.ctx().clone(), ui.layer_id(), egui::Id::new("term-link"), egui::PopupAnchor::Pointer).show(|ui| {
|
||||
ui.label(&link);
|
||||
if !crate::widgets::is_web_url(&link) {
|
||||
ui.label(egui::RichText::new("Not a web link — won't be opened").weak());
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(p) = hover
|
||||
&& ui.input(|i| i.modifiers.command)
|
||||
&& self.url_at(origin, cw, ch, p).is_some()
|
||||
&& self.url_at(origin, cw, ch, p).is_some_and(|u| crate::widgets::is_web_url(&u))
|
||||
{
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
|
||||
} else if hover.is_some() {
|
||||
@@ -552,8 +864,12 @@ impl TermView {
|
||||
}
|
||||
}
|
||||
|
||||
/// The link under `p`: an OSC 8 hyperlink on the cell, else a URL in the text.
|
||||
fn url_at(&self, origin: Pos2, cw: f32, ch: f32, p: Pos2) -> Option<String> {
|
||||
let (point, _) = self.point_at(origin, cw, ch, p);
|
||||
if let Some(link) = self.hyperlink_at(point) {
|
||||
return Some(link);
|
||||
}
|
||||
let (text, cols) = self.line_text(point.line);
|
||||
let re = regex::Regex::new(URL_RE).ok()?;
|
||||
re.find_iter(&text).find_map(|m| {
|
||||
@@ -563,6 +879,13 @@ impl TermView {
|
||||
})
|
||||
}
|
||||
|
||||
fn hyperlink_at(&self, point: Point) -> Option<String> {
|
||||
let g = self.term.grid();
|
||||
(point.line >= g.topmost_line() && point.line <= g.bottommost_line() && point.column.0 < self.term.columns())
|
||||
.then(|| g[point].hyperlink().map(|h| h.uri().to_string()))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn paint(&mut self, ui: &mut Ui, rect: Rect, origin: Pos2, font: &FontId, cw: f32, ch: f32, theme: &TermTheme, focused: bool) {
|
||||
let painter = ui.painter_at(rect);
|
||||
@@ -622,6 +945,13 @@ impl TermView {
|
||||
}
|
||||
if cell.flags.intersects(Flags::ALL_UNDERLINES) {
|
||||
painter.hline(cell_rect.x_range(), y + ch - 1.5, Stroke::new(1.0, fg));
|
||||
} else if cell.hyperlink().is_some() {
|
||||
// OSC 8 links: a dotted underline.
|
||||
let mut x0 = cell_rect.left();
|
||||
while x0 < cell_rect.right() {
|
||||
painter.hline(x0..=(x0 + 1.5).min(cell_rect.right()), y + ch - 1.5, Stroke::new(1.0, fg.gamma_multiply(0.8)));
|
||||
x0 += 3.0;
|
||||
}
|
||||
}
|
||||
if cell.flags.contains(Flags::STRIKEOUT) {
|
||||
painter.hline(cell_rect.x_range(), y + ch * 0.55, Stroke::new(1.0, fg));
|
||||
@@ -902,6 +1232,75 @@ mod tests {
|
||||
assert!(out.confirm_paste.is_none() && out.input.starts_with(b"\x1b[200~"), "bracketed paste needs no prompt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_integration_marks_survive_a_full_scrollback() {
|
||||
// Scrollback of 30 lines, so the history fills and rotates during the test.
|
||||
let mut t = TermView::new(30, 14.0, CursorStyle::Block);
|
||||
let prompt = |t: &mut TermView| t.feed(b"\x1b]133;A\x07$ \x1b]133;B\x07");
|
||||
let run = |t: &mut TermView, cmd: &str, out: &[String], code: i32| {
|
||||
t.feed(format!("{cmd}\r\n\x1b]133;C\x07").as_bytes());
|
||||
for l in out {
|
||||
t.feed(format!("{l}\r\n").as_bytes());
|
||||
}
|
||||
t.feed(format!("\x1b]133;D;{code}\x07").as_bytes());
|
||||
};
|
||||
prompt(&mut t);
|
||||
run(&mut t, "seq 3", &["1".into(), "2".into(), "3".into()], 0);
|
||||
prompt(&mut t);
|
||||
assert_eq!(t.last_output().as_deref(), Some("1\n2\n3"));
|
||||
let many: Vec<String> = (0..80).map(|i| format!("line {i}")).collect();
|
||||
run(&mut t, "big", &many, 3);
|
||||
prompt(&mut t);
|
||||
run(&mut t, "tail", &["a".into(), "b".into()], 1);
|
||||
prompt(&mut t);
|
||||
assert_eq!(t.last_output().as_deref(), Some("a\nb"), "rotation must not shift the marks");
|
||||
let last = t.prompts.iter().rev().nth(1).unwrap();
|
||||
assert_eq!(last.exit, Some(1));
|
||||
assert_eq!(t.line_text(t.line_of(last.prompt)).0.trim_end(), "$ tail");
|
||||
// Jumping back lands an earlier prompt (still in the scrollback) at the top of the view.
|
||||
let more: Vec<String> = (0..20).map(|i| format!("more {i}")).collect();
|
||||
run(&mut t, "more", &more, 0);
|
||||
prompt(&mut t);
|
||||
assert!(t.jump_prompt(false));
|
||||
let top = Line(-(t.term.grid().display_offset() as i32));
|
||||
assert!(t.line_text(top).0.starts_with("$ "), "{:?}", t.line_text(top).0);
|
||||
// A cleared scrollback drops the marks with it.
|
||||
t.feed(b"\x1b[3J\x1b[2J");
|
||||
t.feed(b"x\r\n");
|
||||
assert!(t.prompts.len() <= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn osc8_links_are_found_on_their_cells() {
|
||||
let mut t = TermView::new(100, 14.0, CursorStyle::Block);
|
||||
t.feed(b"see \x1b]8;;https://example.com/docs\x1b\\the docs\x1b]8;;\x1b\\ now");
|
||||
let at = |c| t.hyperlink_at(Point::new(Line(0), Column(c)));
|
||||
assert_eq!(at(4).as_deref(), Some("https://example.com/docs"));
|
||||
assert_eq!(at(11).as_deref(), Some("https://example.com/docs"));
|
||||
assert_eq!(at(12), None, "the link ends with its text");
|
||||
assert_eq!(at(0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_images_reserve_rows_and_respect_width() {
|
||||
use base64::Engine;
|
||||
let mut png = Vec::new();
|
||||
image::RgbaImage::from_pixel(40, 32, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(&png);
|
||||
let mut t = TermView::new(100, 14.0, CursorStyle::Block);
|
||||
t.cell_px = (8.0, 16.0);
|
||||
t.feed(format!("x\r\n\x1b]1337;File=inline=1;width=10:{b64}\x07after").as_bytes());
|
||||
let img = &t.images[0];
|
||||
// 10 cells wide (80 px) keeps the 40x32 aspect: 64 px = 4 rows; the text continues below.
|
||||
assert_eq!((img.col, img.cols, img.rows), (0, 10, 4));
|
||||
assert_eq!(t.line_of(img.stable), Line(1));
|
||||
assert_eq!(t.term.grid().cursor.point.line, Line(5));
|
||||
assert!(t.line_text(Line(5)).0.starts_with("after"));
|
||||
// Garbage is ignored rather than placed.
|
||||
t.feed(b"\x1b]1337;File=inline=1:bm90IGFuIGltYWdl\x07");
|
||||
assert_eq!(t.images.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feeds_text_and_finds_it() {
|
||||
let mut t = TermView::new(1000, 14.0, CursorStyle::Block);
|
||||
|
||||
@@ -136,7 +136,7 @@ pub fn is_web_url(url: &str) -> bool {
|
||||
/// Opens `url` in the browser if it is a web link; returns false (and opens nothing) otherwise.
|
||||
pub fn open_web_url(ctx: &egui::Context, url: &str) -> bool {
|
||||
if !is_web_url(url) {
|
||||
eprintln!("refusing to open non-web URL {url:?}");
|
||||
tracing::warn!(url, "refusing to open a non-web URL");
|
||||
return false;
|
||||
}
|
||||
ctx.open_url(egui::OpenUrl::new_tab(url.trim()));
|
||||
|
||||
@@ -3,6 +3,10 @@ name = "nexus-core"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[features]
|
||||
# Exposes parser entry points for rust/fuzz (cargo-fuzz).
|
||||
fuzzing = []
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
@@ -23,6 +27,7 @@ hmac = "0.13.0"
|
||||
sha1 = "0.11.0"
|
||||
zeroize = "1"
|
||||
parking_lot = "0.12"
|
||||
tracing = "0.1"
|
||||
portable-pty = "0.9.0"
|
||||
serialport = { version = "4", default-features = false }
|
||||
des = "0.9"
|
||||
@@ -31,10 +36,15 @@ image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
webpki-roots = "1"
|
||||
ironrdp = { version = "0.17", features = ["connector", "session", "graphics", "pdu", "svc", "dvc", "displaycontrol", "input"] }
|
||||
ironrdp = { version = "0.17", features = ["connector", "session", "graphics", "pdu", "svc", "dvc", "displaycontrol", "input", "cliprdr", "rdpsnd", "rdpdr"] }
|
||||
ironrdp-rdpsnd-native = { version = "0.7", default-features = false }
|
||||
ironrdp-blocking = "0.10"
|
||||
ironrdp-mstsgu = "0.0.1"
|
||||
x509-cert = { version = "0.2", default-features = false, features = ["std"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
ironrdp-rdpdr-native = "0.7"
|
||||
|
||||
[dev-dependencies]
|
||||
tiny_http = "0.12"
|
||||
|
||||
|
||||
@@ -105,6 +105,10 @@ fn main() {
|
||||
vnc.vnc.as_mut().unwrap().vnc_port = 42900;
|
||||
vnc.vnc.as_mut().unwrap().scale_to_fit = true;
|
||||
profiles.push(vnc);
|
||||
let mut rdp = mk(Protocol::Rdp, "Design workstation", "192.0.2.60", 0, "Home", false);
|
||||
rdp.username = "andy".into();
|
||||
rdp.rdp.as_mut().unwrap().domain = "STUDIO".into();
|
||||
profiles.push(rdp);
|
||||
|
||||
for p in profiles {
|
||||
svc.create_profile(p).unwrap();
|
||||
|
||||
@@ -53,6 +53,10 @@ pub struct Config {
|
||||
pub nickserv_account: String,
|
||||
pub nickserv_password: String,
|
||||
|
||||
/// SASL PLAIN login during registration (IRCv3); empty account disables it.
|
||||
pub sasl_account: String,
|
||||
pub sasl_password: String,
|
||||
|
||||
/// Provides the transport instead of a direct TCP connect (e.g. an SSH tunnel). TLS, when
|
||||
/// enabled, is layered on top of it.
|
||||
pub connector: Option<Connector>,
|
||||
@@ -78,6 +82,8 @@ impl Default for Config {
|
||||
nickserv_identify: false,
|
||||
nickserv_account: String::new(),
|
||||
nickserv_password: String::new(),
|
||||
sasl_account: String::new(),
|
||||
sasl_password: String::new(),
|
||||
connector: None,
|
||||
connect_timeout: Duration::ZERO,
|
||||
on_event: Arc::new(|_| {}),
|
||||
@@ -139,6 +145,8 @@ struct Channel {
|
||||
|
||||
struct State {
|
||||
nick: String,
|
||||
/// Capabilities from a multi-line CAP LS, gathered until the last line.
|
||||
caps_offered: Vec<String>,
|
||||
connected: bool,
|
||||
closing: bool,
|
||||
list_rooms: Vec<RoomInfo>,
|
||||
@@ -153,6 +161,9 @@ pub struct Client {
|
||||
cfg: Config,
|
||||
state: Mutex<State>,
|
||||
out: Mutex<Option<Sender<Out>>>,
|
||||
/// The server-time of the line being handled (ms since the epoch; 0 = none), stamped on the
|
||||
/// events it produces.
|
||||
line_time: std::sync::atomic::AtomicI64,
|
||||
}
|
||||
|
||||
/// A parsed server line.
|
||||
@@ -160,6 +171,8 @@ struct Message {
|
||||
source: String,
|
||||
command: String,
|
||||
params: Vec<String>,
|
||||
/// IRCv3 `@time=` tag, in ms since the epoch.
|
||||
time: Option<i64>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
@@ -187,6 +200,7 @@ impl Client {
|
||||
cfg,
|
||||
state: Mutex::new(State {
|
||||
nick,
|
||||
caps_offered: Vec::new(),
|
||||
connected: false,
|
||||
closing: false,
|
||||
list_rooms: Vec::new(),
|
||||
@@ -196,6 +210,7 @@ impl Client {
|
||||
last_pong: Instant::now(),
|
||||
}),
|
||||
out: Mutex::new(None),
|
||||
line_time: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -211,7 +226,7 @@ impl Client {
|
||||
*self.out.lock() = Some(out_tx);
|
||||
|
||||
let client = self.clone();
|
||||
std::thread::spawn(move || client.io_thread(out_rx));
|
||||
std::thread::spawn(super::guarded(self.cfg.on_error.clone(), self.cfg.on_close.clone(), move || client.io_thread(out_rx)));
|
||||
|
||||
let timeout = self.cfg.connect_timeout;
|
||||
match ready_rx.recv_timeout(timeout) {
|
||||
@@ -546,6 +561,8 @@ impl Client {
|
||||
stream.write_all(b"\r\n")?;
|
||||
Ok(stream.flush()?)
|
||||
};
|
||||
// IRCv3 capability negotiation; servers without it ignore the command and register as usual.
|
||||
write(&mut stream, "CAP LS 302")?;
|
||||
if !self.cfg.server_pass.is_empty() {
|
||||
write(&mut stream, &encode("PASS", &[&self.cfg.server_pass]))?;
|
||||
}
|
||||
@@ -589,7 +606,9 @@ impl Client {
|
||||
let raw: Vec<u8> = buf.drain(..=pos).collect();
|
||||
let line = String::from_utf8_lossy(&raw);
|
||||
if let Some(msg) = parse_line(line.trim_end_matches(['\r', '\n'])) {
|
||||
self.line_time.store(msg.time.unwrap_or(0), std::sync::atomic::Ordering::Relaxed);
|
||||
self.handle_message(&msg);
|
||||
self.line_time.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
if buf.len() > MAX_LINE_BYTES {
|
||||
@@ -612,6 +631,27 @@ impl Client {
|
||||
|
||||
fn handle_message(&self, m: &Message) {
|
||||
match m.command.as_str() {
|
||||
"CAP" => self.handle_cap(m),
|
||||
"AUTHENTICATE" if m.param(0) == "+" => {
|
||||
// SASL PLAIN: authzid NUL authcid NUL password, base64, in 400-byte chunks.
|
||||
use base64::Engine;
|
||||
let blob = base64::engine::general_purpose::STANDARD.encode(format!("{0}\0{0}\0{1}", self.cfg.sasl_account, self.cfg.sasl_password));
|
||||
for chunk in blob.as_bytes().chunks(400) {
|
||||
let _ = self.send("AUTHENTICATE", &[std::str::from_utf8(chunk).unwrap_or("")]);
|
||||
}
|
||||
if blob.len() % 400 == 0 {
|
||||
let _ = self.send("AUTHENTICATE", &["+"]);
|
||||
}
|
||||
}
|
||||
// 900 logged in, 903 success; 902/904–907 failures. Either way registration goes on.
|
||||
"903" => {
|
||||
self.emit(Event { kind: "notice".into(), text: format!("SASL: logged in as {}", self.cfg.sasl_account), ..Default::default() });
|
||||
let _ = self.send("CAP", &["END"]);
|
||||
}
|
||||
"902" | "904" | "905" | "906" | "907" => {
|
||||
self.emit(Event { kind: "error".into(), text: format!("SASL login failed: {}", m.last()), ..Default::default() });
|
||||
let _ = self.send("CAP", &["END"]);
|
||||
}
|
||||
"001" => self.handle_welcome(m),
|
||||
"433" | "436" | "437" => {
|
||||
let mut st = self.st();
|
||||
@@ -736,6 +776,52 @@ impl Client {
|
||||
self.emit(Event { kind: "notice".into(), target, from: m.source.clone(), text: m.last().into(), ..Default::default() });
|
||||
}
|
||||
|
||||
/// CAP LS / ACK / NAK: ask for server-time (and sasl when configured), then authenticate or
|
||||
/// end negotiation.
|
||||
fn handle_cap(&self, m: &Message) {
|
||||
let sub = m.param(1).to_ascii_uppercase();
|
||||
let caps: Vec<&str> = m.last().split_whitespace().map(|c| c.split('=').next().unwrap_or(c)).collect();
|
||||
let want_sasl = !self.cfg.sasl_account.is_empty();
|
||||
match sub.as_str() {
|
||||
// A multi-line LS list ("CAP * LS * :…") continues; act on the last line.
|
||||
"LS" if m.params.len() >= 4 && m.param(2) == "*" => {
|
||||
self.st().caps_offered.extend(caps.iter().map(|c| c.to_string()));
|
||||
}
|
||||
"LS" => {
|
||||
let offered: Vec<String> = {
|
||||
let mut st = self.st();
|
||||
st.caps_offered.extend(caps.iter().map(|c| c.to_string()));
|
||||
std::mem::take(&mut st.caps_offered)
|
||||
};
|
||||
let mut req = vec![];
|
||||
if offered.iter().any(|c| c == "server-time") {
|
||||
req.push("server-time");
|
||||
}
|
||||
if want_sasl && offered.iter().any(|c| c == "sasl") {
|
||||
req.push("sasl");
|
||||
} else if want_sasl {
|
||||
self.emit(Event { kind: "error".into(), text: "SASL: the server doesn't offer it".into(), ..Default::default() });
|
||||
}
|
||||
if req.is_empty() {
|
||||
let _ = self.send("CAP", &["END"]);
|
||||
} else {
|
||||
let _ = self.send("CAP", &["REQ", &req.join(" ")]);
|
||||
}
|
||||
}
|
||||
"ACK" => {
|
||||
if want_sasl && caps.contains(&"sasl") {
|
||||
let _ = self.send("AUTHENTICATE", &["PLAIN"]);
|
||||
} else {
|
||||
let _ = self.send("CAP", &["END"]);
|
||||
}
|
||||
}
|
||||
"NAK" => {
|
||||
let _ = self.send("CAP", &["END"]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_join(&self, m: &Message) {
|
||||
let room = m.param(0).to_string();
|
||||
if room.is_empty() {
|
||||
@@ -931,7 +1017,8 @@ impl Client {
|
||||
|
||||
fn emit(&self, mut event: Event) {
|
||||
if event.timestamp == 0 {
|
||||
event.timestamp = chrono::Utc::now().timestamp_millis();
|
||||
let t = self.line_time.load(std::sync::atomic::Ordering::Relaxed);
|
||||
event.timestamp = if t > 0 { t } else { chrono::Utc::now().timestamp_millis() };
|
||||
}
|
||||
if event.target.is_empty() {
|
||||
event.target = SERVER_TARGET.into();
|
||||
@@ -1004,8 +1091,11 @@ fn encode(command: &str, params: &[&str]) -> String {
|
||||
|
||||
fn parse_line(line: &str) -> Option<Message> {
|
||||
let mut rest = line.trim_start();
|
||||
if rest.starts_with('@') {
|
||||
rest = rest.split_once(' ')?.1.trim_start();
|
||||
let mut time = None;
|
||||
if let Some(tagged) = rest.strip_prefix('@') {
|
||||
let (tags, tail) = tagged.split_once(' ')?;
|
||||
time = tags.split(';').find_map(|t| t.strip_prefix("time=")).and_then(|v| chrono::DateTime::parse_from_rfc3339(v).ok()).map(|d| d.timestamp_millis());
|
||||
rest = tail.trim_start();
|
||||
}
|
||||
let mut source = String::new();
|
||||
if let Some(prefixed) = rest.strip_prefix(':') {
|
||||
@@ -1021,7 +1111,7 @@ fn parse_line(line: &str) -> Option<Message> {
|
||||
let command = words.next()?.to_uppercase();
|
||||
let mut params: Vec<String> = words.map(String::from).collect();
|
||||
params.extend(trailing.map(String::from));
|
||||
Some(Message { source, command, params })
|
||||
Some(Message { source, command, params, time })
|
||||
}
|
||||
|
||||
/// A CTCP request in a PRIVMSG: `(TAG, args)`, as girc's `DecodeCTCP`.
|
||||
@@ -1046,6 +1136,25 @@ fn split_first_arg(input: &str) -> (&str, &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fuzzing entry point: each line of `data` through the parser, the state machine (as a
|
||||
/// client in #a) and the mIRC formatter.
|
||||
#[cfg(feature = "fuzzing")]
|
||||
#[doc(hidden)]
|
||||
pub fn fuzz_lines(data: &[u8]) {
|
||||
let client = Client::new(Config::default());
|
||||
client.st().nick = "me".into();
|
||||
if let Some(m) = parse_line(":me!u@h JOIN #a") {
|
||||
client.handle_message(&m);
|
||||
}
|
||||
for line in String::from_utf8_lossy(data).lines() {
|
||||
if let Some(m) = parse_line(line) {
|
||||
client.handle_message(&m);
|
||||
let e = Event { kind: "message".into(), target: m.param(0).into(), from: m.source.clone(), text: m.last().into(), ..Default::default() };
|
||||
let _ = crate::ircformat::format_event(&e, "12:00");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1185,6 +1294,36 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiates_server_time_and_sasl() {
|
||||
let (client, listener, rx, _) = harness(Config { sasl_account: "acct".into(), sasl_password: "s3cret".into(), ..Default::default() });
|
||||
let c = client.clone();
|
||||
let connecting = std::thread::spawn(move || c.connect());
|
||||
let mut srv = accept(&listener);
|
||||
assert_eq!(srv.line(), "CAP LS 302");
|
||||
assert_eq!(srv.line(), "NICK me");
|
||||
assert_eq!(srv.line(), "USER me * * me");
|
||||
// A two-line LS list; only the last line triggers the request.
|
||||
srv.send(":srv CAP * LS * :multi-prefix server-time");
|
||||
srv.send(":srv CAP * LS :sasl=PLAIN,EXTERNAL away-notify");
|
||||
assert_eq!(srv.line(), "CAP REQ :server-time sasl");
|
||||
srv.send(":srv CAP me ACK :server-time sasl");
|
||||
assert_eq!(srv.line(), "AUTHENTICATE PLAIN");
|
||||
srv.send("AUTHENTICATE +");
|
||||
use base64::Engine;
|
||||
assert_eq!(srv.line(), format!("AUTHENTICATE {}", base64::engine::general_purpose::STANDARD.encode("acct\0acct\0s3cret")));
|
||||
srv.send(":srv 903 me :SASL authentication successful");
|
||||
assert_eq!(srv.line(), "CAP END");
|
||||
assert!(wait_for(&rx, |e| e.text.starts_with("SASL: logged in")).text.contains("acct"));
|
||||
srv.send(":srv 001 me :Welcome");
|
||||
connecting.join().unwrap().unwrap();
|
||||
// server-time stamps events with the server's clock, not ours.
|
||||
srv.send("@time=2024-05-01T12:00:00.250Z :bob!u@h PRIVMSG me :old news");
|
||||
let e = wait_for(&rx, |e| e.kind == "message" || e.kind == "privmsg" || e.text == "old news");
|
||||
assert_eq!(e.timestamp, 1714564800250);
|
||||
client.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registers_tracks_rooms_and_handles_input() {
|
||||
let (client, listener, rx, closes) = harness(Config {
|
||||
@@ -1198,6 +1337,7 @@ mod tests {
|
||||
let c = client.clone();
|
||||
let connecting = std::thread::spawn(move || c.connect());
|
||||
let mut srv = accept(&listener);
|
||||
assert_eq!(srv.line(), "CAP LS 302");
|
||||
assert_eq!(srv.line(), "PASS pw");
|
||||
assert_eq!(srv.line(), "NICK me");
|
||||
assert_eq!(srv.line(), "USER me * * me");
|
||||
|
||||
@@ -76,7 +76,8 @@ impl LocalShell {
|
||||
drop(st);
|
||||
|
||||
let me = self.clone();
|
||||
std::thread::Builder::new().name("nexus-local-read".into()).spawn(move || {
|
||||
let (on_error, on_close) = (self.cb.on_error.clone(), self.cb.on_close.clone());
|
||||
std::thread::Builder::new().name("nexus-local-read".into()).spawn(super::guarded(on_error, on_close, move || {
|
||||
let mut buf = vec![0u8; 32 * 1024];
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
@@ -89,7 +90,7 @@ impl LocalShell {
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}))?;
|
||||
let me = self.clone();
|
||||
std::thread::Builder::new().name("nexus-local-wait".into()).spawn(move || {
|
||||
let _ = child.wait();
|
||||
@@ -146,6 +147,12 @@ impl LocalShell {
|
||||
|
||||
/// The last directory the shell was seen in (used to restart in the same place).
|
||||
pub fn working_directory(&self) -> PathBuf {
|
||||
// On Linux the live directory is a cheap readlink; elsewhere the last capture.
|
||||
if cfg!(target_os = "linux")
|
||||
&& let Some(dir) = self.state.lock().0.as_ref().and_then(|r| r.pid).and_then(process_cwd).filter(|d| d.is_dir())
|
||||
{
|
||||
return dir;
|
||||
}
|
||||
self.state.lock().1.clone()
|
||||
}
|
||||
|
||||
|
||||
@@ -40,10 +40,43 @@ impl Callbacks {
|
||||
pub mod proxy;
|
||||
pub mod raw;
|
||||
pub mod rdp;
|
||||
pub mod rdp_devices;
|
||||
pub mod serial;
|
||||
pub mod telnet;
|
||||
pub mod vnc;
|
||||
|
||||
/// Wraps a client's I/O loop so a panic in it (a decoder bug, say) ends only that session —
|
||||
/// reported through `on_error`, then `on_close` — instead of leaving it looking connected with
|
||||
/// nothing reading.
|
||||
pub(crate) fn guarded(on_error: ErrorFn, on_close: CloseFn, f: impl FnOnce() + Send + 'static) -> impl FnOnce() + Send + 'static {
|
||||
move || {
|
||||
if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
|
||||
on_error(format!("internal error: {}", panic_message(&*p)));
|
||||
on_close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `guarded` for a tokio task: the panic surfaces when the task's handle is awaited.
|
||||
pub(crate) fn guarded_task<F>(on_error: ErrorFn, on_close: CloseFn, fut: F)
|
||||
where
|
||||
F: std::future::Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let h = tokio::spawn(fut);
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = h.await
|
||||
&& e.is_panic()
|
||||
{
|
||||
on_error(format!("internal error: {}", panic_message(&*e.into_panic())));
|
||||
on_close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn panic_message(p: &(dyn std::any::Any + Send)) -> String {
|
||||
p.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| p.downcast_ref::<String>().cloned()).unwrap_or_else(|| "unknown panic".into())
|
||||
}
|
||||
|
||||
/// Called with protocol negotiation debug messages (Go's `onDebug`).
|
||||
pub type DebugFn = Arc<dyn Fn(String) + Send + Sync>;
|
||||
|
||||
@@ -91,7 +124,7 @@ impl TcpConn {
|
||||
*guard = Some(stream);
|
||||
}
|
||||
let me = self.clone();
|
||||
std::thread::spawn(move || {
|
||||
std::thread::spawn(guarded(self.on_error.clone(), self.on_close.clone(), move || {
|
||||
use std::io::Read;
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
@@ -111,7 +144,7 @@ impl TcpConn {
|
||||
}
|
||||
return;
|
||||
}
|
||||
});
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -151,3 +184,33 @@ pub(crate) fn utf8_to_latin1(data: &[u8]) -> Vec<u8> {
|
||||
pub(crate) fn latin1_to_utf8(data: &[u8]) -> String {
|
||||
data.iter().map(|&b| b as char).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod guard_tests {
|
||||
use super::*;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
#[test]
|
||||
fn a_panicking_io_loop_reports_and_closes_once() {
|
||||
let log: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let (l1, l2) = (log.clone(), log.clone());
|
||||
let on_error: ErrorFn = Arc::new(move |e| l1.lock().push(e));
|
||||
let on_close: CloseFn = Arc::new(move || l2.lock().push("closed".into()));
|
||||
std::thread::spawn(guarded(on_error.clone(), on_close.clone(), || panic!("bad tile"))).join().unwrap();
|
||||
assert_eq!(*log.lock(), ["internal error: bad tile", "closed"]);
|
||||
// A loop that ends normally is left to report its own close.
|
||||
std::thread::spawn(guarded(on_error.clone(), on_close.clone(), || {})).join().unwrap();
|
||||
assert_eq!(log.lock().len(), 2);
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
rt.block_on(async {
|
||||
guarded_task(on_error, on_close, async { panic!("{}", "task boom") });
|
||||
for _ in 0..50 {
|
||||
if log.lock().len() == 4 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
});
|
||||
assert_eq!(log.lock()[2..], ["internal error: task boom", "closed"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,15 @@
|
||||
//! tunnel), and the desktop decoded into the same RGBA framebuffer the VNC client uses. Like the
|
||||
//! other clients, `connect` blocks and the session runs on its own thread.
|
||||
|
||||
use super::vnc::{FrameFn, Framebuffer};
|
||||
use super::vnc::{ClipboardFn, FrameFn, Framebuffer};
|
||||
use super::{CloseFn, ErrorFn};
|
||||
use crate::Result;
|
||||
use ironrdp::cliprdr::CliprdrClient;
|
||||
use ironrdp::cliprdr::backend::{ClipboardMessage, CliprdrBackend};
|
||||
use ironrdp::cliprdr::pdu::{
|
||||
ClipboardFormat, ClipboardFormatId, ClipboardGeneralCapabilityFlags, FileContentsRequest, FileContentsResponse, FormatDataRequest, FormatDataResponse,
|
||||
LockDataId,
|
||||
};
|
||||
use ironrdp::connector::connection_activation::ConnectionActivationState;
|
||||
use ironrdp::connector::{self, ClientConnector, ConnectionResult, Credentials, Sequence, ServerName};
|
||||
use ironrdp::displaycontrol::client::DisplayControlClient;
|
||||
@@ -37,15 +43,25 @@ pub struct Config {
|
||||
pub host: String,
|
||||
pub username: String,
|
||||
pub domain: String,
|
||||
pub password: String,
|
||||
pub password: zeroize::Zeroizing<String>,
|
||||
pub width: u16,
|
||||
pub height: u16,
|
||||
/// Also allow plain TLS (graphical logon) for servers without NLA, such as xrdp.
|
||||
pub allow_tls_only: bool,
|
||||
/// Play the remote desktop's sound locally.
|
||||
pub audio: bool,
|
||||
/// Kerberos instead of NTLM: the KDC as `host` or `host:port` (TCP).
|
||||
pub kerberos_kdc: Option<String>,
|
||||
/// A local folder to share as a drive (Unix only), and the name it appears under.
|
||||
pub shared_folder: Option<(std::path::PathBuf, String)>,
|
||||
/// Offer a printer; jobs are saved as PostScript in this folder.
|
||||
pub printer: Option<(std::path::PathBuf, super::rdp_devices::PrintedFn)>,
|
||||
pub dial: Dial,
|
||||
pub check_cert: CertCheck,
|
||||
pub connect_timeout: Duration,
|
||||
pub on_frame: FrameFn,
|
||||
/// Text the remote desktop copied (the app applies its remote-clipboard preference).
|
||||
pub on_clipboard: ClipboardFn,
|
||||
pub on_error: ErrorFn,
|
||||
pub on_close: CloseFn,
|
||||
}
|
||||
@@ -53,6 +69,8 @@ pub struct Config {
|
||||
enum Input {
|
||||
Ops(Vec<Operation>),
|
||||
Resize(u16, u16),
|
||||
/// Offer local clipboard text to the remote desktop.
|
||||
Clipboard(String),
|
||||
Close,
|
||||
}
|
||||
|
||||
@@ -60,6 +78,9 @@ pub struct Client {
|
||||
cfg: Config,
|
||||
fb: Arc<Mutex<Framebuffer>>,
|
||||
tx: Mutex<Option<Sender<Input>>>,
|
||||
/// Local text offered to the remote clipboard, read by the clipboard channel on request.
|
||||
clip_text: Arc<Mutex<Option<String>>>,
|
||||
clip_rx: Mutex<Option<Receiver<ClipboardMessage>>>,
|
||||
}
|
||||
|
||||
type Tls = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
|
||||
@@ -69,7 +90,7 @@ const POLL: Duration = Duration::from_millis(15);
|
||||
|
||||
impl Client {
|
||||
pub fn new(cfg: Config) -> Arc<Client> {
|
||||
Arc::new(Client { cfg, fb: Arc::default(), tx: Mutex::new(None) })
|
||||
Arc::new(Client { cfg, fb: Arc::default(), tx: Mutex::new(None), clip_text: Arc::default(), clip_rx: Mutex::new(None) })
|
||||
}
|
||||
|
||||
pub fn framebuffer(&self) -> Arc<Mutex<Framebuffer>> {
|
||||
@@ -82,7 +103,8 @@ impl Client {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
*self.tx.lock() = Some(tx);
|
||||
let me = self.clone();
|
||||
std::thread::Builder::new().name("nexus-rdp".into()).spawn(move || {
|
||||
let (on_error, on_close) = (self.cfg.on_error.clone(), self.cfg.on_close.clone());
|
||||
std::thread::Builder::new().name("nexus-rdp".into()).spawn(super::guarded(on_error, on_close, move || {
|
||||
let r = me.run(framed, result, rx);
|
||||
let closing = me.tx.lock().take().is_none();
|
||||
if let Err(e) = r
|
||||
@@ -91,7 +113,7 @@ impl Client {
|
||||
(me.cfg.on_error)(e.to_string());
|
||||
}
|
||||
(me.cfg.on_close)();
|
||||
})?;
|
||||
}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -105,6 +127,11 @@ impl Client {
|
||||
self.send(Input::Resize(width, height));
|
||||
}
|
||||
|
||||
/// Makes `text` the remote clipboard's contents (the remote pastes it on demand).
|
||||
pub fn set_clipboard(&self, text: String) {
|
||||
self.send(Input::Clipboard(text));
|
||||
}
|
||||
|
||||
pub fn close(&self) {
|
||||
if let Some(tx) = self.tx.lock().take() {
|
||||
let _ = tx.send(Input::Close);
|
||||
@@ -120,7 +147,7 @@ impl Client {
|
||||
fn connector_config(&self) -> connector::Config {
|
||||
let c = &self.cfg;
|
||||
connector::Config {
|
||||
credentials: Credentials::UsernamePassword { username: c.username.clone(), password: c.password.clone() },
|
||||
credentials: Credentials::UsernamePassword { username: c.username.clone(), password: c.password.to_string() },
|
||||
domain: (!c.domain.is_empty()).then(|| c.domain.clone()),
|
||||
enable_tls: c.allow_tls_only,
|
||||
enable_credssp: true,
|
||||
@@ -146,7 +173,7 @@ impl Client {
|
||||
request_data: None,
|
||||
// Also hands the credentials to TLS-only servers (xrdp), which would otherwise show their own login screen.
|
||||
autologon: !c.password.is_empty(),
|
||||
enable_audio_playback: false,
|
||||
enable_audio_playback: c.audio,
|
||||
// ponytail: no bulk compression (the bitmap codecs already compress); enabling it means
|
||||
// carrying the decompressor across reactivations.
|
||||
compression_type: None,
|
||||
@@ -170,6 +197,36 @@ impl Client {
|
||||
let mut framed = Framed::new(tcp);
|
||||
let drdynvc = DrdynvcClient::new().with_dynamic_channel(DisplayControlClient::new(|_| Ok(Vec::new())));
|
||||
let mut connector = ClientConnector::new(self.connector_config(), local).with_static_channel(drdynvc);
|
||||
if self.cfg.audio {
|
||||
connector.attach_static_channel(ironrdp::rdpsnd::client::Rdpsnd::new(Box::new(ironrdp_rdpsnd_native::cpal::RdpsndBackend::new())));
|
||||
}
|
||||
if self.cfg.shared_folder.is_some() || self.cfg.printer.is_some() {
|
||||
let mut devices = super::rdp_devices::Devices::default();
|
||||
let mut drives = vec![];
|
||||
#[cfg(unix)]
|
||||
if let Some((folder, name)) = &self.cfg.shared_folder {
|
||||
devices = devices.with_drive(folder).map_err(|e| format!("shared folder {}: {e}", folder.display()))?;
|
||||
drives.push((1, name.clone()));
|
||||
}
|
||||
if let Some((dir, on_printed)) = &self.cfg.printer {
|
||||
devices = devices.with_printer(dir.clone(), on_printed.clone());
|
||||
}
|
||||
let mut rdpdr = ironrdp::rdpdr::Rdpdr::new(Box::new(devices), "Nexus".into());
|
||||
if !drives.is_empty() {
|
||||
rdpdr = rdpdr.with_drives(Some(drives));
|
||||
}
|
||||
if self.cfg.printer.is_some() {
|
||||
rdpdr = rdpdr.with_printer(2, "Nexus Terminal".into());
|
||||
}
|
||||
connector.attach_static_channel(rdpdr);
|
||||
}
|
||||
let (clip_tx, clip_rx) = mpsc::channel();
|
||||
connector.attach_static_channel(CliprdrClient::new(Box::new(TextClipboard {
|
||||
tx: clip_tx,
|
||||
text: self.clip_text.clone(),
|
||||
on_text: self.cfg.on_clipboard.clone(),
|
||||
})));
|
||||
*self.clip_rx.lock() = Some(clip_rx);
|
||||
let should_upgrade = ironrdp_blocking::connect_begin(&mut framed, &mut connector).map_err(|e| format!("RDP connection failed: {e}"))?;
|
||||
|
||||
let tcp = framed.into_inner_no_leftover();
|
||||
@@ -178,14 +235,22 @@ impl Client {
|
||||
(self.cfg.check_cert)(&fingerprint(&cert))?;
|
||||
let upgraded = ironrdp_blocking::mark_as_upgraded(should_upgrade, &mut connector);
|
||||
let mut framed = Framed::new(tls);
|
||||
let kerberos = match &self.cfg.kerberos_kdc {
|
||||
Some(kdc) => {
|
||||
let kdc = if kdc.contains(':') { kdc.clone() } else { format!("{kdc}:88") };
|
||||
let hostname = std::env::var("HOSTNAME").or_else(|_| std::env::var("COMPUTERNAME")).unwrap_or_else(|_| "nexus".into());
|
||||
Some(connector::credssp::KerberosConfig::new(Some(format!("tcp://{kdc}")), hostname).map_err(|e| format!("Kerberos: {e}"))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let result = ironrdp_blocking::connect_finalize(
|
||||
upgraded,
|
||||
connector,
|
||||
&mut framed,
|
||||
&mut NoNetwork,
|
||||
&mut KdcClient,
|
||||
ServerName::new(self.cfg.host.clone()),
|
||||
server_public_key(&cert)?,
|
||||
None,
|
||||
kerberos,
|
||||
)
|
||||
.map_err(|e| format!("RDP logon failed: {}", describe(&e)))?;
|
||||
Ok((framed, result))
|
||||
@@ -209,6 +274,7 @@ impl Client {
|
||||
}
|
||||
.build();
|
||||
let mut input = Database::new();
|
||||
let clip_rx = self.clip_rx.lock().take();
|
||||
// A resize waits here until the Display Control channel is open (it opens after logon).
|
||||
let mut want_size: Option<(u16, u16)> = None;
|
||||
loop {
|
||||
@@ -222,6 +288,14 @@ impl Client {
|
||||
}
|
||||
}
|
||||
Ok(Input::Resize(w, h)) => want_size = Some((w, h)).filter(|&s| s != (image.width(), image.height())),
|
||||
Ok(Input::Clipboard(text)) => {
|
||||
*self.clip_text.lock() = Some(text);
|
||||
if let Some(c) = stage.get_svc_processor_mut::<CliprdrClient>()
|
||||
&& let Ok(msgs) = c.initiate_copy(&[ClipboardFormat::new(ClipboardFormatId::CF_UNICODETEXT)])
|
||||
{
|
||||
outputs.push(ActiveStageOutput::ResponseFrame(stage.process_svc_processor_messages(msgs)?));
|
||||
}
|
||||
}
|
||||
Ok(Input::Close) | Err(mpsc::TryRecvError::Disconnected) => {
|
||||
for o in stage.graceful_shutdown()? {
|
||||
if let ActiveStageOutput::ResponseFrame(f) = o {
|
||||
@@ -233,6 +307,19 @@ impl Client {
|
||||
Err(mpsc::TryRecvError::Empty) => break,
|
||||
}
|
||||
}
|
||||
// Requests the clipboard backend queued while the stage processed server PDUs.
|
||||
for msg in clip_rx.iter().flat_map(|rx| rx.try_iter()) {
|
||||
let Some(c) = stage.get_svc_processor_mut::<CliprdrClient>() else { break };
|
||||
let msgs = match msg {
|
||||
ClipboardMessage::SendInitiateCopy(formats) => c.initiate_copy(&formats),
|
||||
ClipboardMessage::SendFormatData(response) => c.submit_format_data(response),
|
||||
ClipboardMessage::SendInitiatePaste(format) => c.initiate_paste(format),
|
||||
_ => continue,
|
||||
};
|
||||
if let Ok(msgs) = msgs {
|
||||
outputs.push(ActiveStageOutput::ResponseFrame(stage.process_svc_processor_messages(msgs)?));
|
||||
}
|
||||
}
|
||||
if let Some((w, h)) = want_size {
|
||||
let (w, h) = ironrdp::displaycontrol::pdu::MonitorLayoutEntry::adjust_display_size(w.into(), h.into());
|
||||
if let Some(frame) = stage.encode_resize(w, h, None, None) {
|
||||
@@ -291,6 +378,67 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text-only clipboard sharing (CF_UNICODETEXT) over CLIPRDR. Callbacks run inside the active
|
||||
/// stage, so they queue requests for the session loop instead of answering directly.
|
||||
struct TextClipboard {
|
||||
tx: Sender<ClipboardMessage>,
|
||||
text: Arc<Mutex<Option<String>>>,
|
||||
on_text: ClipboardFn,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TextClipboard {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("TextClipboard")
|
||||
}
|
||||
}
|
||||
|
||||
impl ironrdp::core::AsAny for TextClipboard {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl CliprdrBackend for TextClipboard {
|
||||
fn temporary_directory(&self) -> &str {
|
||||
""
|
||||
}
|
||||
fn client_capabilities(&self) -> ClipboardGeneralCapabilityFlags {
|
||||
ClipboardGeneralCapabilityFlags::empty()
|
||||
}
|
||||
fn on_ready(&mut self) {}
|
||||
fn on_request_format_list(&mut self) {
|
||||
let formats = if self.text.lock().is_some() { vec![ClipboardFormat::new(ClipboardFormatId::CF_UNICODETEXT)] } else { vec![] };
|
||||
let _ = self.tx.send(ClipboardMessage::SendInitiateCopy(formats));
|
||||
}
|
||||
fn on_process_negotiated_capabilities(&mut self, _: ClipboardGeneralCapabilityFlags) {}
|
||||
fn on_remote_copy(&mut self, formats: &[ClipboardFormat]) {
|
||||
if formats.iter().any(|f| f.id() == ClipboardFormatId::CF_UNICODETEXT) {
|
||||
let _ = self.tx.send(ClipboardMessage::SendInitiatePaste(ClipboardFormatId::CF_UNICODETEXT));
|
||||
}
|
||||
}
|
||||
fn on_format_data_request(&mut self, request: FormatDataRequest) {
|
||||
let response = match &*self.text.lock() {
|
||||
Some(t) if request.format == ClipboardFormatId::CF_UNICODETEXT => FormatDataResponse::new_unicode_string(t),
|
||||
_ => FormatDataResponse::new_error(),
|
||||
};
|
||||
let _ = self.tx.send(ClipboardMessage::SendFormatData(ironrdp::core::IntoOwned::into_owned(response)));
|
||||
}
|
||||
fn on_format_data_response(&mut self, response: FormatDataResponse<'_>) {
|
||||
if !response.is_error()
|
||||
&& let Ok(text) = response.to_unicode_string()
|
||||
{
|
||||
(self.on_text)(text);
|
||||
}
|
||||
}
|
||||
fn on_file_contents_request(&mut self, _: FileContentsRequest) {}
|
||||
fn on_file_contents_response(&mut self, _: FileContentsResponse<'_>) {}
|
||||
fn on_lock(&mut self, _: LockDataId) {}
|
||||
fn on_unlock(&mut self, _: LockDataId) {}
|
||||
}
|
||||
|
||||
/// One step of a connection sequence: read the PDU it waits for (if any), answer if it says to.
|
||||
fn sequence_step(framed: &mut Framed<Tls>, seq: &mut dyn Sequence, buf: &mut ironrdp::core::WriteBuf) -> Result<()> {
|
||||
buf.clear();
|
||||
@@ -329,6 +477,34 @@ fn copy_rect(image: &DecodedImage, fb: &mut Framebuffer, left: u16, top: u16, ri
|
||||
fb.dirty = true;
|
||||
}
|
||||
|
||||
/// A transport through an RD Gateway (MS-TSGU over HTTPS WebSocket, Basic authentication). The
|
||||
/// gateway's certificate is verified against the web PKI. The async gateway stream is bridged to
|
||||
/// a loopback socket so the blocking RDP client can use it like any other connection.
|
||||
pub fn gateway_dial(endpoint: String, user: String, password: zeroize::Zeroizing<String>, server: String, port: u16) -> Dial {
|
||||
Arc::new(move || {
|
||||
let endpoint = if endpoint.contains(':') { endpoint.clone() } else { format!("{endpoint}:443") };
|
||||
let target = ironrdp_mstsgu::GwConnectTarget {
|
||||
gw_endpoint: endpoint,
|
||||
gw_user: user.clone(),
|
||||
gw_pass: password.to_string(),
|
||||
server: server.clone(),
|
||||
server_port: port,
|
||||
};
|
||||
let (gw, _) = super::rt()
|
||||
.block_on(ironrdp_mstsgu::GwClient::connect(&target, "Nexus Terminal"))
|
||||
.map_err(|e| format!("RD Gateway {}: {}", target.gw_endpoint, error_chain(&e)))?;
|
||||
let (client, server_end) = super::ssh::loopback_pair()?;
|
||||
server_end.set_nonblocking(true)?;
|
||||
super::rt().spawn(async move {
|
||||
if let Ok(mut local) = tokio::net::TcpStream::from_std(server_end) {
|
||||
let mut gw = gw;
|
||||
let _ = tokio::io::copy_bidirectional(&mut local, &mut gw).await;
|
||||
}
|
||||
});
|
||||
Ok(client)
|
||||
})
|
||||
}
|
||||
|
||||
/// `SHA256:<unpadded base64>` of the certificate, the format SSH host keys use.
|
||||
pub fn fingerprint(cert_der: &[u8]) -> String {
|
||||
use base64::Engine;
|
||||
@@ -397,19 +573,47 @@ impl rustls::client::danger::ServerCertVerifier for Pinned {
|
||||
}
|
||||
}
|
||||
|
||||
/// CredSSP asks for this only for Kerberos (talking to a KDC); NTLM never uses it.
|
||||
struct NoNetwork;
|
||||
/// CredSSP's channel to the Kerberos KDC (NTLM never uses it). TCP only, which every KDC serves;
|
||||
/// replies are capped so a hostile KDC can't force a huge allocation.
|
||||
struct KdcClient;
|
||||
|
||||
impl connector::sspi::network_client::NetworkClient for NoNetwork {
|
||||
fn send(&self, _: &connector::sspi::NetworkRequest) -> connector::sspi::Result<Vec<u8>> {
|
||||
Err(connector::sspi::Error::new(connector::sspi::ErrorKind::NoAuthenticatingAuthority, "Kerberos is not supported; use NTLM"))
|
||||
const MAX_KDC_REPLY: u32 = 1 << 20;
|
||||
|
||||
impl connector::sspi::network_client::NetworkClient for KdcClient {
|
||||
fn send(&self, req: &connector::sspi::NetworkRequest) -> connector::sspi::Result<Vec<u8>> {
|
||||
use connector::sspi::{Error, ErrorKind, network_client::NetworkProtocol};
|
||||
use std::io::{Read, Write};
|
||||
let fail = |e: String| Error::new(ErrorKind::NoAuthenticatingAuthority, e);
|
||||
if req.protocol != NetworkProtocol::Tcp {
|
||||
return Err(fail(format!("KDC over {:?} is not supported; use a tcp:// KDC", req.protocol)));
|
||||
}
|
||||
let host = req.url.host_str().ok_or_else(|| fail("KDC URL has no host".into()))?;
|
||||
let port = req.url.port().unwrap_or(88);
|
||||
let mut s = super::proxy::Proxy::default().connect(host, port, Duration::from_secs(5)).map_err(|e| fail(format!("KDC {host}:{port}: {e}")))?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(10))).map_err(|e| fail(e.to_string()))?;
|
||||
// The request is already length-prefixed (RFC 4120 7.2.2); so is the reply.
|
||||
s.write_all(&req.data).map_err(|e| fail(e.to_string()))?;
|
||||
let mut len = [0u8; 4];
|
||||
s.read_exact(&mut len).map_err(|e| fail(e.to_string()))?;
|
||||
let n = u32::from_be_bytes(len);
|
||||
if n > MAX_KDC_REPLY {
|
||||
return Err(fail(format!("KDC reply of {n} bytes is too large")));
|
||||
}
|
||||
let mut buf = len.to_vec();
|
||||
buf.resize(4 + n as usize, 0);
|
||||
s.read_exact(&mut buf[4..]).map_err(|e| fail(e.to_string()))?;
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// Connector errors carry their cause in a chain; surface the useful part.
|
||||
/// IronRDP errors carry their cause in a chain; surface the useful part.
|
||||
fn describe(e: &connector::ConnectorError) -> String {
|
||||
error_chain(e)
|
||||
}
|
||||
|
||||
fn error_chain(e: &dyn std::error::Error) -> String {
|
||||
let mut s = e.to_string();
|
||||
let mut src = std::error::Error::source(e);
|
||||
let mut src = e.source();
|
||||
while let Some(c) = src {
|
||||
s = format!("{s}: {c}");
|
||||
src = c.source();
|
||||
@@ -421,6 +625,33 @@ fn describe(e: &connector::ConnectorError) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kdc_client_speaks_length_prefixed_tcp_and_caps_replies() {
|
||||
use connector::sspi::network_client::{NetworkClient, NetworkProtocol};
|
||||
use std::io::{Read, Write};
|
||||
let kdc = |reply: Vec<u8>| {
|
||||
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = l.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
let (mut s, _) = l.accept().unwrap();
|
||||
let mut req = [0u8; 7];
|
||||
s.read_exact(&mut req).unwrap();
|
||||
assert_eq!(req, [0, 0, 0, 3, b'a', b's', b'k']);
|
||||
s.write_all(&reply).unwrap();
|
||||
});
|
||||
connector::sspi::NetworkRequest {
|
||||
protocol: NetworkProtocol::Tcp,
|
||||
url: format!("tcp://127.0.0.1:{port}").parse().unwrap(),
|
||||
data: b"\0\0\0\x03ask".to_vec(),
|
||||
}
|
||||
};
|
||||
assert_eq!(KdcClient.send(&kdc(b"\0\0\0\x02ok".to_vec())).unwrap(), b"\0\0\0\x02ok");
|
||||
let err = KdcClient.send(&kdc(vec![0xff, 0xff, 0xff, 0xff])).unwrap_err();
|
||||
assert!(err.to_string().contains("too large"), "{err}");
|
||||
let udp = connector::sspi::NetworkRequest { protocol: NetworkProtocol::Udp, url: "udp://127.0.0.1:88".parse().unwrap(), data: vec![] };
|
||||
assert!(KdcClient.send(&udp).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprints_like_ssh() {
|
||||
assert_eq!(fingerprint(b"abc"), "SHA256:ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0");
|
||||
@@ -457,10 +688,14 @@ mod tests {
|
||||
host: host.clone(),
|
||||
username: v[2].into(),
|
||||
domain: String::new(),
|
||||
password: v[3].into(),
|
||||
password: zeroize::Zeroizing::new(v[3].into()),
|
||||
width: 1024,
|
||||
height: 768,
|
||||
allow_tls_only: true,
|
||||
audio: std::env::var("NEXUS_RDP_AUDIO").is_ok(),
|
||||
kerberos_kdc: None,
|
||||
shared_folder: std::env::var("NEXUS_RDP_SHARE").ok().map(|p| (p.into(), "nexus".into())),
|
||||
printer: std::env::var("NEXUS_RDP_PRINT").ok().map(|p| (p.into(), Arc::new(|f: std::path::PathBuf| eprintln!("printed {}", f.display())) as _)),
|
||||
dial: Arc::new(move || Ok(TcpStream::connect((h2.as_str(), port))?)),
|
||||
check_cert: Arc::new(move |fp| {
|
||||
*sc.lock() = fp.to_string();
|
||||
@@ -470,6 +705,7 @@ mod tests {
|
||||
on_frame: Arc::new(move || {
|
||||
f2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}),
|
||||
on_clipboard: Arc::new(|t| eprintln!("remote clipboard: {t:?}")),
|
||||
on_error: Arc::new(|e| eprintln!("on_error: {e}")),
|
||||
on_close: Arc::new(|| eprintln!("on_close")),
|
||||
});
|
||||
@@ -482,6 +718,10 @@ mod tests {
|
||||
c.input(vec![Operation::MouseMove(MousePosition { x: 100, y: 100 })]);
|
||||
c.input(vec![Operation::KeyPressed(Scancode::from_u8(false, 0x1e)), Operation::KeyReleased(Scancode::from_u8(false, 0x1e))]);
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
if std::env::var("NEXUS_RDP_CLIP").is_ok() {
|
||||
c.set_clipboard("from-nexus-123".into());
|
||||
std::thread::sleep(Duration::from_secs(25));
|
||||
}
|
||||
let fb = c.framebuffer().lock().clone();
|
||||
eprintln!("frames {} size {}x{}", frames.load(std::sync::atomic::Ordering::SeqCst), fb.width, fb.height);
|
||||
if let Ok(out) = std::env::var("NEXUS_RDP_PNG") {
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
//! RDP device redirection: a shared folder as a drive, and a virtual printer whose jobs are saved
|
||||
//! as PostScript files.
|
||||
//!
|
||||
//! The drive is confined to one folder. IronRDP's native backend joins the server's paths onto
|
||||
//! the share without checking them, so a hostile server could reach `\..\..\.ssh\id_ed25519`.
|
||||
//! Every path the server sends is checked here first: no `..` components, and after resolving
|
||||
//! symlinks it must stay inside the share. Drives are Unix only (the native backend has no Windows
|
||||
//! implementation); the printer works everywhere.
|
||||
|
||||
use ironrdp::core::impl_as_any;
|
||||
use ironrdp::pdu::PduResult;
|
||||
use ironrdp::rdpdr::RdpdrBackend;
|
||||
use ironrdp::rdpdr::pdu::RdpdrPdu;
|
||||
use ironrdp::rdpdr::pdu::efs::{
|
||||
ClientDriveQueryDirectoryResponse, ClientDriveSetInformationResponse, DeviceCloseResponse, DeviceControlRequest, DeviceCreateResponse, DeviceIoResponse,
|
||||
DeviceWriteResponse, FileInformationClass, Information, NtStatus, PrinterIoRequest, ServerDeviceAnnounceResponse, ServerDriveIoRequest,
|
||||
};
|
||||
use ironrdp::rdpdr::pdu::esc::{ScardCall, ScardIoCtlCode};
|
||||
use ironrdp::svc::SvcMessage;
|
||||
#[cfg(unix)]
|
||||
use ironrdp_rdpdr_native::backend::NixRdpdrBackend;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A print job may not grow past this (a hostile server could otherwise fill the disk).
|
||||
const MAX_PRINT_JOB: u64 = 256 << 20;
|
||||
|
||||
/// Called with the file a finished print job was saved to.
|
||||
pub type PrintedFn = std::sync::Arc<dyn Fn(PathBuf) + Send + Sync>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Devices {
|
||||
#[cfg(unix)]
|
||||
drive: Option<ConfinedDrive>,
|
||||
printer: Option<Spool>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Devices {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Devices")
|
||||
}
|
||||
}
|
||||
|
||||
impl_as_any!(Devices);
|
||||
|
||||
impl Devices {
|
||||
#[cfg(unix)]
|
||||
pub fn with_drive(mut self, folder: &Path) -> std::io::Result<Devices> {
|
||||
self.drive = Some(ConfinedDrive::new(folder)?);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Print jobs go to `dir` as `Nexus print <time>.ps`.
|
||||
pub fn with_printer(mut self, dir: PathBuf, on_printed: PrintedFn) -> Devices {
|
||||
self.printer = Some(Spool { dir, on_printed, jobs: HashMap::new(), next_id: 1 });
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct Spool {
|
||||
dir: PathBuf,
|
||||
on_printed: PrintedFn,
|
||||
jobs: HashMap<u32, (std::fs::File, PathBuf, u64)>,
|
||||
next_id: u32,
|
||||
}
|
||||
|
||||
impl Spool {
|
||||
fn handle(&mut self, req: PrinterIoRequest) -> PduResult<Vec<SvcMessage>> {
|
||||
let pdu = match req {
|
||||
PrinterIoRequest::Create(r) => {
|
||||
let name = format!("Nexus print {}.ps", chrono::Local::now().format("%Y-%m-%d %H.%M.%S"));
|
||||
let path = self.dir.join(name);
|
||||
match std::fs::File::create(&path) {
|
||||
Ok(f) => {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
self.jobs.insert(id, (f, path, 0));
|
||||
RdpdrPdu::DeviceCreateResponse(DeviceCreateResponse {
|
||||
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::SUCCESS),
|
||||
file_id: id,
|
||||
information: Information::FILE_OPENED,
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, dir = %self.dir.display(), "couldn't create a print file");
|
||||
RdpdrPdu::DeviceCreateResponse(DeviceCreateResponse {
|
||||
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::ACCESS_DENIED),
|
||||
file_id: 0,
|
||||
information: Information::empty(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
PrinterIoRequest::Write(r) => {
|
||||
let n = r.write_data.len() as u64;
|
||||
let ok = match self.jobs.get_mut(&r.device_io_request.file_id) {
|
||||
Some((f, _, written)) if *written + n <= MAX_PRINT_JOB => {
|
||||
*written += n;
|
||||
f.write_all(&r.write_data).is_ok()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
RdpdrPdu::DeviceWriteResponse(DeviceWriteResponse {
|
||||
device_io_reply: DeviceIoResponse::new(r.device_io_request, if ok { NtStatus::SUCCESS } else { NtStatus::UNSUCCESSFUL }),
|
||||
length: if ok { n as u32 } else { 0 },
|
||||
})
|
||||
}
|
||||
PrinterIoRequest::Close(r) => {
|
||||
if let Some((f, path, written)) = self.jobs.remove(&r.device_io_request.file_id) {
|
||||
drop(f);
|
||||
if written == 0 {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
} else {
|
||||
(self.on_printed)(path);
|
||||
}
|
||||
}
|
||||
RdpdrPdu::DeviceCloseResponse(DeviceCloseResponse { device_io_response: DeviceIoResponse::new(r.device_io_request, NtStatus::SUCCESS) })
|
||||
}
|
||||
};
|
||||
Ok(vec![SvcMessage::from(pdu)])
|
||||
}
|
||||
}
|
||||
|
||||
impl RdpdrBackend for Devices {
|
||||
fn handle_server_device_announce_response(&mut self, _: ServerDeviceAnnounceResponse) -> PduResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_scard_call(&mut self, _: DeviceControlRequest<ScardIoCtlCode>, _: ScardCall) -> PduResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_drive_io_request(&mut self, req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
|
||||
#[cfg(unix)]
|
||||
if let Some(d) = &mut self.drive {
|
||||
return d.handle(req);
|
||||
}
|
||||
ConfinedDrive::refuse(req)
|
||||
}
|
||||
|
||||
fn handle_printer_io_request(&mut self, req: PrinterIoRequest) -> PduResult<Vec<SvcMessage>> {
|
||||
match &mut self.printer {
|
||||
Some(p) => p.handle(req),
|
||||
None => Ok(vec![SvcMessage::from(RdpdrPdu::DeviceCloseResponse(DeviceCloseResponse {
|
||||
device_io_response: DeviceIoResponse::new(req.into_device_io_request(), NtStatus::NOT_SUPPORTED),
|
||||
}))]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ConfinedDrive {
|
||||
#[cfg(unix)]
|
||||
inner: NixRdpdrBackend,
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
base: PathBuf,
|
||||
}
|
||||
|
||||
impl ConfinedDrive {
|
||||
pub fn new(folder: &Path) -> std::io::Result<ConfinedDrive> {
|
||||
let base = folder.canonicalize()?;
|
||||
if !base.is_dir() {
|
||||
return Err(std::io::Error::other(format!("{} is not a folder", base.display())));
|
||||
}
|
||||
Ok(ConfinedDrive {
|
||||
#[cfg(unix)]
|
||||
inner: NixRdpdrBackend::new(base.to_string_lossy().trim_end_matches('/').to_string()),
|
||||
base,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a server path (`\dir\file`, Windows separators) stays inside the share.
|
||||
fn allowed(&self, server_path: &str) -> bool {
|
||||
let rel = server_path.replace('\\', "/");
|
||||
if rel.contains('\0') {
|
||||
return false;
|
||||
}
|
||||
let mut p = self.base.clone();
|
||||
for c in rel.split('/').filter(|c| !c.is_empty() && *c != ".") {
|
||||
if c == ".." {
|
||||
return false;
|
||||
}
|
||||
p.push(c);
|
||||
}
|
||||
// The deepest part that exists must resolve (through any symlinks) inside the share; what
|
||||
// doesn't exist yet can't be a link.
|
||||
let mut probe = p.as_path();
|
||||
loop {
|
||||
if probe.symlink_metadata().is_ok() {
|
||||
return probe.canonicalize().is_ok_and(|real| real.starts_with(&self.base));
|
||||
}
|
||||
match probe.parent() {
|
||||
Some(parent) if parent.starts_with(&self.base) => probe = parent,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refuse(req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
|
||||
tracing::warn!("RDP server asked for a path outside the shared folder; refused");
|
||||
let pdu = match req {
|
||||
ServerDriveIoRequest::ServerCreateDriveRequest(r) => RdpdrPdu::DeviceCreateResponse(DeviceCreateResponse {
|
||||
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::ACCESS_DENIED),
|
||||
file_id: 0,
|
||||
information: Information::empty(),
|
||||
}),
|
||||
ServerDriveIoRequest::ServerDriveQueryDirectoryRequest(r) => RdpdrPdu::ClientDriveQueryDirectoryResponse(ClientDriveQueryDirectoryResponse {
|
||||
device_io_reply: DeviceIoResponse::new(r.device_io_request, NtStatus::NO_MORE_FILES),
|
||||
buffer: None,
|
||||
}),
|
||||
ServerDriveIoRequest::ServerDriveSetInformationRequest(r) => RdpdrPdu::ClientDriveSetInformationResponse(
|
||||
ClientDriveSetInformationResponse::new(&r, NtStatus::ACCESS_DENIED).map_err(|e| ironrdp::pdu::encode_err!(e))?,
|
||||
),
|
||||
_ => return Ok(vec![]),
|
||||
};
|
||||
Ok(vec![SvcMessage::from(pdu)])
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfinedDrive {
|
||||
#[cfg(unix)]
|
||||
fn handle(&mut self, req: ServerDriveIoRequest) -> PduResult<Vec<SvcMessage>> {
|
||||
let ok = match &req {
|
||||
ServerDriveIoRequest::ServerCreateDriveRequest(r) => self.allowed(&r.path),
|
||||
ServerDriveIoRequest::ServerDriveQueryDirectoryRequest(r) => r.initial_query == 0 || self.allowed(r.path.trim_end_matches('*')),
|
||||
ServerDriveIoRequest::ServerDriveSetInformationRequest(r) => match &r.set_buffer {
|
||||
FileInformationClass::Rename(info) => self.allowed(&info.file_name),
|
||||
_ => true,
|
||||
},
|
||||
// Everything else names a file by an id that a checked create handed out.
|
||||
_ => true,
|
||||
};
|
||||
if ok { self.inner.handle_drive_io_request(req) } else { Self::refuse(req) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn print_jobs_are_saved_and_capped() {
|
||||
use ironrdp::rdpdr::pdu::efs::{
|
||||
CreateDisposition, CreateOptions, DesiredAccess, DeviceCloseRequest, DeviceCreateRequest, DeviceIoRequest, DeviceWriteRequest, FileAttributes,
|
||||
MajorFunction, SharedAccess,
|
||||
};
|
||||
let dir = std::env::temp_dir().join(format!("nexus-print-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let printed: std::sync::Arc<parking_lot::Mutex<Vec<PathBuf>>> = Default::default();
|
||||
let p2 = printed.clone();
|
||||
let mut dev = Devices::default().with_printer(dir.clone(), std::sync::Arc::new(move |f| p2.lock().push(f)));
|
||||
let io = |file_id, major| DeviceIoRequest { device_id: 2, file_id, completion_id: 1, major_function: major, minor_function: 0.into() };
|
||||
let create = || {
|
||||
PrinterIoRequest::Create(DeviceCreateRequest {
|
||||
device_io_request: io(0, MajorFunction::Create),
|
||||
desired_access: DesiredAccess::empty(),
|
||||
allocation_size: 0,
|
||||
file_attributes: FileAttributes::empty(),
|
||||
shared_access: SharedAccess::empty(),
|
||||
create_disposition: CreateDisposition::FILE_OPEN,
|
||||
create_options: CreateOptions::empty(),
|
||||
path: String::new(),
|
||||
})
|
||||
};
|
||||
let write = |id, data: &[u8]| {
|
||||
PrinterIoRequest::Write(DeviceWriteRequest { device_io_request: io(id, MajorFunction::Write), offset: 0, write_data: data.to_vec() })
|
||||
};
|
||||
let close = |id| PrinterIoRequest::Close(DeviceCloseRequest { device_io_request: io(id, MajorFunction::Close) });
|
||||
dev.handle_printer_io_request(create()).unwrap();
|
||||
dev.handle_printer_io_request(write(1, b"%!PS-Adobe-3.0\n")).unwrap();
|
||||
dev.handle_printer_io_request(write(1, b"showpage\n")).unwrap();
|
||||
dev.handle_printer_io_request(close(1)).unwrap();
|
||||
let files = printed.lock().clone();
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&files[0]).unwrap(), "%!PS-Adobe-3.0\nshowpage\n");
|
||||
// An empty job leaves no file behind; writes past the cap are refused.
|
||||
dev.handle_printer_io_request(create()).unwrap();
|
||||
dev.handle_printer_io_request(close(2)).unwrap();
|
||||
dev.handle_printer_io_request(create()).unwrap();
|
||||
dev.printer.as_mut().unwrap().jobs.get_mut(&3).unwrap().2 = MAX_PRINT_JOB;
|
||||
dev.handle_printer_io_request(write(3, b"x")).unwrap();
|
||||
assert_eq!(dev.printer.as_ref().unwrap().jobs[&3].2, MAX_PRINT_JOB);
|
||||
assert_eq!(printed.lock().len(), 1);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_paths_stay_inside_the_share() {
|
||||
let root = std::env::temp_dir().join(format!("nexus-drive-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let share = root.join("share");
|
||||
std::fs::create_dir_all(share.join("sub")).unwrap();
|
||||
std::fs::write(root.join("secret"), "x").unwrap();
|
||||
std::os::unix::fs::symlink(&root, share.join("escape")).unwrap();
|
||||
std::os::unix::fs::symlink(share.join("sub"), share.join("inside")).unwrap();
|
||||
let d = ConfinedDrive::new(&share).unwrap();
|
||||
for ok in ["\\", "\\sub", "\\sub\\new.txt", "\\new\\deeper\\file", "\\inside\\x", "\\.\\sub"] {
|
||||
assert!(d.allowed(ok), "{ok}");
|
||||
}
|
||||
for bad in ["\\..\\secret", "\\sub\\..\\..\\secret", "\\escape\\secret", "\\escape\\new", "\\a\0b"] {
|
||||
assert!(!d.allowed(bad), "{bad:?}");
|
||||
}
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ impl SerialClient {
|
||||
*guard = Some((port, stop.clone()));
|
||||
}
|
||||
let me = inner.clone();
|
||||
std::thread::spawn(move || me.read_loop(reader, stop));
|
||||
std::thread::spawn(super::guarded(inner.cb.on_error.clone(), inner.cb.on_close.clone(), move || me.read_loop(reader, stop)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,8 @@ pub struct HostKeyInfo {
|
||||
|
||||
pub type HostKeyCheck = Arc<dyn Fn(&HostKeyInfo) -> std::result::Result<(), String> + Send + Sync>;
|
||||
/// Blocking credential source (may prompt the user).
|
||||
pub type SecretFn = Arc<dyn Fn() -> Result<String> + Send + Sync>;
|
||||
/// The value is wiped from memory when dropped; libraries that need a plain `String` get a copy.
|
||||
pub type SecretFn = Arc<dyn Fn() -> Result<zeroize::Zeroizing<String>> + Send + Sync>;
|
||||
|
||||
pub fn host_key_info(host: &str, port: u16, key: &PublicKey) -> HostKeyInfo {
|
||||
HostKeyInfo {
|
||||
@@ -60,6 +61,22 @@ struct Handler {
|
||||
port: u16,
|
||||
check: HostKeyCheck,
|
||||
shared: Arc<Shared>,
|
||||
/// Certificate authorities trusted for this host (from `@cert-authority` known-hosts rows).
|
||||
cas: Vec<PublicKey>,
|
||||
}
|
||||
|
||||
/// A host certificate is trusted when a CA for this host signed it, it is a host certificate,
|
||||
/// it names the host as a principal and it is inside its validity window.
|
||||
fn check_host_certificate(cert: &russh::keys::Certificate, cas: &[PublicKey], host: &str) -> std::result::Result<(), String> {
|
||||
use russh::keys::ssh_key::certificate::CertType;
|
||||
if cert.cert_type() != CertType::Host {
|
||||
return Err(format!("{host} presented a user certificate as its host key"));
|
||||
}
|
||||
if !cert.valid_principals().iter().any(|p| p.eq_ignore_ascii_case(host)) {
|
||||
return Err(format!("host certificate for {host} doesn't list it (principals: {})", cert.valid_principals().join(", ")));
|
||||
}
|
||||
let fps: Vec<_> = cas.iter().map(|k| k.fingerprint(HashAlg::Sha256)).collect();
|
||||
cert.validate(&fps).map_err(|_| format!("host certificate for {host} isn't signed by a trusted CA, or is expired"))
|
||||
}
|
||||
|
||||
impl client::Handler for Handler {
|
||||
@@ -68,7 +85,19 @@ impl client::Handler for Handler {
|
||||
async fn check_server_key(&mut self, key: &russh::keys::PublicKeyOrCertificate) -> std::result::Result<bool, Self::Error> {
|
||||
let key = match key {
|
||||
russh::keys::PublicKeyOrCertificate::PublicKey { key, .. } => key.clone(),
|
||||
russh::keys::PublicKeyOrCertificate::Certificate(c) => c.public_key().clone().into(),
|
||||
// Only asked for when a CA covers this host, so it must check out against one.
|
||||
russh::keys::PublicKeyOrCertificate::Certificate(c) => {
|
||||
return match check_host_certificate(c, &self.cas, &self.host) {
|
||||
Ok(()) => {
|
||||
tracing::info!(host = %self.host, ca = %c.signature_key().fingerprint(HashAlg::Sha256), "host certificate accepted");
|
||||
Ok(true)
|
||||
}
|
||||
Err(why) => {
|
||||
*self.shared.rejection.lock() = Some(why);
|
||||
Ok(false)
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
let info = host_key_info(&self.host, self.port, &key);
|
||||
let check = self.check.clone();
|
||||
@@ -200,6 +229,15 @@ fn base32_decode(s: &str) -> Option<Vec<u8>> {
|
||||
}
|
||||
|
||||
/// Reads an OpenSSH/PEM private key, asking for a passphrase only if it's encrypted.
|
||||
/// The OpenSSH user certificate next to a private key (`id_ed25519` → `id_ed25519-cert.pub`).
|
||||
fn load_user_certificate(key_path: &str) -> Option<russh::keys::Certificate> {
|
||||
if key_path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let text = std::fs::read_to_string(format!("{key_path}-cert.pub")).ok().filter(|t| t.len() < 64 << 10)?;
|
||||
russh::keys::Certificate::from_openssh(text.trim()).ok()
|
||||
}
|
||||
|
||||
pub fn load_private_key(path: &str, passphrase: Option<&SecretFn>) -> Result<russh::keys::PrivateKey> {
|
||||
let meta = std::fs::metadata(path).map_err(|e| format!("unable to stat key file: {e}"))?;
|
||||
if meta.is_dir() {
|
||||
@@ -239,8 +277,12 @@ async fn dial(sc: &SshConfig, proxy_password: &str, host: &str, port: u16, timeo
|
||||
Ok(tokio::net::TcpStream::from_std(s)?)
|
||||
}
|
||||
|
||||
fn config(sc: &SshConfig) -> Arc<client::Config> {
|
||||
/// `host_certificates`: ask for a host certificate first (when a CA applies), as OpenSSH does.
|
||||
fn config(sc: &SshConfig, host_certificates: bool) -> Arc<client::Config> {
|
||||
let mut c = client::Config::default();
|
||||
if host_certificates {
|
||||
c.preferred.host_key_certificates = c.preferred.key.clone();
|
||||
}
|
||||
if sc.keepalive_interval > 0 {
|
||||
c.keepalive_interval = Some(Duration::from_secs(sc.keepalive_interval as u64));
|
||||
c.keepalive_max = sc.keepalive_count_max.max(1) as usize;
|
||||
@@ -259,6 +301,8 @@ struct Auth<'a> {
|
||||
methods: Vec<String>,
|
||||
agent: bool,
|
||||
key: Option<russh::keys::PrivateKey>,
|
||||
/// `<key>-cert.pub` next to the private key: log in with the certificate instead.
|
||||
cert: Option<russh::keys::Certificate>,
|
||||
password: Option<SecretFn>,
|
||||
totp_secret: String,
|
||||
}
|
||||
@@ -281,6 +325,11 @@ async fn authenticate(h: &mut Handle<Handler>, a: Auth<'_>) -> Result<()> {
|
||||
for m in &a.methods {
|
||||
match m.as_str() {
|
||||
"publickey" => {
|
||||
if let (Some(k), Some(cert)) = (&a.key, &a.cert)
|
||||
&& h.authenticate_openssh_cert(a.user, Arc::new(k.clone()), cert.clone()).await?.success()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(k) = &a.key {
|
||||
let hash = if k.algorithm().is_rsa() { h.best_supported_rsa_hash().await?.flatten() } else { None };
|
||||
if h.authenticate_publickey(a.user, PrivateKeyWithHashAlg::new(Arc::new(k.clone()), hash)).await?.success() {
|
||||
@@ -291,7 +340,7 @@ async fn authenticate(h: &mut Handle<Handler>, a: Auth<'_>) -> Result<()> {
|
||||
"password" => {
|
||||
if let Some(get) = a.password.clone() {
|
||||
let pw = blocking(move || get()).await?;
|
||||
if h.authenticate_password(a.user, pw).await?.success() {
|
||||
if h.authenticate_password(a.user, pw.as_str()).await?.success() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -310,7 +359,7 @@ async fn authenticate(h: &mut Handle<Handler>, a: Auth<'_>) -> Result<()> {
|
||||
answers.push(totp_code(&a.totp_secret).map_err(|e| format!("failed to generate TOTP code: {e}"))?);
|
||||
} else {
|
||||
let get = get.clone();
|
||||
answers.push(blocking(move || get()).await?);
|
||||
answers.push(blocking(move || get()).await?.to_string());
|
||||
}
|
||||
}
|
||||
resp = h.authenticate_keyboard_interactive_respond(answers).await?;
|
||||
@@ -348,6 +397,8 @@ pub struct SshClient {
|
||||
/// Credentials that live in the secret store rather than the profile: (TOTP seed, proxy
|
||||
/// password). Set by the session manager before connecting.
|
||||
stored: Mutex<(Zeroizing<String>, Zeroizing<String>)>,
|
||||
/// `@cert-authority` known-hosts rows (CA keys by host pattern), for host certificates.
|
||||
authorities: Mutex<Vec<crate::models::KnownHost>>,
|
||||
}
|
||||
|
||||
impl SshClient {
|
||||
@@ -363,9 +414,15 @@ impl SshClient {
|
||||
sftp: tokio::sync::Mutex::new(None),
|
||||
closed: false.into(),
|
||||
stored: Mutex::default(),
|
||||
authorities: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Certificate authorities (known-hosts CA rows) to trust for host certificates.
|
||||
pub fn set_authorities(&self, rows: Vec<crate::models::KnownHost>) {
|
||||
*self.authorities.lock() = rows;
|
||||
}
|
||||
|
||||
/// The TOTP seed (for keyboard-interactive 2FA prompts) and proxy password to use.
|
||||
pub fn set_stored_secrets(&self, totp_secret: String, proxy_password: String) {
|
||||
*self.stored.lock() = (Zeroizing::new(totp_secret), Zeroizing::new(proxy_password));
|
||||
@@ -413,9 +470,11 @@ impl SshClient {
|
||||
port: u16,
|
||||
check: &HostKeyCheck,
|
||||
) -> Result<Handle<Handler>> {
|
||||
let handler = Handler { host: host.into(), port, check: check.clone(), shared: self.shared.clone() };
|
||||
let cas = crate::known_hosts::authorities_for(&self.authorities.lock(), host, port);
|
||||
let cfg = config(&self.sc(), !cas.is_empty());
|
||||
let handler = Handler { host: host.into(), port, check: check.clone(), shared: self.shared.clone(), cas };
|
||||
let timeout = Duration::from_secs(self.profile.connect_timeout.max(1) as u64);
|
||||
match tokio::time::timeout(timeout, client::connect_stream(config(&self.sc()), stream, handler)).await {
|
||||
match tokio::time::timeout(timeout, client::connect_stream(cfg, stream, handler)).await {
|
||||
Err(_) => Err(format!("SSH handshake with {host}:{port} timed out").into()),
|
||||
Ok(Ok(h)) => Ok(h),
|
||||
Ok(Err(e)) => match self.shared.rejection.lock().take() {
|
||||
@@ -460,7 +519,8 @@ impl SshClient {
|
||||
self.handshake(ch.into_stream(), &p.host, port, &check).await?
|
||||
};
|
||||
|
||||
authenticate(&mut handle, Auth { user: &p.username, methods, agent: sc.agent_auth, key, password, totp_secret }).await?;
|
||||
let cert = load_user_certificate(&sc.private_key_path);
|
||||
authenticate(&mut handle, Auth { user: &p.username, methods, agent: sc.agent_auth, key, cert, password, totp_secret }).await?;
|
||||
let handle = Arc::new(handle);
|
||||
if !shell {
|
||||
*self.handle.lock() = Some(handle);
|
||||
@@ -502,7 +562,7 @@ impl SshClient {
|
||||
}
|
||||
});
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
super::guarded_task(self.cb.on_error.clone(), self.cb.on_close.clone(), async move {
|
||||
while let Some(msg) = read.wait().await {
|
||||
match msg {
|
||||
ChannelMsg::Data { data } | ChannelMsg::ExtendedData { data, .. } => (me.cb.on_data)(&data),
|
||||
@@ -557,6 +617,7 @@ impl SshClient {
|
||||
methods: vec!["publickey".into()],
|
||||
agent: key.is_none() || sc.agent_auth,
|
||||
key,
|
||||
cert: None,
|
||||
password: None,
|
||||
totp_secret: String::new(),
|
||||
},
|
||||
@@ -848,7 +909,7 @@ mod tests {
|
||||
// Encrypted: unreadable without the passphrase, readable with it.
|
||||
let p = path.to_string_lossy().into_owned();
|
||||
assert!(load_private_key(&p, None).is_err());
|
||||
let pp: SecretFn = Arc::new(|| Ok("pass phrase".into()));
|
||||
let pp: SecretFn = Arc::new(|| Ok(zeroize::Zeroizing::new("pass phrase".into())));
|
||||
assert_eq!(load_private_key(&p, Some(&pp)).unwrap().algorithm().as_str(), "ssh-ed25519");
|
||||
assert!(generate_key_pair(&dir, "id_test", "ed25519", 0, "").is_err(), "must not overwrite");
|
||||
let plain = generate_key_pair(&dir, "id_plain", "ecdsa", 0, "").unwrap();
|
||||
|
||||
@@ -314,6 +314,17 @@ fn encode_outgoing(data: &[u8], encoding: &str) -> Vec<u8> {
|
||||
if super::is_latin1(encoding) { super::utf8_to_latin1(data) } else { data.to_vec() }
|
||||
}
|
||||
|
||||
/// Fuzzing entry point: `data` through the IAC negotiation parser, in uneven chunks.
|
||||
#[cfg(feature = "fuzzing")]
|
||||
#[doc(hidden)]
|
||||
pub fn fuzz_negotiation(data: &[u8]) {
|
||||
let c = TelnetClient::new(&crate::models::Profile::new(crate::models::Protocol::Telnet), Callbacks::noop(), None);
|
||||
let mut pending = Vec::new();
|
||||
for chunk in data.chunks(37) {
|
||||
c.inner.process(&mut pending, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -164,7 +164,7 @@ impl Client {
|
||||
*self.out.lock() = Some(out_tx);
|
||||
|
||||
let client = self.clone();
|
||||
std::thread::spawn(move || client.io_thread(out_rx));
|
||||
std::thread::spawn(super::guarded(self.cfg.on_error.clone(), self.cfg.on_close.clone(), move || client.io_thread(out_rx)));
|
||||
|
||||
let timeout = self.cfg.connect_timeout;
|
||||
match ready_rx.recv_timeout(timeout) {
|
||||
@@ -861,6 +861,19 @@ pub fn keysym_for(name: &str, ch: Option<char>) -> Option<u32> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fuzzing entry point: `data` as a stream of FramebufferUpdate messages into a 64x64 desktop.
|
||||
#[cfg(feature = "fuzzing")]
|
||||
#[doc(hidden)]
|
||||
pub fn fuzz_updates(data: &[u8]) {
|
||||
let (mut fb, mut dec) = (Framebuffer::new(64, 64), Decoders::default());
|
||||
let mut r = data;
|
||||
while !r.is_empty() && read_update(&mut r, &mut fb, &mut dec).is_ok() {
|
||||
if fb.width as usize * fb.height as usize > 1 << 20 {
|
||||
fb = Framebuffer::new(64, 64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -36,16 +36,33 @@ pub fn encrypt_and_export(profiles: &[Profile], password: &str, path: &Path) ->
|
||||
profiles: profiles.to_vec(),
|
||||
count: profiles.len(),
|
||||
};
|
||||
let plain = serde_json::to_vec_pretty(&bundle)?;
|
||||
crate::secrets::write_private(path, &seal(&serde_json::to_vec_pretty(&bundle)?, password)?)
|
||||
}
|
||||
|
||||
/// `[version][salt 32][nonce 12][AES-256-GCM ciphertext]` under an Argon2id key from `password`.
|
||||
pub fn seal(plain: &[u8], password: &str) -> Result<Vec<u8>> {
|
||||
let salt = random_bytes::<32>();
|
||||
let nonce = random_bytes::<12>();
|
||||
let key = derive_key(password, &salt)?;
|
||||
let ct = Aes256Gcm::new((&*key).into()).encrypt(Nonce::from_slice(&nonce), plain.as_slice()).map_err(|e| e.to_string())?;
|
||||
let ct = Aes256Gcm::new((&*key).into()).encrypt(Nonce::from_slice(&nonce), plain).map_err(|e| e.to_string())?;
|
||||
let mut out = vec![VERSION];
|
||||
out.extend(salt);
|
||||
out.extend(nonce);
|
||||
out.extend(ct);
|
||||
crate::secrets::write_private(path, &out)
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn open(data: &[u8], password: &str) -> Result<Vec<u8>> {
|
||||
if data.len() < 1 + 32 + 12 + 1 + 16 {
|
||||
return Err("exportimport: file is too small or corrupt".into());
|
||||
}
|
||||
if data[0] != VERSION {
|
||||
return Err(format!("exportimport: unsupported format version {}", data[0]).into());
|
||||
}
|
||||
let key = derive_key(password, &data[1..33])?;
|
||||
Ok(Aes256Gcm::new((&*key).into())
|
||||
.decrypt(Nonce::from_slice(&data[33..45]), &data[45..])
|
||||
.map_err(|_| "exportimport: decryption failed — wrong password or corrupt file")?)
|
||||
}
|
||||
|
||||
pub fn decrypt_and_import(path: &Path, password: &str) -> Result<Vec<Profile>> {
|
||||
@@ -55,17 +72,7 @@ pub fn decrypt_and_import(path: &Path, password: &str) -> Result<Vec<Profile>> {
|
||||
if std::fs::metadata(path)?.len() > MAX_IMPORT_BYTES {
|
||||
return Err("exportimport: file is too large (max 10 MiB)".into());
|
||||
}
|
||||
let data = std::fs::read(path)?;
|
||||
if data.len() < 1 + 32 + 12 + 1 + 16 {
|
||||
return Err("exportimport: file is too small or corrupt".into());
|
||||
}
|
||||
if data[0] != VERSION {
|
||||
return Err(format!("exportimport: unsupported format version {}", data[0]).into());
|
||||
}
|
||||
let key = derive_key(password, &data[1..33])?;
|
||||
let plain = Aes256Gcm::new((&*key).into())
|
||||
.decrypt(Nonce::from_slice(&data[33..45]), &data[45..])
|
||||
.map_err(|_| "exportimport: decryption failed — wrong password or corrupt file")?;
|
||||
let plain = open(&std::fs::read(path)?, password)?;
|
||||
let bundle: Bundle = serde_json::from_slice(&plain).map_err(|e| format!("exportimport: invalid bundle JSON: {e}"))?;
|
||||
Ok(bundle.profiles)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
//! OpenSSH `known_hosts` interchange and SSH certificate authorities.
|
||||
//!
|
||||
//! Imported host keys become ordinary known-host rows. `@cert-authority` lines become rows with
|
||||
//! `key_type` [`CA_KEY_TYPE`], the host *pattern* as `host`, port 0, and the CA's public key in
|
||||
//! OpenSSH form; a host certificate signed by a CA whose pattern matches the host is trusted
|
||||
//! without a first-use prompt. Hashed entries (`|1|…`) can't be mapped back to a host name and
|
||||
//! are skipped, as are `@revoked` lines.
|
||||
|
||||
use crate::models::KnownHost;
|
||||
use russh::keys::{HashAlg, PublicKey};
|
||||
|
||||
/// `key_type` of a certificate-authority row.
|
||||
pub const CA_KEY_TYPE: &str = "@cert-authority";
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Parsed {
|
||||
pub hosts: Vec<(String, u16, PublicKey)>,
|
||||
/// (host pattern, CA key)
|
||||
pub authorities: Vec<(String, PublicKey)>,
|
||||
/// Lines skipped: hashed host names, revocations, unparseable keys, wildcard host keys.
|
||||
pub skipped: usize,
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Parsed {
|
||||
let mut out = Parsed::default();
|
||||
for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
|
||||
let mut fields = line.split_whitespace().peekable();
|
||||
let marker = fields.next_if(|f| f.starts_with('@'));
|
||||
let (Some(hosts), Some(kind), Some(b64)) = (fields.next(), fields.next(), fields.next()) else {
|
||||
out.skipped += 1;
|
||||
continue;
|
||||
};
|
||||
let Ok(key) = PublicKey::from_openssh(&format!("{kind} {b64}")) else {
|
||||
out.skipped += 1;
|
||||
continue;
|
||||
};
|
||||
match marker {
|
||||
Some("@cert-authority") => out.authorities.push((hosts.to_string(), key)),
|
||||
Some(_) => out.skipped += 1,
|
||||
None if hosts.starts_with('|') => out.skipped += 1,
|
||||
None => {
|
||||
for h in hosts.split(',') {
|
||||
let (host, port) = split_host(h);
|
||||
if host.contains(['*', '?', '!']) {
|
||||
out.skipped += 1;
|
||||
} else {
|
||||
out.hosts.push((host.to_string(), port, key.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `[host]:port` → (host, port); a bare host is port 22.
|
||||
fn split_host(h: &str) -> (&str, u16) {
|
||||
if let Some(rest) = h.strip_prefix('[')
|
||||
&& let Some((host, port)) = rest.split_once("]:")
|
||||
&& let Ok(p) = port.parse()
|
||||
{
|
||||
return (host, p);
|
||||
}
|
||||
(h, 22)
|
||||
}
|
||||
|
||||
/// OpenSSH form of a host: `host` on port 22, `[host]:port` otherwise.
|
||||
fn host_field(host: &str, port: i64) -> String {
|
||||
if port == 22 { host.to_string() } else { format!("[{host}]:{port}") }
|
||||
}
|
||||
|
||||
/// Known-hosts lines for `rows` (SSH host keys and CAs; other protocols' certificates are left out).
|
||||
pub fn export(rows: &[KnownHost]) -> String {
|
||||
let mut out = String::new();
|
||||
for kh in rows {
|
||||
if kh.key_type == CA_KEY_TYPE {
|
||||
out += &format!("@cert-authority {} {}\n", kh.host, kh.public_key);
|
||||
} else if !kh.public_key.is_empty() && ["ssh-", "ecdsa-", "sk-"].iter().any(|p| kh.key_type.starts_with(p)) {
|
||||
out += &format!("{} {} {}\n", host_field(&kh.host, kh.port), kh.key_type, kh.public_key);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A row for a CA under a host pattern.
|
||||
pub fn authority_row(pattern: &str, key: &PublicKey) -> KnownHost {
|
||||
let now = crate::models::now();
|
||||
KnownHost {
|
||||
id: String::new(),
|
||||
host: pattern.into(),
|
||||
port: 0,
|
||||
key_type: CA_KEY_TYPE.into(),
|
||||
fingerprint: key.fingerprint(HashAlg::Sha256).to_string(),
|
||||
public_key: key.to_openssh().unwrap_or_default(),
|
||||
first_seen: now,
|
||||
last_seen: now,
|
||||
trusted: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `host:port` matches an OpenSSH host pattern list (`*`, `?`, `!negation`, commas). As in
|
||||
/// OpenSSH, patterns match `host` for port 22 and `[host]:port` otherwise, so `[*.corp]:*`
|
||||
/// covers every port.
|
||||
pub fn pattern_matches(patterns: &str, host: &str, port: u16) -> bool {
|
||||
let target = host_field(host, port.into()).to_ascii_lowercase();
|
||||
let mut matched = false;
|
||||
for p in patterns.split(',') {
|
||||
let (neg, p) = p.strip_prefix('!').map_or((false, p), |r| (true, r));
|
||||
if glob(&p.to_ascii_lowercase(), &target) {
|
||||
if neg {
|
||||
return false;
|
||||
}
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
matched
|
||||
}
|
||||
|
||||
fn glob(p: &str, s: &str) -> bool {
|
||||
match (p.chars().next(), s.chars().next()) {
|
||||
(None, None) => true,
|
||||
(Some('*'), _) => glob(&p[1..], s) || (!s.is_empty() && glob(p, &s[s.chars().next().unwrap().len_utf8()..])),
|
||||
(Some('?'), Some(c)) => glob(&p[1..], &s[c.len_utf8()..]),
|
||||
(Some(a), Some(b)) if a == b => glob(&p[a.len_utf8()..], &s[b.len_utf8()..]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// CA keys trusted for `host:port`.
|
||||
pub fn authorities_for(rows: &[KnownHost], host: &str, port: u16) -> Vec<PublicKey> {
|
||||
rows.iter()
|
||||
.filter(|r| r.key_type == CA_KEY_TYPE && pattern_matches(&r.host, host, port))
|
||||
.filter_map(|r| PublicKey::from_openssh(&r.public_key).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(non_snake_case)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A real (deterministic) Ed25519 public key in OpenSSH form.
|
||||
fn ed() -> String {
|
||||
use russh::keys::ssh_key::private::Ed25519Keypair;
|
||||
let kp = Ed25519Keypair::from_seed(&[7; 32]);
|
||||
PublicKey::new(kp.public.into(), "").to_openssh().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_openssh_known_hosts() {
|
||||
let ED = ed();
|
||||
let text = format!(
|
||||
"# comment\n\
|
||||
github.com,140.82.112.3 {ED}\n\
|
||||
[git.example.com]:2222 {ED} laptop\n\
|
||||
|1|abc=|def= {ED}\n\
|
||||
*.wild {ED}\n\
|
||||
@cert-authority *.corp.example,!bad.corp.example {ED}\n\
|
||||
@revoked old.example {ED}\n\
|
||||
broken ssh-ed25519 notbase64\n"
|
||||
);
|
||||
let p = parse(&text);
|
||||
let hosts: Vec<_> = p.hosts.iter().map(|(h, port, _)| (h.as_str(), *port)).collect();
|
||||
assert_eq!(hosts, [("github.com", 22), ("140.82.112.3", 22), ("git.example.com", 2222)]);
|
||||
assert_eq!(p.authorities.len(), 1);
|
||||
assert_eq!(p.skipped, 4, "hashed, wildcard, revoked, broken");
|
||||
assert_eq!(p.authorities[0].0, "*.corp.example,!bad.corp.example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_patterns() {
|
||||
let pats = "*.corp.example,!bad.corp.example,[jump.?.example]:2200,[*.any]:*";
|
||||
assert!(pattern_matches(pats, "x.any", 2201) && !pattern_matches(pats, "x.any", 22), "[..]:* is any port but 22");
|
||||
assert!(pattern_matches(pats, "web.corp.example", 22));
|
||||
assert!(pattern_matches(pats, "WEB.Corp.Example", 22), "case-insensitive");
|
||||
assert!(!pattern_matches(pats, "bad.corp.example", 22), "negated");
|
||||
assert!(!pattern_matches(pats, "web.corp.example", 2222), "bare patterns are port 22");
|
||||
assert!(pattern_matches(pats, "jump.a.example", 2200));
|
||||
assert!(!pattern_matches(pats, "jump.ab.example", 2200));
|
||||
assert!(!pattern_matches(pats, "corp.example", 22));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_what_it_imports() {
|
||||
let ED = ed();
|
||||
let p = parse(&format!("[h.example]:2022 {ED}\n@cert-authority *.corp {ED}\n"));
|
||||
let (h, port, key) = &p.hosts[0];
|
||||
let mut row = authority_row("x", key);
|
||||
row.host = h.clone();
|
||||
row.port = *port as i64;
|
||||
row.key_type = key.algorithm().as_str().into();
|
||||
row.public_key = ED.split_whitespace().nth(1).unwrap().into();
|
||||
let ca = authority_row(&p.authorities[0].0, &p.authorities[0].1);
|
||||
let out = export(&[row, ca.clone()]);
|
||||
assert_eq!(out, format!("[h.example]:2022 {ED}\n@cert-authority *.corp {ED}\n"));
|
||||
assert_eq!(authorities_for(&[ca], "db.corp", 22).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub mod config;
|
||||
pub mod exportimport;
|
||||
pub mod ircformat;
|
||||
pub mod keyfiles;
|
||||
pub mod known_hosts;
|
||||
pub mod models;
|
||||
pub mod recording;
|
||||
pub mod secrets;
|
||||
@@ -13,6 +14,7 @@ pub mod service;
|
||||
pub mod sessions;
|
||||
pub mod sshconfig;
|
||||
pub mod storage;
|
||||
pub mod sync;
|
||||
pub mod terminalenv;
|
||||
pub mod updater;
|
||||
pub mod validation;
|
||||
|
||||
@@ -409,9 +409,21 @@ pub struct RdpConfig {
|
||||
/// Allow plain TLS logon for servers without Network Level Authentication (e.g. xrdp).
|
||||
#[serde(rename = "allowTLSOnly")]
|
||||
pub allow_tls_only: bool,
|
||||
/// Play remote audio locally.
|
||||
pub audio: bool,
|
||||
/// Log on with Kerberos through this KDC (`host` or `host:port`, TCP); empty uses NTLM.
|
||||
pub kerberos_kdc: String,
|
||||
/// Local folder shared with the remote desktop as a drive (empty: none). Linux and macOS.
|
||||
pub shared_folder: String,
|
||||
/// Offer a printer; print jobs are saved as PostScript files in Downloads.
|
||||
pub redirect_printer: bool,
|
||||
/// Trust policy for the server's TLS certificate (pinned like an SSH host key).
|
||||
#[serde(deserialize_with = "lenient")]
|
||||
pub host_key_policy: HostKeyPolicy,
|
||||
/// RD Gateway (`host` or `host:port`, HTTPS); empty connects without one. Basic auth only.
|
||||
pub gateway_host: String,
|
||||
pub gateway_username: String,
|
||||
pub gateway_secret_mode: SecretMode,
|
||||
/// "none", "socks5" or "http"; the password is a stored secret.
|
||||
pub proxy_type: String,
|
||||
pub proxy_host: String,
|
||||
@@ -433,6 +445,7 @@ impl RdpConfig {
|
||||
RdpConfig {
|
||||
scale_to_fit: true,
|
||||
dynamic_resolution: true,
|
||||
audio: true,
|
||||
proxy_type: "none".into(),
|
||||
ssh_port: DEFAULT_SSH_PORT.into(),
|
||||
ssh_auth_method: "publickey".into(),
|
||||
@@ -453,6 +466,11 @@ pub struct IrcConfig {
|
||||
pub nick_serv_identify: bool,
|
||||
pub nick_serv_account: String,
|
||||
pub nick_serv_mode: SecretMode,
|
||||
/// Log in with SASL PLAIN during registration (needs the network to offer it).
|
||||
pub sasl: bool,
|
||||
/// SASL account (defaults to the nick).
|
||||
pub sasl_account: String,
|
||||
pub sasl_mode: SecretMode,
|
||||
#[serde(deserialize_with = "nd")]
|
||||
pub auto_join_rooms: Vec<String>,
|
||||
pub ssh_tunnel: bool,
|
||||
@@ -608,6 +626,10 @@ pub struct AppPreferences {
|
||||
pub allow_remote_clipboard: bool,
|
||||
/// Ask before pasting multi-line text into a terminal that isn't in bracketed-paste mode.
|
||||
pub confirm_multiline_paste: bool,
|
||||
/// Reopen the previous session's tabs and splits at launch.
|
||||
pub restore_sessions: bool,
|
||||
/// Folder holding the encrypted profile sync file (empty: sync off).
|
||||
pub sync_folder: String,
|
||||
}
|
||||
|
||||
impl Default for AppPreferences {
|
||||
@@ -629,6 +651,8 @@ impl Default for AppPreferences {
|
||||
check_for_updates: true,
|
||||
allow_remote_clipboard: true,
|
||||
confirm_multiline_paste: true,
|
||||
restore_sessions: true,
|
||||
sync_folder: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,12 +34,14 @@ pub enum SecretKind {
|
||||
RdpPassword,
|
||||
RdpSshPassword,
|
||||
RdpSshPassphrase,
|
||||
RdpGatewayPassword,
|
||||
IrcSaslPassword,
|
||||
}
|
||||
|
||||
impl SecretKind {
|
||||
/// Every kind, so deleting a profile can purge them all from the keychain. A new variant
|
||||
/// must be added here as well as to `as_str`.
|
||||
pub const ALL: [SecretKind; 15] = [
|
||||
pub const ALL: [SecretKind; 17] = [
|
||||
Self::Password,
|
||||
Self::Passphrase,
|
||||
Self::Totp,
|
||||
@@ -55,6 +57,8 @@ impl SecretKind {
|
||||
Self::RdpPassword,
|
||||
Self::RdpSshPassword,
|
||||
Self::RdpSshPassphrase,
|
||||
Self::RdpGatewayPassword,
|
||||
Self::IrcSaslPassword,
|
||||
];
|
||||
|
||||
/// The storage name, shared with the Go app.
|
||||
@@ -75,6 +79,8 @@ impl SecretKind {
|
||||
Self::RdpPassword => "rdp-password",
|
||||
Self::RdpSshPassword => "rdp-ssh-password",
|
||||
Self::RdpSshPassphrase => "rdp-ssh-passphrase",
|
||||
Self::RdpGatewayPassword => "rdp-gateway-password",
|
||||
Self::IrcSaslPassword => "irc-sasl-password",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +203,34 @@ impl Vault {
|
||||
*self.state.lock() = None;
|
||||
}
|
||||
|
||||
/// Re-encrypts every entry under `new` (fresh salt, key and verifier) after checking `old`.
|
||||
/// One atomic write: a crash leaves either the old vault or the new one.
|
||||
pub fn change_password(&self, old: &str, new: &str) -> Result<()> {
|
||||
if new.is_empty() {
|
||||
return Err("secrets: the new master password can't be empty".into());
|
||||
}
|
||||
self.unlock(old)?;
|
||||
let mut st = self.state.lock();
|
||||
let u = st.as_mut().ok_or("secrets: vault is locked")?;
|
||||
let mut plain = Vec::with_capacity(u.vault.secrets.len());
|
||||
for (k, v) in &u.vault.secrets {
|
||||
let data = B64.decode(v).map_err(|e| format!("secrets: corrupt entry {k:?}: {e}"))?;
|
||||
plain.push((k.clone(), Zeroizing::new(open(&u.key, &data)?)));
|
||||
}
|
||||
let salt = random_bytes::<32>();
|
||||
let key = derive_key(new, &salt)?;
|
||||
let secrets = plain.iter().map(|(k, v)| (k.clone(), B64.encode(seal(&key, v)))).collect();
|
||||
let next = Unlocked { vault: VaultFile { version: 1, salt: B64.encode(salt), secrets, verifier: verifier(&key) }, key };
|
||||
self.save(&next)?;
|
||||
*u = next;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stored keys (not values); empty while locked.
|
||||
pub fn keys(&self) -> Vec<String> {
|
||||
self.state.lock().as_ref().map(|u| u.vault.secrets.keys().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn save(&self, u: &Unlocked) -> Result<()> {
|
||||
let data = serde_json::to_vec_pretty(&u.vault)?;
|
||||
write_private(&self.path(), &data)
|
||||
@@ -346,6 +380,25 @@ impl Secrets {
|
||||
}
|
||||
|
||||
/// Removes every credential saved for a profile from both stores.
|
||||
/// Which credentials a profile has stored, and where. Probes the keychain once per kind
|
||||
/// (it can't be listed), so call it off the UI thread.
|
||||
pub fn stored_for(&self, profile_id: &str) -> Vec<(SecretKind, &'static str)> {
|
||||
let vault: std::collections::HashSet<String> = self.vault.keys().into_iter().collect();
|
||||
SecretKind::ALL
|
||||
.iter()
|
||||
.filter_map(|&k| {
|
||||
let key = k.key(profile_id);
|
||||
if self.keychain_ok && self.keychain.get(&key).is_some() {
|
||||
Some((k, "keychain"))
|
||||
} else if vault.contains(&key) {
|
||||
Some((k, "vault"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn delete_profile(&self, profile_id: &str) {
|
||||
if self.keychain_ok {
|
||||
for kind in SecretKind::ALL {
|
||||
@@ -393,6 +446,24 @@ mod tests {
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_master_password_keeps_every_secret() {
|
||||
let dir = std::env::temp_dir().join(format!("nexus-vault-rekey-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let v = Vault::new(dir.clone());
|
||||
v.initialise("old").unwrap();
|
||||
v.set("a", "1").unwrap();
|
||||
v.set("profile:p:password", "hunter2").unwrap();
|
||||
assert!(v.change_password("wrong", "new").is_err());
|
||||
v.change_password("old", "new").unwrap();
|
||||
v.lock();
|
||||
assert!(v.unlock("old").is_err(), "the old password no longer opens it");
|
||||
v.unlock("new").unwrap();
|
||||
assert_eq!((v.get("a").unwrap(), v.get("profile:p:password").unwrap()), ("1".to_string(), "hunter2".to_string()));
|
||||
assert_eq!(v.keys(), ["a", "profile:p:password"]);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_writes_are_atomic_and_owner_only() {
|
||||
let dir = std::env::temp_dir().join(format!("nexus-wp-{}", std::process::id()));
|
||||
|
||||
@@ -21,6 +21,23 @@ pub const VERSION: &str = match option_env!("NEXUS_VERSION") {
|
||||
};
|
||||
const MAX_IMPORT_JSON_BYTES: usize = 5 * 1024 * 1024;
|
||||
|
||||
/// Secret-store key of the profile-sync password.
|
||||
const SYNC_PASSWORD: &str = "sync:password";
|
||||
/// Setting holding deleted profile ids and when, for sync.
|
||||
const SYNC_DELETED: &str = "sync_deleted";
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq)]
|
||||
pub struct SyncReport {
|
||||
/// Profiles created or updated from the shared file.
|
||||
pub pulled: usize,
|
||||
/// Profiles deleted because another machine deleted them.
|
||||
pub removed: usize,
|
||||
/// Incoming profiles that failed validation.
|
||||
pub skipped: usize,
|
||||
/// Whether the shared file was rewritten.
|
||||
pub pushed: bool,
|
||||
}
|
||||
|
||||
pub struct Service {
|
||||
pub config: AppConfig,
|
||||
pub store: Arc<Store>,
|
||||
@@ -72,6 +89,10 @@ impl Service {
|
||||
let p = self.store.get_profile(id).map_err(|e| format!("profile not found: {e}"))?;
|
||||
self.store.delete_profile(id).map_err(|e| format!("failed to delete profile: {e}"))?;
|
||||
self.secrets.delete_profile(id);
|
||||
// So other machines syncing the same folder delete it too.
|
||||
let mut gone = self.sync_tombstones();
|
||||
gone.insert(id.to_string(), now());
|
||||
let _ = self.store.set_setting(SYNC_DELETED, &serde_json::to_string(&gone).unwrap_or_default());
|
||||
self.store.add_audit("profile.delete", id, "", &format!("Deleted profile {:?}", p.display_name));
|
||||
Ok(())
|
||||
}
|
||||
@@ -88,6 +109,82 @@ impl Service {
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
fn sync_tombstones(&self) -> std::collections::BTreeMap<String, Time> {
|
||||
self.store.setting(SYNC_DELETED).and_then(|j| serde_json::from_str(&j).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Sets (or, when empty, forgets) the profile-sync password.
|
||||
pub fn set_sync_password(&self, password: &str) -> Result<()> {
|
||||
if password.is_empty() {
|
||||
self.secrets.delete(SYNC_PASSWORD);
|
||||
return Ok(());
|
||||
}
|
||||
self.secrets.set_checked(SYNC_PASSWORD, password)
|
||||
}
|
||||
|
||||
/// Every profile's stored credentials: (profile id, profile name, kind, "keychain"/"vault").
|
||||
/// Slow-ish (keychain probes); run off the UI thread.
|
||||
pub fn credential_inventory(&self) -> Vec<(String, String, crate::secrets::SecretKind, &'static str)> {
|
||||
let mut out = vec![];
|
||||
for p in self.profiles() {
|
||||
for (kind, at) in self.secrets.stored_for(&p.id) {
|
||||
out.push((p.id.clone(), p.display_name.clone(), kind, at));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn forget_credential(&self, profile_id: &str, kind: crate::secrets::SecretKind) {
|
||||
self.secrets.delete(&kind.key(profile_id));
|
||||
self.store.add_audit("secret.delete", profile_id, "", &format!("Forgot {} credential", kind.as_str()));
|
||||
}
|
||||
|
||||
pub fn has_sync_password(&self) -> bool {
|
||||
self.secrets.get(SYNC_PASSWORD).is_some()
|
||||
}
|
||||
|
||||
/// Merges profiles with the shared sync file; see [`crate::sync`].
|
||||
pub fn sync_profiles(&self) -> Result<SyncReport> {
|
||||
let folder = self.store.preferences().sync_folder;
|
||||
if folder.trim().is_empty() {
|
||||
return Err("profile sync isn't set up (choose a folder in Settings)".into());
|
||||
}
|
||||
let folder = PathBuf::from(folder.trim());
|
||||
if !folder.is_dir() {
|
||||
return Err(format!("sync folder {} isn't available", folder.display()).into());
|
||||
}
|
||||
let password = self.secrets.get(SYNC_PASSWORD).ok_or("no sync password is stored (set one in Settings)")?;
|
||||
let remote = crate::sync::read(&folder, &password)?.unwrap_or_default();
|
||||
let m = crate::sync::merge(&self.profiles(), &self.sync_tombstones(), &remote, now());
|
||||
let mut report = SyncReport::default();
|
||||
for mut p in m.upsert {
|
||||
// The file is ours, but it crossed a shared folder: validate what comes in.
|
||||
p.normalize();
|
||||
if validation::validate_profile(&p).is_err() {
|
||||
report.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let r = if self.store.get_profile(&p.id).is_ok() { self.store.update_profile(&p) } else { self.store.create_profile(&p) };
|
||||
match r {
|
||||
Ok(()) => report.pulled += 1,
|
||||
Err(_) => report.skipped += 1,
|
||||
}
|
||||
}
|
||||
for id in &m.delete {
|
||||
if self.store.delete_profile(id).is_ok() {
|
||||
self.secrets.delete_profile(id);
|
||||
report.removed += 1;
|
||||
}
|
||||
}
|
||||
if m.file != remote {
|
||||
crate::sync::write(&folder, &password, &m.file)?;
|
||||
report.pushed = true;
|
||||
}
|
||||
self.store.set_setting(SYNC_DELETED, &serde_json::to_string(&m.file.deleted)?)?;
|
||||
self.store.add_audit("sync", "", "", &format!("Profile sync: {} in, {} removed, wrote file: {}", report.pulled, report.removed, report.pushed));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub fn profiles(&self) -> Vec<Profile> {
|
||||
self.store.list_profiles().unwrap_or_default()
|
||||
}
|
||||
@@ -127,6 +224,11 @@ impl Service {
|
||||
self.sessions.connect_local(&shell)
|
||||
}
|
||||
|
||||
/// A local shell with an explicit shell and start directory (restored tabs).
|
||||
pub fn connect_local_in(&self, shell: &str, cwd: Option<PathBuf>) -> String {
|
||||
self.sessions.connect_local_in(shell, cwd)
|
||||
}
|
||||
|
||||
pub fn reconnect(&self, id: &str) -> Result<String> {
|
||||
self.sessions.reconnect(id)
|
||||
}
|
||||
@@ -160,6 +262,65 @@ impl Service {
|
||||
self.store.delete_known_host(id)
|
||||
}
|
||||
|
||||
/// Imports an OpenSSH known_hosts file (default ~/.ssh/known_hosts); returns (host keys,
|
||||
/// certificate authorities, lines skipped). Existing entries for the same host and port are
|
||||
/// replaced.
|
||||
pub fn import_known_hosts(&self, path: Option<&Path>) -> Result<(usize, usize, usize)> {
|
||||
let path = match path {
|
||||
Some(p) => p.to_path_buf(),
|
||||
None => Self::ssh_dir()?.join("known_hosts"),
|
||||
};
|
||||
if std::fs::metadata(&path)?.len() > 5 << 20 {
|
||||
return Err("known_hosts file is too large".into());
|
||||
}
|
||||
let parsed = crate::known_hosts::parse(&std::fs::read_to_string(&path)?);
|
||||
for (host, port, key) in &parsed.hosts {
|
||||
let i = crate::clients::ssh::host_key_info(host, *port, key);
|
||||
let n = now();
|
||||
self.store.save_known_host(&KnownHost {
|
||||
id: String::new(),
|
||||
host: i.host,
|
||||
port: i.port as i64,
|
||||
key_type: i.key_type,
|
||||
fingerprint: i.fingerprint,
|
||||
public_key: i.public_key_b64,
|
||||
first_seen: n,
|
||||
last_seen: n,
|
||||
trusted: true,
|
||||
})?;
|
||||
}
|
||||
for (pattern, key) in &parsed.authorities {
|
||||
self.store.save_known_host(&crate::known_hosts::authority_row(pattern, key))?;
|
||||
}
|
||||
self.store.add_audit(
|
||||
"knownhosts.import",
|
||||
"",
|
||||
"",
|
||||
&format!("Imported {} host key(s) and {} CA(s) from {}", parsed.hosts.len(), parsed.authorities.len(), path.display()),
|
||||
);
|
||||
Ok((parsed.hosts.len(), parsed.authorities.len(), parsed.skipped))
|
||||
}
|
||||
|
||||
/// Writes the SSH known hosts and CAs in OpenSSH known_hosts format.
|
||||
pub fn export_known_hosts(&self, path: &Path) -> Result<usize> {
|
||||
let rows = self.store.list_known_hosts()?;
|
||||
let text = crate::known_hosts::export(&rows);
|
||||
std::fs::write(path, &text)?;
|
||||
Ok(text.lines().count())
|
||||
}
|
||||
|
||||
/// Trusts an SSH certificate authority for hosts matching `pattern` (OpenSSH syntax).
|
||||
pub fn add_cert_authority(&self, pattern: &str, public_key: &str) -> Result<()> {
|
||||
let pattern = pattern.trim();
|
||||
if pattern.is_empty() || pattern.contains(char::is_whitespace) {
|
||||
return Err("the host pattern must be one word, e.g. *.example.com".into());
|
||||
}
|
||||
let key = russh::keys::PublicKey::from_openssh(public_key.trim()).map_err(|e| format!("not an OpenSSH public key: {e}"))?;
|
||||
self.store.save_known_host(&crate::known_hosts::authority_row(pattern, &key))?;
|
||||
self.store.add_audit("knownhosts.ca", "", "", &format!("Trusted SSH CA {} for {pattern}", key.fingerprint(russh::keys::HashAlg::Sha256)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn preferences(&self) -> AppPreferences {
|
||||
self.store.preferences()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Credential resolution (saved, session-only, ask-every-time), prompts and host-key checks.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) type SessionSecrets = Arc<Mutex<SecretState>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct SecretState {
|
||||
/// `SecretMode::SessionOnly` values, asked once per session. Wiped from memory on drop.
|
||||
pub(super) session_only: HashMap<String, Zeroizing<String>>,
|
||||
/// `SecretMode::Saved` values typed during this attempt; stored only once it connects, so a
|
||||
/// typo never ends up saved.
|
||||
pub(super) pending: HashMap<String, Zeroizing<String>>,
|
||||
/// Saved values this attempt used.
|
||||
pub(super) used: HashSet<String>,
|
||||
/// Saved values the server rejected: the next attempt asks again instead of reusing them.
|
||||
pub(super) rejected: HashSet<String>,
|
||||
}
|
||||
|
||||
/// After a failed attempt, typed credentials are dropped and, when the server refused them, the
|
||||
/// saved ones used are skipped next time so the user can enter a replacement.
|
||||
pub(super) fn attempt_failed(state: &SessionSecrets, error: &str) {
|
||||
let mut st = state.lock();
|
||||
st.pending.clear();
|
||||
if is_auth_error(error) {
|
||||
let used = std::mem::take(&mut st.used);
|
||||
st.rejected.extend(used);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a connect error means the server refused the credentials (as opposed to a network or
|
||||
/// host-key failure).
|
||||
pub fn is_auth_error(msg: &str) -> bool {
|
||||
let m = msg.to_lowercase();
|
||||
// The last two are CredSSP's (RDP with NLA) wording for a rejected password.
|
||||
["unable to authenticate", "authentication failed", "permission denied", "no supported methods", "logondenied", "logon failure"]
|
||||
.iter()
|
||||
.any(|p| m.contains(p))
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
// --- credentials --------------------------------------------------------------------
|
||||
|
||||
/// Resolves a credential per its SecretMode (Go's buildSecretCallback): saved values come from
|
||||
/// the keychain then the vault (unless the server just rejected them), and newly typed ones
|
||||
/// are saved once the connection succeeds; session-only values are asked once per session and
|
||||
/// reused on reconnects (so e.g. a NickServ password entered once keeps identifying after a
|
||||
/// drop).
|
||||
pub fn secret_fn(&self, session: &str, profile_id: &str, kind: SecretKind, mode: SecretMode, prompt: Prompt) -> SecretFn {
|
||||
let key = kind.key(profile_id);
|
||||
let (secrets, store) = (self.secrets.clone(), self.store.clone());
|
||||
let (pid, kind) = (profile_id.to_string(), kind.as_str());
|
||||
let state: SessionSecrets = self.sessions.lock().get(session).map(|s| s.session_secrets.clone()).unwrap_or_default();
|
||||
Arc::new(move || {
|
||||
if mode == SecretMode::Saved {
|
||||
let mut st = state.lock();
|
||||
if let Some(v) = st.pending.get(&key) {
|
||||
return Ok(v.clone());
|
||||
}
|
||||
if !st.rejected.remove(&key)
|
||||
&& let Some(v) = secrets.get(&key)
|
||||
{
|
||||
st.used.insert(key.clone());
|
||||
store.add_audit("secret.access", &pid, "", &format!("Accessed {kind} credential"));
|
||||
return Ok(Zeroizing::new(v));
|
||||
}
|
||||
}
|
||||
if mode == SecretMode::SessionOnly
|
||||
&& let Some(v) = state.lock().session_only.get(&key).cloned()
|
||||
{
|
||||
return Ok(v);
|
||||
}
|
||||
let v = Zeroizing::new(prompt(&format!("Enter {kind}:"))?);
|
||||
let mut st = state.lock();
|
||||
match mode {
|
||||
SecretMode::Saved => {
|
||||
st.pending.insert(key.clone(), v.clone());
|
||||
}
|
||||
SecretMode::SessionOnly => {
|
||||
st.session_only.insert(key.clone(), v.clone());
|
||||
}
|
||||
SecretMode::AskEveryTime => {}
|
||||
}
|
||||
Ok(v)
|
||||
})
|
||||
}
|
||||
|
||||
/// Blocks until the user answers a credential prompt (5 minutes, or cancel).
|
||||
pub fn prompt(&self, session: &str, title: &str, message: &str, timeout: Duration) -> Result<String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.emit(Event::SecretPrompt { session: session.into(), title: title.into(), message: message.into(), reply: tx });
|
||||
match rx.recv_timeout(timeout) {
|
||||
Ok(v) => Ok(v),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => err("secret prompt timed out".into()),
|
||||
Err(_) => err("user cancelled secret prompt".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard interactive prompt for a session's credentials.
|
||||
pub fn prompt_for(self: &Arc<Self>, session: &str, title: &str, timeout: Duration) -> Prompt {
|
||||
let (me, sid, title) = (self.clone(), session.to_string(), title.to_string());
|
||||
Arc::new(move |msg| me.prompt(&sid, &title, msg, timeout))
|
||||
}
|
||||
|
||||
/// Host-key policy check against the known-hosts table (Go's HostKeyVerifier). Under the
|
||||
/// `ask` policy both unknown and changed keys go to the user, who can reject, accept once
|
||||
/// (connect without touching the record) or accept and save/update the record.
|
||||
pub fn host_key_check(self: &Arc<Self>, session: &str, policy: HostKeyPolicy) -> HostKeyCheck {
|
||||
let (me, sid) = (self.clone(), session.to_string());
|
||||
Arc::new(move |k: &HostKeyInfo| {
|
||||
let stored = me.store.get_known_host(&k.host, k.port as i64).map_err(|e| format!("failed to query known hosts: {e}"))?;
|
||||
let save = || {
|
||||
let n = now();
|
||||
me.store
|
||||
.save_known_host(&KnownHost {
|
||||
id: String::new(),
|
||||
host: k.host.clone(),
|
||||
port: k.port as i64,
|
||||
key_type: k.key_type.clone(),
|
||||
fingerprint: k.fingerprint.clone(),
|
||||
public_key: k.public_key_b64.clone(),
|
||||
first_seen: n,
|
||||
last_seen: n,
|
||||
trusted: true,
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
};
|
||||
let touch = |mut s: KnownHost| {
|
||||
s.last_seen = now();
|
||||
let _ = me.store.save_known_host(&s);
|
||||
Ok(())
|
||||
};
|
||||
let changed = |s: &KnownHost| {
|
||||
format!("host key for {} has changed! stored fingerprint: {}, received: {} — possible MITM attack", k.host, s.fingerprint, k.fingerprint)
|
||||
};
|
||||
let ask = |stored: Option<&KnownHost>| -> std::result::Result<HostKeyDecision, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
me.emit(Event::HostKeyVerify {
|
||||
session: sid.clone(),
|
||||
host: k.host.clone(),
|
||||
key_type: k.key_type.clone(),
|
||||
fingerprint: k.fingerprint.clone(),
|
||||
stored: stored.map(|s| s.fingerprint.clone()),
|
||||
reply: tx,
|
||||
});
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(d) => Ok(d),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => Ok(HostKeyDecision::Reject),
|
||||
Err(_) => Err("host key prompt failed: host key prompt timed out waiting for user response".into()),
|
||||
}
|
||||
};
|
||||
tracing::info!(host = %k.host, port = k.port, key_type = %k.key_type, fingerprint = %k.fingerprint, ?policy, known = stored.is_some(), "checking host key");
|
||||
match (policy, stored) {
|
||||
(HostKeyPolicy::Insecure, None) | (HostKeyPolicy::AcceptNew, None) => save(),
|
||||
(HostKeyPolicy::Insecure, Some(s)) => touch(s),
|
||||
(HostKeyPolicy::Strict, None) => Err(format!("host key for {}:{} is not known (policy: strict)", k.host, k.port)),
|
||||
(HostKeyPolicy::Ask, None) => match ask(None)? {
|
||||
HostKeyDecision::AcceptAndSave => save(),
|
||||
HostKeyDecision::AcceptOnce => Ok(()),
|
||||
HostKeyDecision::Reject => Err(format!("host key for {}:{} rejected by user", k.host, k.port)),
|
||||
},
|
||||
(_, Some(s)) if s.fingerprint == k.fingerprint => touch(s),
|
||||
(HostKeyPolicy::Ask, Some(s)) => match ask(Some(&s))? {
|
||||
HostKeyDecision::AcceptAndSave => {
|
||||
me.store.delete_known_host(&s.id).map_err(|e| e.to_string())?;
|
||||
save()?;
|
||||
me.store.add_audit(
|
||||
"hostkey.update",
|
||||
"",
|
||||
&sid,
|
||||
&format!("Replaced host key for {}:{} ({} -> {})", k.host, k.port, s.fingerprint, k.fingerprint),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
HostKeyDecision::AcceptOnce => {
|
||||
me.store.add_audit(
|
||||
"hostkey.accept-once",
|
||||
"",
|
||||
&sid,
|
||||
&format!("Accepted changed host key for {}:{} once ({})", k.host, k.port, k.fingerprint),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
HostKeyDecision::Reject => Err(format!("{} (rejected by user)", changed(&s))),
|
||||
},
|
||||
(_, Some(s)) => Err(changed(&s)),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Accessors and actions specific to one protocol (RAW, IRC, GitHub, desktops, SSH).
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Manager {
|
||||
// --- RAW ----------------------------------------------------------------------------
|
||||
|
||||
pub(super) fn raw(&self, id: &str) -> Result<Arc<raw::RawClient>> {
|
||||
match self.client(id)? {
|
||||
Client::Raw(c) => Ok(c),
|
||||
_ => err(format!("sessions: session {id:?} is not a RAW connection")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw_write_text(&self, id: &str, s: &str) -> Result<()> {
|
||||
self.raw(id)?.write_text(s)
|
||||
}
|
||||
|
||||
pub fn raw_write_hex(&self, id: &str, s: &str) -> Result<()> {
|
||||
self.raw(id)?.write_hex(s)
|
||||
}
|
||||
|
||||
pub fn raw_write_escaped(&self, id: &str, s: &str) -> Result<()> {
|
||||
self.raw(id)?.write_escaped(s)
|
||||
}
|
||||
|
||||
pub fn raw_history(&self, id: &str) -> Result<Vec<raw::HistoryEntry>> {
|
||||
Ok(self.raw(id)?.history())
|
||||
}
|
||||
|
||||
pub fn raw_clear_history(&self, id: &str) -> Result<()> {
|
||||
self.raw(id)?.clear_history();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn raw_save_capture(&self, id: &str, path: &std::path::Path) -> Result<()> {
|
||||
self.raw(id)?.save_capture(path)
|
||||
}
|
||||
|
||||
// --- IRC ----------------------------------------------------------------------------
|
||||
|
||||
pub fn irc(&self, id: &str) -> Result<Arc<irc::Client>> {
|
||||
match self.client(id)? {
|
||||
Client::Irc(c, _) => Ok(c),
|
||||
_ => err(format!("sessions: session {id:?} is not an IRC connection")),
|
||||
}
|
||||
}
|
||||
|
||||
// --- GitHub -------------------------------------------------------------------------
|
||||
|
||||
pub fn github(&self, id: &str) -> Result<Arc<github::Client>> {
|
||||
match self.client(id)? {
|
||||
Client::Github(c, _) => Ok(c),
|
||||
_ => err(format!("sessions: session {id:?} is not a GitHub connection")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rdp(&self, id: &str) -> Result<Arc<clients::rdp::Client>> {
|
||||
match self.client(id)? {
|
||||
Client::Rdp(c, _) => Ok(c),
|
||||
_ => err(format!("sessions: session {id:?} is not an RDP connection")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vnc(&self, id: &str) -> Result<Arc<clients::vnc::Client>> {
|
||||
match self.client(id)? {
|
||||
Client::Vnc(c, _) => Ok(c),
|
||||
_ => err(format!("sessions: session {id:?} is not a VNC connection")),
|
||||
}
|
||||
}
|
||||
|
||||
// --- SSH extras ---------------------------------------------------------------------
|
||||
|
||||
pub fn ssh(&self, id: &str) -> Result<Arc<SshClient>> {
|
||||
match self.client(id)? {
|
||||
Client::Ssh(c) => Ok(c),
|
||||
_ => err(format!("sessions: session {id:?} is not an SSH connection")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ping(&self, id: &str) -> Result<i64> {
|
||||
self.ssh(id)?.ping()
|
||||
}
|
||||
|
||||
pub fn cwd(&self, id: &str) -> Result<String> {
|
||||
self.ssh(id)?.run_command("pwd")
|
||||
}
|
||||
|
||||
pub fn start_forward(&self, id: &str, rule: PortForward) -> Result<()> {
|
||||
self.ssh(id)?.start_forward(rule.clone())?;
|
||||
self.emit(Event::ForwardStarted { session: id.into(), forward: rule });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop_forward(&self, id: &str, fid: &str) -> Result<()> {
|
||||
self.ssh(id)?.stop_forward(fid)?;
|
||||
self.emit(Event::ForwardStopped { session: id.into(), forward_id: fid.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn forwards(&self, id: &str) -> Result<Vec<PortForward>> {
|
||||
Ok(self.ssh(id)?.active_forwards())
|
||||
}
|
||||
|
||||
pub fn sftp_download(&self, id: &str, remote: &str, local: &std::path::Path) -> Result<()> {
|
||||
let s = self.ssh(id)?.sftp()?;
|
||||
clients::sftp::download(&s, remote, local, &|p| self.emit(Event::SftpProgress { session: id.into(), progress: p }))
|
||||
}
|
||||
|
||||
pub fn sftp_upload(&self, id: &str, local: &std::path::Path, remote: &str) -> Result<()> {
|
||||
let s = self.ssh(id)?.sftp()?;
|
||||
clients::sftp::upload(&s, local, remote, &|p| self.emit(Event::SftpProgress { session: id.into(), progress: p }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Local shells and login scripts.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Manager {
|
||||
// --- local shell --------------------------------------------------------------------
|
||||
|
||||
pub fn connect_local(self: &Arc<Self>, shell: &str) -> String {
|
||||
self.connect_local_in(shell, None)
|
||||
}
|
||||
|
||||
/// A local shell starting in `cwd` (when it still exists), e.g. a restored tab.
|
||||
pub fn connect_local_in(self: &Arc<Self>, shell: &str, cwd: Option<PathBuf>) -> String {
|
||||
let id = new_id();
|
||||
let info = SessionInfo {
|
||||
id: id.clone(),
|
||||
profile_id: String::new(),
|
||||
profile_name: "Local Machine".into(),
|
||||
protocol: Protocol::Local,
|
||||
host: "localhost".into(),
|
||||
port: 0,
|
||||
state: SessionState::Connecting,
|
||||
tab_name: "Local".into(),
|
||||
pinned: false,
|
||||
connected_at: now(),
|
||||
error: String::new(),
|
||||
};
|
||||
let epoch = self.new_session(info, None, shell.into(), SessionSecrets::default());
|
||||
if let Some(dir) = cwd.filter(|d| d.is_dir()) {
|
||||
let _ = self.with(&id, |s| s.local_cwd = Some(dir));
|
||||
}
|
||||
self.emit_state(&id, SessionState::Connecting, "");
|
||||
let me = self.clone();
|
||||
let id2 = id.clone();
|
||||
std::thread::spawn(move || me.start_local(&id2, epoch, 80, 24));
|
||||
id
|
||||
}
|
||||
|
||||
/// A local session's shell and its current directory.
|
||||
pub fn local_state(&self, id: &str) -> Option<(String, Option<PathBuf>)> {
|
||||
self.with(id, |s| {
|
||||
let cwd = match &s.client {
|
||||
Client::Local(c) => Some(c.working_directory()),
|
||||
_ => s.local_cwd.clone(),
|
||||
};
|
||||
(s.local_shell.clone(), cwd)
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Starts a fresh shell in an exited local tab, keeping its scrollback and last directory.
|
||||
pub fn restart_local(self: &Arc<Self>, id: &str, cols: u16, rows: u16) -> Result<()> {
|
||||
let epoch = self.with(id, |s| {
|
||||
if s.info.protocol != Protocol::Local {
|
||||
return Err(format!("sessions: session {id:?} is not local"));
|
||||
}
|
||||
if matches!(s.client, Client::Local(_)) || matches!(s.info.state, SessionState::Connecting | SessionState::Connected) {
|
||||
return Err(format!("sessions: local session {id:?} is still running"));
|
||||
}
|
||||
s.info.state = SessionState::Connecting;
|
||||
s.info.error.clear();
|
||||
Ok(s.epoch)
|
||||
})??;
|
||||
self.emit_state(id, SessionState::Connecting, "");
|
||||
let (me, id2) = (self.clone(), id.to_string());
|
||||
std::thread::spawn(move || me.start_local(&id2, epoch, cols, rows));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn start_local(self: &Arc<Self>, id: &str, epoch: u64, cols: u16, rows: u16) {
|
||||
let Ok((shell, cwd, pending)) = self.with(id, |s| (s.local_shell.clone(), s.local_cwd.clone(), s.pending_resize.take())) else { return };
|
||||
let (cols, rows) = pending.unwrap_or((cols, rows));
|
||||
let mut cb = self.terminal_callbacks(id, epoch);
|
||||
// A local shell exiting keeps its tab ("press enter to restart").
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
cb.on_close = Arc::new(move || {
|
||||
let (me, sid) = (me.clone(), sid.clone());
|
||||
std::thread::spawn(move || me.local_closed(&sid, epoch));
|
||||
});
|
||||
let c = LocalShell::new(&shell, cwd, cols, rows, cb);
|
||||
let r = c.start().map(|_| Client::Local(c.clone()));
|
||||
self.finish_connect(id, epoch, r, |me| me.store.add_audit("connect", "", id, "Connected via local to localhost"));
|
||||
}
|
||||
|
||||
pub(super) fn local_closed(self: &Arc<Self>, id: &str, epoch: u64) {
|
||||
let cwd = self.with(id, |s| {
|
||||
if s.epoch != epoch || s.closed {
|
||||
return None;
|
||||
}
|
||||
match std::mem::replace(&mut s.client, Client::None) {
|
||||
Client::Local(c) => Some(c.working_directory()),
|
||||
other => {
|
||||
s.client = other;
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Ok(Some(cwd)) = cwd {
|
||||
let _ = self.with(id, |s| s.local_cwd = Some(cwd));
|
||||
self.handle_closed(id, epoch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
// --- login scripts ------------------------------------------------------------------
|
||||
|
||||
pub(super) fn start_login_scripts(self: &Arc<Self>, id: &str, epoch: u64, steps: Vec<LoginScriptStep>) {
|
||||
if steps.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Ok(login) = self.with(id, |s| s.login.clone()) else { return };
|
||||
*login.lock() = LoginBuf { active: true, buf: vec![] };
|
||||
let (me, id) = (self.clone(), id.to_string());
|
||||
std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
for (i, step) in steps.iter().enumerate() {
|
||||
// Wait until the connect has been recorded as Connected.
|
||||
let mut waited = 0;
|
||||
while me.with(&id, |s| s.info.state).ok() == Some(SessionState::Connecting) && waited < 100 {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
waited += 1;
|
||||
}
|
||||
if !me.is_current(&id, epoch) || me.with(&id, |s| s.info.state).ok() != Some(SessionState::Connected) {
|
||||
break;
|
||||
}
|
||||
match step.kind.as_str() {
|
||||
"wait" => {
|
||||
let timeout = Duration::from_secs(if step.timeout <= 0 { 10 } else { step.timeout as u64 });
|
||||
if !wait_for_output(&login, &step.value, timeout) {
|
||||
me.emit(Event::Debug {
|
||||
session: id.clone(),
|
||||
message: format!("login script step {} timed out waiting for {:?}", i + 1, step.value),
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
"send" => {
|
||||
if let Err(e) = me.write(&id, format!("{}\n", step.value).as_bytes()) {
|
||||
me.emit(Event::Debug { session: id.clone(), message: format!("login script step {} failed to send: {e}", i + 1) });
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
*login.lock() = LoginBuf::default();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn wait_for_output(login: &Mutex<LoginBuf>, pattern: &str, timeout: Duration) -> bool {
|
||||
if pattern.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
while std::time::Instant::now() < deadline {
|
||||
{
|
||||
let mut l = login.lock();
|
||||
let text = String::from_utf8_lossy(&l.buf).into_owned();
|
||||
if let Some(i) = text.find(pattern) {
|
||||
let consumed = text[..i + pattern.len()].len();
|
||||
let n = consumed.min(l.buf.len());
|
||||
l.buf.drain(..n);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -0,0 +1,907 @@
|
||||
//! The session manager: one entry per open tab, each owning a protocol client. A port of
|
||||
//! internal/sessions — same lifecycle, reconnect backoff, login scripts, recording hooks and
|
||||
//! credential resolution — reporting to the UI through `Event`s.
|
||||
|
||||
use crate::Result;
|
||||
use crate::clients::local::LocalShell;
|
||||
use crate::clients::ssh::{HostKeyCheck, HostKeyInfo, SecretFn, SshClient};
|
||||
use crate::clients::{self, Callbacks, github, irc, raw, serial, telnet};
|
||||
use crate::models::*;
|
||||
use crate::recording::{self, Recorder};
|
||||
use crate::secrets::{SecretKind, Secrets};
|
||||
use crate::storage::Store;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
mod credentials;
|
||||
mod extras;
|
||||
mod local;
|
||||
mod protocols;
|
||||
|
||||
pub use credentials::is_auth_error;
|
||||
use credentials::{SessionSecrets, attempt_failed};
|
||||
|
||||
/// Everything the UI hears about. Prompts carry their reply channel; dropping it cancels.
|
||||
pub enum Event {
|
||||
Data {
|
||||
session: String,
|
||||
data: Vec<u8>,
|
||||
},
|
||||
State {
|
||||
session: String,
|
||||
state: SessionState,
|
||||
error: String,
|
||||
retry: Option<Retry>,
|
||||
},
|
||||
Closed {
|
||||
session: String,
|
||||
},
|
||||
RawData {
|
||||
session: String,
|
||||
data: Vec<u8>,
|
||||
direction: String,
|
||||
timestamp: i64,
|
||||
},
|
||||
Debug {
|
||||
session: String,
|
||||
message: String,
|
||||
},
|
||||
GithubStatus {
|
||||
session: String,
|
||||
status: String,
|
||||
},
|
||||
GithubRepos {
|
||||
session: String,
|
||||
login: String,
|
||||
repos: Vec<GitHubRepo>,
|
||||
},
|
||||
GithubError {
|
||||
session: String,
|
||||
error: String,
|
||||
},
|
||||
/// Something the user might like to know (e.g. where a print job was saved).
|
||||
Info {
|
||||
session: String,
|
||||
message: String,
|
||||
},
|
||||
/// Something the user should know about that didn't stop the session (e.g. a credential that
|
||||
/// couldn't be saved).
|
||||
Warning {
|
||||
session: String,
|
||||
message: String,
|
||||
},
|
||||
Irc {
|
||||
session: String,
|
||||
event: irc::Event,
|
||||
},
|
||||
ForwardStarted {
|
||||
session: String,
|
||||
forward: PortForward,
|
||||
},
|
||||
ForwardStopped {
|
||||
session: String,
|
||||
forward_id: String,
|
||||
},
|
||||
ForwardError {
|
||||
session: String,
|
||||
forward_id: String,
|
||||
label: String,
|
||||
error: String,
|
||||
},
|
||||
RecordingStarted {
|
||||
session: String,
|
||||
},
|
||||
RecordingStopped {
|
||||
session: String,
|
||||
duration: f64,
|
||||
events: usize,
|
||||
},
|
||||
SftpProgress {
|
||||
session: String,
|
||||
progress: clients::sftp::Progress,
|
||||
},
|
||||
SecretPrompt {
|
||||
session: String,
|
||||
title: String,
|
||||
message: String,
|
||||
reply: mpsc::Sender<String>,
|
||||
},
|
||||
/// A host key needs the user's decision: unknown (`stored` is None) or changed (`stored` is
|
||||
/// the fingerprint on record).
|
||||
HostKeyVerify {
|
||||
session: String,
|
||||
host: String,
|
||||
key_type: String,
|
||||
fingerprint: String,
|
||||
stored: Option<String>,
|
||||
reply: mpsc::Sender<HostKeyDecision>,
|
||||
},
|
||||
DesktopReady {
|
||||
session: String,
|
||||
},
|
||||
DesktopFrame {
|
||||
session: String,
|
||||
},
|
||||
/// The remote desktop's clipboard changed.
|
||||
DesktopClipboard {
|
||||
session: String,
|
||||
text: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// The user's answer to a host-key prompt.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HostKeyDecision {
|
||||
Reject,
|
||||
/// Connect, leaving the known-hosts record as it is.
|
||||
AcceptOnce,
|
||||
/// Connect and record this key (replacing a changed one).
|
||||
AcceptAndSave,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Retry {
|
||||
pub attempt: i64,
|
||||
pub max: i64,
|
||||
pub delay_secs: u64,
|
||||
}
|
||||
|
||||
pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;
|
||||
/// Asks the user for a credential (blocks the calling worker thread).
|
||||
pub type Prompt = Arc<dyn Fn(&str) -> Result<String> + Send + Sync>;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Client {
|
||||
None,
|
||||
Ssh(Arc<SshClient>),
|
||||
Telnet(Arc<telnet::TelnetClient>),
|
||||
Raw(Arc<raw::RawClient>),
|
||||
Serial(Arc<serial::SerialClient>),
|
||||
Local(Arc<LocalShell>),
|
||||
Github(Arc<github::Client>, Arc<AtomicBool>),
|
||||
Irc(Arc<irc::Client>, Option<Arc<SshClient>>),
|
||||
Vnc(Arc<clients::vnc::Client>, Option<Arc<SshClient>>),
|
||||
Rdp(Arc<clients::rdp::Client>, Option<Arc<SshClient>>),
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn close(&self) {
|
||||
match self {
|
||||
Client::None => {}
|
||||
Client::Ssh(c) => c.close(),
|
||||
Client::Telnet(c) => c.close(),
|
||||
Client::Raw(c) => c.close(),
|
||||
Client::Serial(c) => c.close(),
|
||||
Client::Local(c) => c.close(),
|
||||
Client::Github(_, stop) => stop.store(true, Ordering::SeqCst),
|
||||
Client::Irc(c, tunnel) => {
|
||||
c.close();
|
||||
if let Some(t) = tunnel {
|
||||
t.close();
|
||||
}
|
||||
}
|
||||
Client::Vnc(c, tunnel) => {
|
||||
c.close();
|
||||
if let Some(t) = tunnel {
|
||||
t.close();
|
||||
}
|
||||
}
|
||||
Client::Rdp(c, tunnel) => {
|
||||
c.close();
|
||||
if let Some(t) = tunnel {
|
||||
t.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct LoginBuf {
|
||||
active: bool,
|
||||
buf: Vec<u8>,
|
||||
}
|
||||
|
||||
struct Session {
|
||||
info: SessionInfo,
|
||||
/// Distinguishes this Session object from a later one with the same id (Go compared pointers).
|
||||
epoch: u64,
|
||||
closed: bool,
|
||||
client: Client,
|
||||
profile: Option<Profile>,
|
||||
local_shell: String,
|
||||
local_cwd: Option<PathBuf>,
|
||||
recorder: Option<Arc<Recorder>>,
|
||||
reconnect_count: i64,
|
||||
cancel_reconnect: Option<Arc<AtomicBool>>,
|
||||
pending_resize: Option<(u16, u16)>,
|
||||
login: Arc<Mutex<LoginBuf>>,
|
||||
/// Credential state kept across reconnects of this session.
|
||||
session_secrets: SessionSecrets,
|
||||
}
|
||||
|
||||
pub struct Manager {
|
||||
sessions: Mutex<HashMap<String, Session>>,
|
||||
store: Arc<Store>,
|
||||
secrets: Arc<Secrets>,
|
||||
recordings: recording::Store,
|
||||
sink: Mutex<Option<EventSink>>,
|
||||
next_epoch: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
|
||||
fn err<T>(msg: String) -> Result<T> {
|
||||
Err(msg.into())
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
pub fn new(store: Arc<Store>, secrets: Arc<Secrets>, recordings_dir: PathBuf) -> Arc<Manager> {
|
||||
Arc::new(Manager {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
store,
|
||||
secrets,
|
||||
recordings: recording::Store::new(recordings_dir),
|
||||
sink: Mutex::new(None),
|
||||
next_epoch: 1.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_sink(&self, sink: EventSink) {
|
||||
*self.sink.lock() = Some(sink);
|
||||
}
|
||||
|
||||
fn emit(&self, e: Event) {
|
||||
let sink = self.sink.lock().clone();
|
||||
if let Some(s) = sink {
|
||||
s(e);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_state(&self, id: &str, state: SessionState, error: &str) {
|
||||
self.emit(Event::State { session: id.into(), state, error: error.into(), retry: None });
|
||||
}
|
||||
|
||||
/// True while `id` still names the Session object with `epoch` and it isn't closed.
|
||||
fn is_current(&self, id: &str, epoch: u64) -> bool {
|
||||
self.sessions.lock().get(id).is_some_and(|s| s.epoch == epoch && !s.closed)
|
||||
}
|
||||
|
||||
fn with<R>(&self, id: &str, f: impl FnOnce(&mut Session) -> R) -> Result<R> {
|
||||
let mut map = self.sessions.lock();
|
||||
match map.get_mut(id) {
|
||||
Some(s) => Ok(f(s)),
|
||||
None => err(format!("sessions: session {id:?} not found")),
|
||||
}
|
||||
}
|
||||
|
||||
fn client(&self, id: &str) -> Result<Client> {
|
||||
self.with(id, |s| s.client.clone())
|
||||
}
|
||||
|
||||
fn new_session(&self, info: SessionInfo, profile: Option<Profile>, shell: String, session_secrets: SessionSecrets) -> u64 {
|
||||
let epoch = self.next_epoch.fetch_add(1, Ordering::SeqCst);
|
||||
let s = Session {
|
||||
info,
|
||||
epoch,
|
||||
closed: false,
|
||||
client: Client::None,
|
||||
profile,
|
||||
local_shell: shell,
|
||||
local_cwd: None,
|
||||
recorder: None,
|
||||
reconnect_count: 0,
|
||||
cancel_reconnect: None,
|
||||
pending_resize: None,
|
||||
login: Arc::default(),
|
||||
session_secrets,
|
||||
};
|
||||
let id = s.info.id.clone();
|
||||
self.sessions.lock().insert(id, s);
|
||||
epoch
|
||||
}
|
||||
|
||||
/// Opens a session for `profile` and connects it on a worker thread. Returns the session id
|
||||
/// immediately; progress arrives as `Event::State`.
|
||||
pub fn connect(self: &Arc<Self>, profile: Profile) -> String {
|
||||
self.connect_with(profile, SessionSecrets::default())
|
||||
}
|
||||
|
||||
/// `connect` with session-only credentials carried over from a previous session (reconnect).
|
||||
fn connect_with(self: &Arc<Self>, profile: Profile, session_secrets: SessionSecrets) -> String {
|
||||
let id = new_id();
|
||||
let prompt = self.prompt_for(&id, "Credentials Required", Duration::from_secs(300));
|
||||
let info = SessionInfo {
|
||||
id: id.clone(),
|
||||
profile_id: profile.id.clone(),
|
||||
profile_name: profile.display_name.clone(),
|
||||
protocol: profile.protocol,
|
||||
host: profile.host.clone(),
|
||||
port: profile.port,
|
||||
state: SessionState::Connecting,
|
||||
tab_name: profile.tab_name(),
|
||||
pinned: false,
|
||||
connected_at: now(),
|
||||
error: String::new(),
|
||||
};
|
||||
let epoch = self.new_session(info, Some(profile.clone()), String::new(), session_secrets);
|
||||
self.emit_state(&id, SessionState::Connecting, "");
|
||||
let me = self.clone();
|
||||
let id2 = id.clone();
|
||||
std::thread::spawn(move || {
|
||||
let r = me.connect_protocol(&id2, epoch, &profile, prompt);
|
||||
me.finish_connect(&id2, epoch, r, |me| {
|
||||
me.store.add_audit("connect", &profile.id, &id2, &format!("Connected via {} to {}", profile.protocol.id(), profile.host))
|
||||
});
|
||||
});
|
||||
id
|
||||
}
|
||||
|
||||
fn finish_connect(&self, id: &str, epoch: u64, r: Result<Client>, on_ok: impl FnOnce(&Self)) {
|
||||
let mut map = self.sessions.lock();
|
||||
let current = map.get_mut(id).filter(|s| s.epoch == epoch && !s.closed);
|
||||
match (r, current) {
|
||||
(Ok(client), None) => {
|
||||
drop(map);
|
||||
client.close();
|
||||
}
|
||||
(Err(_), None) => {}
|
||||
(Err(e), Some(s)) => {
|
||||
tracing::warn!(session = id, error = %e, "connection failed");
|
||||
s.info.state = SessionState::Error;
|
||||
s.info.error = e.to_string();
|
||||
attempt_failed(&s.session_secrets, &e.to_string());
|
||||
drop(map);
|
||||
self.emit_state(id, SessionState::Error, &e.to_string());
|
||||
}
|
||||
(Ok(client), Some(s)) => {
|
||||
tracing::info!(session = id, "connected");
|
||||
let typed = std::mem::take(&mut s.session_secrets.lock().pending);
|
||||
s.client = client.clone();
|
||||
s.info.state = SessionState::Connected;
|
||||
s.info.connected_at = now();
|
||||
s.reconnect_count = 0;
|
||||
let pending = s.pending_resize.take();
|
||||
drop(map);
|
||||
if let Some((c, r)) = pending {
|
||||
let _ = self.resize_client(&client, c, r);
|
||||
}
|
||||
for (key, value) in typed {
|
||||
if let Err(e) = self.secrets.set_checked(&key, &value) {
|
||||
tracing::warn!(session = id, credential = key.rsplit(':').next().unwrap_or(""), error = %e, "credential not saved");
|
||||
self.emit(Event::Warning { session: id.into(), message: format!("Credential not saved: {e}") });
|
||||
}
|
||||
}
|
||||
self.emit_state(id, SessionState::Connected, "");
|
||||
on_ok(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn connect_protocol(self: &Arc<Self>, id: &str, epoch: u64, p: &Profile, prompt: Prompt) -> Result<Client> {
|
||||
tracing::info!(session = id, protocol = p.protocol.id(), host = %p.host, port = p.port, "connecting");
|
||||
let _ = self.with(id, |s| {
|
||||
let mut st = s.session_secrets.lock();
|
||||
st.pending.clear();
|
||||
st.used.clear();
|
||||
});
|
||||
match p.protocol {
|
||||
Protocol::Ssh => self.connect_ssh(id, epoch, p, prompt),
|
||||
Protocol::Telnet => {
|
||||
let debug = p.telnet.as_ref().is_some_and(|t| t.negotiation_debug).then(|| {
|
||||
let (me, id) = (self.clone(), id.to_string());
|
||||
Arc::new(move |m: String| me.emit(Event::Debug { session: id.clone(), message: m })) as clients::DebugFn
|
||||
});
|
||||
let c = Arc::new(telnet::TelnetClient::new(p, self.terminal_callbacks(id, epoch), debug));
|
||||
c.connect()?;
|
||||
self.start_login_scripts(id, epoch, p.telnet.as_ref().map(|t| t.login_scripts.clone()).unwrap_or_default());
|
||||
Ok(Client::Telnet(c))
|
||||
}
|
||||
Protocol::Raw => {
|
||||
let cb = self.terminal_callbacks(id, epoch);
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let on_data: raw::RawDataFn =
|
||||
Arc::new(move |d, dir, ts| me.emit(Event::RawData { session: sid.clone(), data: d.to_vec(), direction: dir.into(), timestamp: ts }));
|
||||
let c = Arc::new(raw::RawClient::new(p, on_data, cb.on_error, cb.on_close));
|
||||
c.connect()?;
|
||||
Ok(Client::Raw(c))
|
||||
}
|
||||
Protocol::Serial => {
|
||||
let c = Arc::new(serial::SerialClient::new(p, self.terminal_callbacks(id, epoch)));
|
||||
c.connect()?;
|
||||
Ok(Client::Serial(c))
|
||||
}
|
||||
Protocol::Github => self.connect_github(id, epoch, p, prompt),
|
||||
Protocol::Irc => self.connect_irc(id, epoch, p, prompt),
|
||||
Protocol::Vnc => self.connect_vnc(id, epoch, p, prompt),
|
||||
Protocol::Rdp => self.connect_rdp(id, epoch, p, prompt),
|
||||
Protocol::Local => err("unsupported protocol \"local\"".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Callbacks for terminal-style clients: output to the UI, recording and login scripts.
|
||||
fn terminal_callbacks(self: &Arc<Self>, id: &str, epoch: u64) -> Callbacks {
|
||||
let login = self.sessions.lock().get(id).map(|s| s.login.clone()).unwrap_or_default();
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let on_data = Arc::new(move |d: &[u8]| {
|
||||
me.emit(Event::Data { session: sid.clone(), data: d.to_vec() });
|
||||
let rec = me.sessions.lock().get(&sid).and_then(|s| s.recorder.clone());
|
||||
if let Some(r) = rec {
|
||||
r.write_output(d);
|
||||
}
|
||||
let mut l = login.lock();
|
||||
if l.active {
|
||||
l.buf.extend_from_slice(d);
|
||||
if l.buf.len() > 16384 {
|
||||
let cut = l.buf.len() - 16384;
|
||||
l.buf.drain(..cut);
|
||||
}
|
||||
}
|
||||
});
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let on_error = Arc::new(move |e: String| {
|
||||
let ok = me
|
||||
.with(&sid, |s| {
|
||||
if s.epoch != epoch {
|
||||
return false;
|
||||
}
|
||||
s.info.state = SessionState::Error;
|
||||
s.info.error = e.clone();
|
||||
true
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if ok {
|
||||
me.emit_state(&sid, SessionState::Error, &e);
|
||||
}
|
||||
});
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let on_close = Arc::new(move || {
|
||||
let me = me.clone();
|
||||
let sid = sid.clone();
|
||||
// Close callbacks can fire inside a client's own lock; handle them off-thread.
|
||||
std::thread::spawn(move || me.handle_closed(&sid, epoch));
|
||||
});
|
||||
Callbacks { on_data, on_error, on_close }
|
||||
}
|
||||
|
||||
// --- lifecycle ----------------------------------------------------------------------
|
||||
|
||||
/// Explicit close: the tab is gone, so no reconnect.
|
||||
pub fn disconnect(&self, id: &str) -> Result<()> {
|
||||
let s = self.sessions.lock().remove(id).ok_or_else(|| format!("sessions: session {id:?} not found"))?;
|
||||
self.close_session(s);
|
||||
self.store.add_audit("disconnect", "", id, "Session disconnected");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Closes and re-opens a session from its profile, keeping the tab name and pin; returns the
|
||||
/// new session id.
|
||||
pub fn reconnect(self: &Arc<Self>, id: &str) -> Result<String> {
|
||||
let s = self.sessions.lock().remove(id).ok_or_else(|| format!("sessions: session {id:?} not found"))?;
|
||||
let (profile, tab, pinned, proto, shell) = (s.profile.clone(), s.info.tab_name.clone(), s.info.pinned, s.info.protocol, s.local_shell.clone());
|
||||
let session_secrets = s.session_secrets.clone();
|
||||
self.close_session(s);
|
||||
let new = match (proto, profile) {
|
||||
(Protocol::Local, _) => self.connect_local(&shell),
|
||||
(_, Some(p)) => self.connect_with(p, session_secrets),
|
||||
_ => return err("sessions: nothing to reconnect".into()),
|
||||
};
|
||||
let _ = self.with(&new, |s| {
|
||||
s.info.tab_name = tab;
|
||||
s.info.pinned = pinned;
|
||||
});
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
fn close_session(&self, mut s: Session) {
|
||||
s.closed = true;
|
||||
if let Some(c) = s.cancel_reconnect.take() {
|
||||
c.store(true, Ordering::SeqCst);
|
||||
}
|
||||
if let Some(r) = s.recorder.take() {
|
||||
let _ = r.close();
|
||||
}
|
||||
s.client.close();
|
||||
}
|
||||
|
||||
fn handle_closed(self: &Arc<Self>, id: &str, epoch: u64) {
|
||||
let profile = {
|
||||
let mut map = self.sessions.lock();
|
||||
let Some(s) = map.get_mut(id).filter(|s| s.epoch == epoch && !s.closed) else { return };
|
||||
s.info.state = SessionState::Disconnected;
|
||||
if !matches!(s.client, Client::Local(_)) {
|
||||
s.client = Client::None;
|
||||
}
|
||||
s.profile.clone()
|
||||
};
|
||||
self.store.add_audit("disconnect", "", id, "Session disconnected");
|
||||
tracing::info!(session = id, "remote closed the session");
|
||||
if let Some(p) = profile.filter(|p| p.auto_reconnect()) {
|
||||
self.schedule_reconnect(id, epoch, p);
|
||||
return;
|
||||
}
|
||||
self.emit(Event::Closed { session: id.into() });
|
||||
self.emit_state(id, SessionState::Disconnected, "");
|
||||
}
|
||||
|
||||
/// Exponential backoff 1, 2, 4 … 30 s, up to the profile's attempt limit.
|
||||
fn schedule_reconnect(self: &Arc<Self>, id: &str, epoch: u64, p: Profile) {
|
||||
let max = p.max_reconnect_tries();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let attempt = self.with(id, |s| {
|
||||
s.reconnect_count += 1;
|
||||
if s.reconnect_count > max {
|
||||
tracing::warn!(session = id, tries = max, "giving up reconnecting");
|
||||
s.info.state = SessionState::Disconnected;
|
||||
return None;
|
||||
}
|
||||
tracing::info!(session = id, attempt = s.reconnect_count, of = max, "scheduling reconnect");
|
||||
s.info.state = SessionState::Reconnecting;
|
||||
s.info.error.clear();
|
||||
if let Some(c) = s.cancel_reconnect.replace(cancel.clone()) {
|
||||
c.store(true, Ordering::SeqCst);
|
||||
}
|
||||
Some(s.reconnect_count)
|
||||
});
|
||||
let Ok(attempt) = attempt else { return };
|
||||
let Some(attempt) = attempt else {
|
||||
self.emit(Event::Closed { session: id.into() });
|
||||
self.emit_state(id, SessionState::Disconnected, "auto-reconnect failed after maximum attempts");
|
||||
return;
|
||||
};
|
||||
let delay = (1u64 << (attempt - 1).min(5)).min(30);
|
||||
self.emit(Event::State {
|
||||
session: id.into(),
|
||||
state: SessionState::Reconnecting,
|
||||
error: String::new(),
|
||||
retry: Some(Retry { attempt, max, delay_secs: delay }),
|
||||
});
|
||||
let (me, id) = (self.clone(), id.to_string());
|
||||
std::thread::spawn(move || {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(delay);
|
||||
while std::time::Instant::now() < deadline {
|
||||
if cancel.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
let ok = me
|
||||
.with(&id, |s| {
|
||||
if s.epoch != epoch || s.closed || cancel.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
}
|
||||
s.client = Client::None;
|
||||
s.info.state = SessionState::Connecting;
|
||||
true
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
return;
|
||||
}
|
||||
me.emit_state(&id, SessionState::Connecting, "");
|
||||
let prompt = me.prompt_for(&id, "Reconnection Credentials", Duration::from_secs(300));
|
||||
match me.connect_protocol(&id, epoch, &p, prompt) {
|
||||
Ok(c) => me.finish_connect(&id, epoch, Ok(c), |_| {}),
|
||||
Err(e) => {
|
||||
let current = me.with(&id, |s| {
|
||||
if s.epoch != epoch || s.closed {
|
||||
return false;
|
||||
}
|
||||
s.info.state = SessionState::Error;
|
||||
s.info.error = e.to_string();
|
||||
attempt_failed(&s.session_secrets, &e.to_string());
|
||||
true
|
||||
});
|
||||
if current.unwrap_or(false) {
|
||||
me.emit_state(&id, SessionState::Error, &e.to_string());
|
||||
me.schedule_reconnect(&id, epoch, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn cancel_reconnect(&self, id: &str) {
|
||||
let found = self
|
||||
.with(id, |s| {
|
||||
if let Some(c) = s.cancel_reconnect.take() {
|
||||
c.store(true, Ordering::SeqCst);
|
||||
s.reconnect_count = 0;
|
||||
s.info.state = SessionState::Disconnected;
|
||||
}
|
||||
})
|
||||
.is_ok();
|
||||
if found {
|
||||
self.emit_state(id, SessionState::Disconnected, "");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close_all(&self) {
|
||||
let all: Vec<Session> = self.sessions.lock().drain().map(|(_, s)| s).collect();
|
||||
for s in all {
|
||||
self.close_session(s);
|
||||
}
|
||||
}
|
||||
|
||||
// --- I/O ----------------------------------------------------------------------------
|
||||
|
||||
pub fn write(&self, id: &str, data: &[u8]) -> Result<()> {
|
||||
let (client, rec) = self.with(id, |s| (s.client.clone(), s.recorder.clone()))?;
|
||||
if let Some(r) = rec {
|
||||
r.write_input(data);
|
||||
}
|
||||
match client {
|
||||
Client::Ssh(c) => c.write(data),
|
||||
Client::Telnet(c) => c.write(data),
|
||||
Client::Raw(c) => c.write(data),
|
||||
Client::Serial(c) => c.write(data),
|
||||
Client::Local(c) => c.write(data),
|
||||
_ => err(format!("sessions: no active client for session {id:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn resize_client(&self, c: &Client, cols: u16, rows: u16) -> Result<()> {
|
||||
if cols == 0 || rows == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
match c {
|
||||
Client::Ssh(c) => c.resize(cols as u32, rows as u32),
|
||||
Client::Telnet(c) => c.resize(cols, rows),
|
||||
Client::Local(c) => c.resize(cols, rows),
|
||||
// For a remote desktop the "size" is the tab's size in pixels.
|
||||
Client::Rdp(c, _) => {
|
||||
c.resize(cols, rows);
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resizes the remote PTY; before a client exists the size is kept and applied on connect.
|
||||
pub fn resize(&self, id: &str, cols: u16, rows: u16) -> Result<()> {
|
||||
let c = self.with(id, |s| {
|
||||
if matches!(s.client, Client::None) {
|
||||
s.pending_resize = Some((cols, rows));
|
||||
}
|
||||
s.client.clone()
|
||||
})?;
|
||||
self.resize_client(&c, cols, rows)
|
||||
}
|
||||
|
||||
pub fn info(&self, id: &str) -> Option<SessionInfo> {
|
||||
self.sessions.lock().get(id).map(|s| s.info.clone())
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Vec<SessionInfo> {
|
||||
self.sessions.lock().values().map(|s| s.info.clone()).collect()
|
||||
}
|
||||
|
||||
pub fn profile(&self, id: &str) -> Option<Profile> {
|
||||
self.sessions.lock().get(id).and_then(|s| s.profile.clone())
|
||||
}
|
||||
|
||||
pub fn rename(&self, id: &str, name: &str) -> Result<()> {
|
||||
self.with(id, |s| s.info.tab_name = name.into())
|
||||
}
|
||||
|
||||
pub fn pin(&self, id: &str, pinned: bool) -> Result<()> {
|
||||
self.with(id, |s| s.info.pinned = pinned)
|
||||
}
|
||||
|
||||
pub fn send_break(&self, id: &str) -> Result<()> {
|
||||
match self.client(id)? {
|
||||
Client::Telnet(c) => c.send_break(),
|
||||
Client::Serial(c) => c.send_break(),
|
||||
_ => err(format!("sessions: session {id:?} does not support break")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_serial_lines(&self, id: &str, dtr: bool, rts: bool) -> Result<()> {
|
||||
match self.client(id)? {
|
||||
Client::Serial(c) => c.set_lines(dtr, rts),
|
||||
_ => err(format!("sessions: session {id:?} is not a serial connection")),
|
||||
}
|
||||
}
|
||||
|
||||
// --- recording ----------------------------------------------------------------------
|
||||
|
||||
pub fn start_recording(&self, id: &str, cols: u16, rows: u16) -> Result<()> {
|
||||
let (exists, title) = self.with(id, |s| (s.recorder.is_some(), format!("{} — {}", s.info.profile_name, s.info.host)))?;
|
||||
if exists {
|
||||
return err(format!("sessions: session {id:?} is already being recorded"));
|
||||
}
|
||||
let r = Arc::new(
|
||||
Recorder::new(self.recordings.dir(), id, &title, cols as i64, rows as i64).map_err(|e| format!("sessions: failed to start recording: {e}"))?,
|
||||
);
|
||||
self.with(id, |s| s.recorder = Some(r))?;
|
||||
self.emit(Event::RecordingStarted { session: id.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop_recording(&self, id: &str) -> Result<()> {
|
||||
let r = self.with(id, |s| s.recorder.take())?.ok_or_else(|| format!("sessions: session {id:?} is not being recorded"))?;
|
||||
r.close().map_err(|e| format!("sessions: failed to stop recording: {e}"))?;
|
||||
self.emit(Event::RecordingStopped { session: id.into(), duration: r.duration(), events: r.event_count() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_recording(&self, id: &str) -> bool {
|
||||
self.with(id, |s| s.recorder.is_some()).unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn recordings(&self) -> &recording::Store {
|
||||
&self.recordings
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::secrets::{Keychain, Secrets, Vault};
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
fn manager(name: &str) -> (Arc<Manager>, PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!("nexus-secretfn-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let store = Arc::new(Store::open(&dir.join("nexus.db")).unwrap());
|
||||
let secrets = Arc::new(Secrets { vault: Vault::new(dir.join("vault")), keychain: Keychain::new("NexusTerminalTest"), keychain_ok: false });
|
||||
(Manager::new(store, secrets, dir.join("recordings")), dir)
|
||||
}
|
||||
|
||||
fn counting_prompt(n: Arc<AtomicUsize>) -> Prompt {
|
||||
Arc::new(move |_| {
|
||||
n.fetch_add(1, Ordering::SeqCst);
|
||||
Ok("hunter2".into())
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_credentials_are_stored_only_after_success_and_reasked_after_rejection() {
|
||||
let (m, dir) = manager("saved");
|
||||
let warnings: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let w = warnings.clone();
|
||||
m.set_sink(Arc::new(move |e| {
|
||||
if let Event::Warning { message, .. } = e {
|
||||
w.lock().push(message);
|
||||
}
|
||||
}));
|
||||
let p = Profile { host: "127.0.0.1".into(), port: 1, ..Profile::new(Protocol::Raw) };
|
||||
let key = SecretKind::Password.key(&p.id);
|
||||
let info = |id: &str| SessionInfo {
|
||||
id: id.into(),
|
||||
profile_id: p.id.clone(),
|
||||
profile_name: String::new(),
|
||||
protocol: Protocol::Raw,
|
||||
host: p.host.clone(),
|
||||
port: p.port,
|
||||
state: SessionState::Connecting,
|
||||
tab_name: String::new(),
|
||||
pinned: false,
|
||||
connected_at: now(),
|
||||
error: String::new(),
|
||||
};
|
||||
let asked = Arc::new(AtomicUsize::new(0));
|
||||
let resolve = |m: &Arc<Manager>, id: &str| m.secret_fn(id, &p.id, SecretKind::Password, SecretMode::Saved, counting_prompt(asked.clone()))().unwrap();
|
||||
|
||||
// Locked store: the credential can't be saved, and the user is told.
|
||||
let e = m.new_session(info("s0"), Some(p.clone()), String::new(), SessionSecrets::default());
|
||||
resolve(&m, "s0");
|
||||
m.finish_connect("s0", e, Ok(Client::None), |_| {});
|
||||
assert_eq!(warnings.lock().len(), 1);
|
||||
|
||||
m.secrets.vault.initialise("pw").unwrap();
|
||||
let e = m.new_session(info("s1"), Some(p.clone()), String::new(), SessionSecrets::default());
|
||||
// A typed password the server rejects is never stored.
|
||||
resolve(&m, "s1");
|
||||
m.finish_connect("s1", e, Err("ssh: unable to authenticate".into()), |_| {});
|
||||
assert!(m.secrets.get(&key).is_none());
|
||||
// Typed again and accepted: stored.
|
||||
resolve(&m, "s1");
|
||||
m.finish_connect("s1", e, Ok(Client::None), |_| {});
|
||||
assert_eq!(m.secrets.get(&key).as_deref(), Some("hunter2"));
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 3);
|
||||
|
||||
// The saved value is reused; once the server rejects it, the next attempt asks again.
|
||||
let e = m.new_session(info("s2"), Some(p.clone()), String::new(), SessionSecrets::default());
|
||||
resolve(&m, "s2");
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 3);
|
||||
m.finish_connect("s2", e, Err("VNC authentication failed".into()), |_| {});
|
||||
resolve(&m, "s2");
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 4);
|
||||
// A network error doesn't count as a rejection.
|
||||
m.finish_connect("s2", e, Err("connection refused".into()), |_| {});
|
||||
resolve(&m, "s2");
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 4);
|
||||
m.close_all();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_only_secrets_survive_reconnects() {
|
||||
let (m, dir) = manager("cache");
|
||||
let p = Profile { host: "127.0.0.1".into(), port: 1, ..Profile::new(Protocol::Raw) };
|
||||
let info = SessionInfo {
|
||||
id: "s1".into(),
|
||||
profile_id: p.id.clone(),
|
||||
profile_name: String::new(),
|
||||
protocol: Protocol::Raw,
|
||||
host: p.host.clone(),
|
||||
port: p.port,
|
||||
state: SessionState::Connecting,
|
||||
tab_name: String::new(),
|
||||
pinned: false,
|
||||
connected_at: now(),
|
||||
error: String::new(),
|
||||
};
|
||||
m.new_session(info, Some(p.clone()), String::new(), SessionSecrets::default());
|
||||
let asked = Arc::new(AtomicUsize::new(0));
|
||||
// Two separate resolutions (as two connects of the same session make) prompt once.
|
||||
for _ in 0..2 {
|
||||
let f = m.secret_fn("s1", &p.id, SecretKind::IrcNickServPassword, SecretMode::SessionOnly, counting_prompt(asked.clone()));
|
||||
assert_eq!(f().unwrap().as_str(), "hunter2");
|
||||
}
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 1);
|
||||
// Ask-every-time still prompts each time.
|
||||
let f = m.secret_fn("s1", &p.id, SecretKind::IrcNickServPassword, SecretMode::AskEveryTime, counting_prompt(asked.clone()));
|
||||
f().unwrap();
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 2);
|
||||
// An explicit reconnect carries the cache to the new session id.
|
||||
let new = m.reconnect("s1").unwrap();
|
||||
let f = m.secret_fn(&new, &p.id, SecretKind::IrcNickServPassword, SecretMode::SessionOnly, counting_prompt(asked.clone()));
|
||||
assert_eq!(f().unwrap().as_str(), "hunter2");
|
||||
assert_eq!(asked.load(Ordering::SeqCst), 2);
|
||||
m.close_all();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_host_keys_can_be_rejected_accepted_once_or_updated() {
|
||||
use crate::clients::ssh::HostKeyInfo;
|
||||
let (m, dir) = manager("hostkey");
|
||||
let answers: Arc<Mutex<Vec<HostKeyDecision>>> = Arc::default();
|
||||
let prompts: Arc<Mutex<Vec<Option<String>>>> = Arc::default();
|
||||
let (a, pr) = (answers.clone(), prompts.clone());
|
||||
m.set_sink(Arc::new(move |e| {
|
||||
if let Event::HostKeyVerify { stored, reply, .. } = e {
|
||||
pr.lock().push(stored);
|
||||
let _ = reply.send(a.lock().remove(0));
|
||||
}
|
||||
}));
|
||||
let info = |fp: &str| HostKeyInfo { host: "h".into(), port: 22, key_type: "ssh-ed25519".into(), fingerprint: fp.into(), public_key_b64: "AAAA".into() };
|
||||
let stored = |m: &Manager| m.store.get_known_host("h", 22).unwrap().map(|k| k.fingerprint);
|
||||
// Unknown key: accept once records nothing; accept & save records it.
|
||||
let check = m.host_key_check("s", HostKeyPolicy::Ask);
|
||||
answers.lock().push(HostKeyDecision::AcceptOnce);
|
||||
check(&info("A")).unwrap();
|
||||
assert_eq!(stored(&m), None);
|
||||
answers.lock().push(HostKeyDecision::AcceptAndSave);
|
||||
check(&info("A")).unwrap();
|
||||
assert_eq!(stored(&m).as_deref(), Some("A"));
|
||||
assert_eq!(prompts.lock().as_slice(), [None, None]);
|
||||
// Same key again: no prompt.
|
||||
check(&info("A")).unwrap();
|
||||
assert_eq!(prompts.lock().len(), 2);
|
||||
// Changed key: reject, accept once (record untouched), accept & update (record replaced).
|
||||
answers.lock().push(HostKeyDecision::Reject);
|
||||
assert!(check(&info("B")).unwrap_err().contains("has changed"));
|
||||
answers.lock().push(HostKeyDecision::AcceptOnce);
|
||||
check(&info("B")).unwrap();
|
||||
assert_eq!(stored(&m).as_deref(), Some("A"));
|
||||
answers.lock().push(HostKeyDecision::AcceptAndSave);
|
||||
check(&info("B")).unwrap();
|
||||
assert_eq!(stored(&m).as_deref(), Some("B"));
|
||||
assert_eq!(prompts.lock()[2..], [Some("A".to_string()), Some("A".into()), Some("A".into())]);
|
||||
assert_eq!(m.store.list_known_hosts().unwrap().len(), 1);
|
||||
// Strict and accept-new never prompt on a changed key.
|
||||
for policy in [HostKeyPolicy::Strict, HostKeyPolicy::AcceptNew] {
|
||||
assert!(m.host_key_check("s", policy)(&info("C")).unwrap_err().contains("has changed"));
|
||||
}
|
||||
assert_eq!(prompts.lock().len(), 5);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! Per-protocol connect: SSH, GitHub, IRC, VNC and RDP, and the SSH tunnels they can use.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl Manager {
|
||||
/// Known-hosts rows that are SSH certificate authorities.
|
||||
pub(super) fn cert_authorities(&self) -> Vec<KnownHost> {
|
||||
self.store.list_known_hosts().unwrap_or_default().into_iter().filter(|k| k.key_type == crate::known_hosts::CA_KEY_TYPE).collect()
|
||||
}
|
||||
|
||||
// --- per-protocol connect -----------------------------------------------------------
|
||||
|
||||
pub(super) fn connect_ssh(self: &Arc<Self>, id: &str, epoch: u64, p: &Profile, prompt: Prompt) -> Result<Client> {
|
||||
let mut p = p.clone();
|
||||
let sc = p.ssh.get_or_insert_with(SshConfig::defaults).clone();
|
||||
let password = self.secret_fn(id, &p.id, SecretKind::Password, sc.secret_mode, prompt.clone());
|
||||
let passphrase = self.secret_fn(id, &p.id, SecretKind::Passphrase, sc.key_secret_mode, prompt);
|
||||
let c = SshClient::new(&p, self.terminal_callbacks(id, epoch));
|
||||
c.set_authorities(self.cert_authorities());
|
||||
let stored = |k: SecretKind| self.secrets.get(&k.key(&p.id)).unwrap_or_default();
|
||||
c.set_stored_secrets(stored(SecretKind::Totp), stored(SecretKind::ProxyPassword));
|
||||
c.connect(self.host_key_check(id, sc.host_key_policy), Some(password), Some(passphrase))?;
|
||||
for pf in sc.port_forwards.iter().filter(|f| f.enabled) {
|
||||
match c.start_forward(pf.clone()) {
|
||||
Ok(()) => self.emit(Event::ForwardStarted { session: id.into(), forward: pf.clone() }),
|
||||
Err(e) => self.emit(Event::ForwardError { session: id.into(), forward_id: pf.id.clone(), label: pf.label.clone(), error: e.to_string() }),
|
||||
}
|
||||
}
|
||||
self.start_login_scripts(id, epoch, sc.login_scripts.clone());
|
||||
Ok(Client::Ssh(c))
|
||||
}
|
||||
|
||||
/// An SSH connection used only to tunnel another protocol (IRC, VNC).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn tunnel(
|
||||
self: &Arc<Self>,
|
||||
id: &str,
|
||||
profile_id: &str,
|
||||
host: &str,
|
||||
port: i64,
|
||||
user: &str,
|
||||
method: &str,
|
||||
key: &str,
|
||||
agent: bool,
|
||||
mode: SecretMode,
|
||||
kind: &str,
|
||||
prompt: Prompt,
|
||||
) -> Result<Arc<SshClient>> {
|
||||
let mut tp = Profile::new(Protocol::Ssh);
|
||||
tp.host = host.into();
|
||||
tp.port = if port == 0 { 22 } else { port };
|
||||
tp.username = user.into();
|
||||
let c = tp.ssh.as_mut().unwrap();
|
||||
c.auth_methods = vec![if method.is_empty() { "publickey".into() } else { method.into() }];
|
||||
c.private_key_path = key.into();
|
||||
c.agent_auth = agent;
|
||||
let (pw_kind, pp_kind) = match kind {
|
||||
"vnc" => (SecretKind::VncSshPassword, SecretKind::VncSshPassphrase),
|
||||
"rdp" => (SecretKind::RdpSshPassword, SecretKind::RdpSshPassphrase),
|
||||
_ => (SecretKind::IrcSshPassword, SecretKind::IrcSshPassphrase),
|
||||
};
|
||||
let password = (method == "password").then(|| self.secret_fn(id, profile_id, pw_kind, mode, prompt.clone()));
|
||||
let passphrase = self.secret_fn(id, profile_id, pp_kind, mode, prompt);
|
||||
let t = SshClient::new(&tp, Callbacks::noop());
|
||||
t.set_authorities(self.cert_authorities());
|
||||
t.connect_tunnel_only(self.host_key_check(id, HostKeyPolicy::Ask), password, Some(passphrase))?;
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
pub(super) fn connect_github(self: &Arc<Self>, id: &str, epoch: u64, p: &Profile, prompt: Prompt) -> Result<Client> {
|
||||
let gh = p.github.clone().ok_or_else(|| format!("GitHub configuration missing on profile {:?}", p.id))?;
|
||||
let token = self.secret_fn(id, &p.id, SecretKind::GithubToken, gh.secret_mode, prompt.clone())().map_err(|e| format!("obtaining GitHub token: {e}"))?;
|
||||
if token.is_empty() {
|
||||
return err("GitHub token cannot be empty".into());
|
||||
}
|
||||
let mut client = github::Client::new(&gh.base_url, &token);
|
||||
let login = match client.validate_token() {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
let msg = e.to_string().to_lowercase();
|
||||
let auth = ["token validation failed", "authentication failed", "http 401", "http 403"].iter().any(|k| msg.contains(k));
|
||||
let retry = auth.then(|| prompt("GitHub token did not work. Please enter a valid token:").ok()).flatten().filter(|t| !t.is_empty());
|
||||
let Some(t) = retry else { return err(format!("GitHub authentication failed: {e}")) };
|
||||
if gh.secret_mode == SecretMode::Saved {
|
||||
let _ = self.with(id, |s| s.session_secrets.lock().pending.insert(SecretKind::GithubToken.key(&p.id), Zeroizing::new(t.clone())));
|
||||
}
|
||||
client = github::Client::new(&gh.base_url, &t);
|
||||
client.validate_token().map_err(|e| format!("GitHub authentication failed: {e}"))?
|
||||
}
|
||||
};
|
||||
let client = Arc::new(client);
|
||||
if !self.is_current(id, epoch) {
|
||||
return err(format!("session {id:?} was closed while connecting"));
|
||||
}
|
||||
let fetch = {
|
||||
let (me, sid, client) = (self.clone(), id.to_string(), client.clone());
|
||||
move |status: &str| {
|
||||
me.emit(Event::GithubStatus { session: sid.clone(), status: status.into() });
|
||||
let (me2, sid2) = (me.clone(), sid.clone());
|
||||
client.fetch_repos_with_progress(move |done, total| {
|
||||
if total > 0 {
|
||||
me2.emit(Event::GithubStatus { session: sid2.clone(), status: format!("Loading commit info ({done}/{total})") });
|
||||
}
|
||||
})
|
||||
}
|
||||
};
|
||||
let repos = fetch("Loading repositories...").map_err(|e| format!("fetching repositories: {e}"))?;
|
||||
self.emit(Event::GithubRepos { session: id.into(), login: login.clone(), repos });
|
||||
let interval = Duration::from_secs(if gh.refresh_interval_secs < 60 { 300 } else { gh.refresh_interval_secs as u64 });
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let (me, sid, stop2) = (self.clone(), id.to_string(), stop.clone());
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let deadline = std::time::Instant::now() + interval;
|
||||
while std::time::Instant::now() < deadline {
|
||||
if stop2.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
match fetch("Refreshing repositories...") {
|
||||
Ok(repos) => me.emit(Event::GithubRepos { session: sid.clone(), login: login.clone(), repos }),
|
||||
Err(e) => me.emit(Event::GithubError { session: sid.clone(), error: e.to_string() }),
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Client::Github(client, stop))
|
||||
}
|
||||
|
||||
pub(super) fn connect_irc(self: &Arc<Self>, id: &str, epoch: u64, p: &Profile, prompt: Prompt) -> Result<Client> {
|
||||
let ic = p.irc.clone().ok_or("IRC configuration missing")?;
|
||||
let server_pass = if ic.server_password_required {
|
||||
self.secret_fn(id, &p.id, SecretKind::IrcServerPassword, ic.server_password_mode, prompt.clone())()
|
||||
.map_err(|e| format!("IRC server password: {e}"))?
|
||||
.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let ns_pass = if ic.nick_serv_identify {
|
||||
self.secret_fn(id, &p.id, SecretKind::IrcNickServPassword, ic.nick_serv_mode, prompt.clone())()
|
||||
.map_err(|e| format!("NickServ password: {e}"))?
|
||||
.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let (sasl_account, sasl_password) = if ic.sasl {
|
||||
let account = if ic.sasl_account.trim().is_empty() { ic.nick.clone() } else { ic.sasl_account.trim().to_string() };
|
||||
let pw = self.secret_fn(id, &p.id, SecretKind::IrcSaslPassword, ic.sasl_mode, prompt.clone())().map_err(|e| format!("SASL password: {e}"))?;
|
||||
(account, pw.to_string())
|
||||
} else {
|
||||
(String::new(), String::new())
|
||||
};
|
||||
let mut rooms = ic.auto_join_rooms.clone();
|
||||
if !p.id.is_empty() {
|
||||
let last = self.store.irc_last_rooms(&p.id).map_err(|e| format!("loading remembered IRC rooms: {e}"))?;
|
||||
rooms = crate::storage::dedup_rooms(&[&rooms, &last]);
|
||||
}
|
||||
let tunnel = if ic.ssh_tunnel {
|
||||
Some(self.tunnel(
|
||||
id,
|
||||
&p.id,
|
||||
&ic.ssh_host,
|
||||
ic.ssh_port,
|
||||
&ic.ssh_username,
|
||||
&ic.ssh_auth_method,
|
||||
&ic.ssh_private_key,
|
||||
ic.ssh_agent_auth,
|
||||
ic.ssh_secret_mode,
|
||||
"irc",
|
||||
prompt,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let cb = self.terminal_callbacks(id, epoch);
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let on_event: irc::EventFn = Arc::new(move |e| me.emit(Event::Irc { session: sid.clone(), event: e }));
|
||||
let (me, sid, pid) = (self.clone(), id.to_string(), p.id.clone());
|
||||
let on_rooms: irc::RoomsChangedFn = Arc::new(move |rooms: Vec<String>| {
|
||||
if pid.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = me.store.save_irc_last_rooms(&pid, &rooms) {
|
||||
me.emit(Event::Irc {
|
||||
session: sid.clone(),
|
||||
event: irc::Event {
|
||||
kind: "system".into(),
|
||||
target: irc::SERVER_TARGET.into(),
|
||||
text: format!("Could not remember open IRC rooms: {e}"),
|
||||
timestamp: chrono::Utc::now().timestamp_millis(),
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
let connector: Option<irc::Connector> = tunnel.clone().map(|t| {
|
||||
let (host, port) = (p.host.clone(), p.port as u16);
|
||||
Arc::new(move || {
|
||||
let s = t.open_tunnel(&host, port)?;
|
||||
s.set_read_timeout(Some(Duration::from_millis(50)))?;
|
||||
Ok(Box::new(s) as Box<dyn irc::ReadWrite>)
|
||||
}) as irc::Connector
|
||||
});
|
||||
let cfg = irc::Config {
|
||||
server: p.host.clone(),
|
||||
port: p.port as u16,
|
||||
nick: ic.nick.clone(),
|
||||
user: if p.username.is_empty() { ic.nick.clone() } else { p.username.clone() },
|
||||
real_name: ic.real_name.clone(),
|
||||
use_tls: ic.use_tls,
|
||||
server_pass,
|
||||
auto_join_rooms: rooms,
|
||||
nickserv_identify: ic.nick_serv_identify,
|
||||
nickserv_account: ic.nick_serv_account.clone(),
|
||||
nickserv_password: ns_pass,
|
||||
sasl_account,
|
||||
sasl_password,
|
||||
connector,
|
||||
connect_timeout: Duration::from_secs(p.connect_timeout.max(1) as u64),
|
||||
on_event,
|
||||
on_error: cb.on_error,
|
||||
on_close: cb.on_close,
|
||||
on_rooms_changed: on_rooms,
|
||||
};
|
||||
let c = irc::Client::new(cfg);
|
||||
if let Err(e) = c.connect() {
|
||||
if let Some(t) = tunnel {
|
||||
t.close();
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Client::Irc(c, tunnel))
|
||||
}
|
||||
|
||||
pub(super) fn connect_vnc(self: &Arc<Self>, id: &str, epoch: u64, p: &Profile, prompt: Prompt) -> Result<Client> {
|
||||
let vc = p.vnc.clone().ok_or("VNC configuration missing")?;
|
||||
let host = if vc.vnc_host.is_empty() { p.host.clone() } else { vc.vnc_host.clone() };
|
||||
let port = if vc.vnc_port == 0 { 5900 } else { vc.vnc_port } as u16;
|
||||
let tunnel = if vc.ssh_tunnel {
|
||||
Some(self.tunnel(
|
||||
id,
|
||||
&p.id,
|
||||
&vc.ssh_host,
|
||||
vc.ssh_port,
|
||||
&vc.ssh_username,
|
||||
&vc.ssh_auth_method,
|
||||
&vc.ssh_private_key,
|
||||
vc.ssh_agent_auth,
|
||||
vc.ssh_secret_mode,
|
||||
"vnc",
|
||||
prompt.clone(),
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let password = self.secret_fn(id, &p.id, SecretKind::VncPassword, vc.secret_mode, prompt);
|
||||
let cb = self.terminal_callbacks(id, epoch);
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let (me2, sid2) = (self.clone(), id.to_string());
|
||||
let clip: clients::vnc::ClipboardFn = Arc::new(move |text| me2.emit(Event::DesktopClipboard { session: sid2.clone(), text }));
|
||||
let c = connect_vnc_client(
|
||||
&host,
|
||||
port,
|
||||
&vc,
|
||||
p.connect_timeout,
|
||||
password,
|
||||
tunnel.clone(),
|
||||
cb,
|
||||
Arc::new(move || me.emit(Event::DesktopFrame { session: sid.clone() })),
|
||||
clip,
|
||||
);
|
||||
match c {
|
||||
Ok(c) => {
|
||||
self.emit(Event::DesktopReady { session: id.into() });
|
||||
Ok(Client::Vnc(c, tunnel))
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(t) = tunnel {
|
||||
t.close();
|
||||
}
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn connect_rdp(self: &Arc<Self>, id: &str, epoch: u64, p: &Profile, prompt: Prompt) -> Result<Client> {
|
||||
let rc = p.rdp.clone().unwrap_or_else(RdpConfig::defaults);
|
||||
let port = if p.port == 0 { DEFAULT_RDP_PORT } else { p.port as u16 };
|
||||
let tunnel = if rc.ssh_tunnel {
|
||||
Some(self.tunnel(
|
||||
id,
|
||||
&p.id,
|
||||
&rc.ssh_host,
|
||||
rc.ssh_port,
|
||||
&rc.ssh_username,
|
||||
&rc.ssh_auth_method,
|
||||
&rc.ssh_private_key,
|
||||
rc.ssh_agent_auth,
|
||||
rc.ssh_secret_mode,
|
||||
"rdp",
|
||||
prompt.clone(),
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let r = self.rdp_client(id, epoch, p, &rc, port, tunnel.clone(), prompt);
|
||||
match r {
|
||||
Ok(c) => {
|
||||
self.emit(Event::DesktopReady { session: id.into() });
|
||||
Ok(Client::Rdp(c, tunnel))
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(t) = tunnel {
|
||||
t.close();
|
||||
}
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn rdp_client(
|
||||
self: &Arc<Self>,
|
||||
id: &str,
|
||||
epoch: u64,
|
||||
p: &Profile,
|
||||
rc: &RdpConfig,
|
||||
port: u16,
|
||||
tunnel: Option<Arc<SshClient>>,
|
||||
prompt: Prompt,
|
||||
) -> Result<Arc<clients::rdp::Client>> {
|
||||
let timeout = Duration::from_secs(p.connect_timeout.max(1) as u64);
|
||||
let host = p.host.clone();
|
||||
let gateway = (!rc.gateway_host.trim().is_empty()).then(|| rc.gateway_host.trim().to_string());
|
||||
let dial: clients::rdp::Dial = match (tunnel, gateway) {
|
||||
(_, Some(gw)) => {
|
||||
let pw = self.secret_fn(id, &p.id, SecretKind::RdpGatewayPassword, rc.gateway_secret_mode, prompt.clone())()?;
|
||||
clients::rdp::gateway_dial(gw, rc.gateway_username.clone(), pw, host.clone(), port)
|
||||
}
|
||||
(Some(t), None) => {
|
||||
let h = host.clone();
|
||||
Arc::new(move || t.open_tunnel(&h, port))
|
||||
}
|
||||
(None, None) => {
|
||||
let proxy = clients::proxy::Proxy {
|
||||
kind: rc.proxy_type.clone(),
|
||||
host: rc.proxy_host.clone(),
|
||||
port: rc.proxy_port as u16,
|
||||
username: rc.proxy_username.clone(),
|
||||
password: self.secrets.get(&SecretKind::ProxyPassword.key(&p.id)).unwrap_or_default(),
|
||||
};
|
||||
let h = host.clone();
|
||||
Arc::new(move || proxy.connect(&h, port, timeout))
|
||||
}
|
||||
};
|
||||
let check = self.host_key_check(id, rc.host_key_policy);
|
||||
let h = host.clone();
|
||||
let check_cert: clients::rdp::CertCheck = Arc::new(move |fp: &str| {
|
||||
check(&HostKeyInfo { host: h.clone(), port, key_type: "rdp-tls".into(), fingerprint: fp.into(), public_key_b64: String::new() })
|
||||
});
|
||||
// A 0×0 configured size follows the tab, which reports its pixel size like a terminal.
|
||||
let (width, height) = match (rc.width, rc.height) {
|
||||
(w, h) if w > 0 && h > 0 => (w as u16, h as u16),
|
||||
_ => self.with(id, |s| s.pending_resize).ok().flatten().unwrap_or((1280, 800)),
|
||||
};
|
||||
let password = self.secret_fn(id, &p.id, SecretKind::RdpPassword, rc.secret_mode, prompt)()?;
|
||||
let cb = self.terminal_callbacks(id, epoch);
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let (me2, sid2) = (self.clone(), id.to_string());
|
||||
let c = clients::rdp::Client::new(clients::rdp::Config {
|
||||
host,
|
||||
username: p.username.clone(),
|
||||
domain: rc.domain.clone(),
|
||||
password,
|
||||
width,
|
||||
height,
|
||||
allow_tls_only: rc.allow_tls_only,
|
||||
audio: rc.audio,
|
||||
kerberos_kdc: (!rc.kerberos_kdc.trim().is_empty()).then(|| rc.kerberos_kdc.trim().to_string()),
|
||||
shared_folder: (!rc.shared_folder.trim().is_empty()).then(|| (rc.shared_folder.trim().into(), "Nexus".into())),
|
||||
printer: rc.redirect_printer.then(|| {
|
||||
let (me, sid) = (self.clone(), id.to_string());
|
||||
let on_printed: clients::rdp_devices::PrintedFn =
|
||||
Arc::new(move |f: PathBuf| me.emit(Event::Info { session: sid.clone(), message: format!("Print job saved to {}", f.display()) }));
|
||||
(downloads_dir(), on_printed)
|
||||
}),
|
||||
dial,
|
||||
check_cert,
|
||||
connect_timeout: timeout,
|
||||
on_frame: Arc::new(move || me.emit(Event::DesktopFrame { session: sid.clone() })),
|
||||
on_clipboard: Arc::new(move |text| me2.emit(Event::DesktopClipboard { session: sid2.clone(), text })),
|
||||
on_error: cb.on_error,
|
||||
on_close: cb.on_close,
|
||||
});
|
||||
c.connect()?;
|
||||
Ok(c)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds and connects a VNC client from a profile's settings, optionally through an SSH tunnel.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn connect_vnc_client(
|
||||
host: &str,
|
||||
port: u16,
|
||||
vc: &VncConfig,
|
||||
timeout: i64,
|
||||
password: SecretFn,
|
||||
tunnel: Option<Arc<SshClient>>,
|
||||
cb: Callbacks,
|
||||
on_frame: Arc<dyn Fn() + Send + Sync>,
|
||||
on_clipboard: clients::vnc::ClipboardFn,
|
||||
) -> Result<Arc<clients::vnc::Client>> {
|
||||
let connector: Option<irc::Connector> = tunnel.map(|t| {
|
||||
let host = host.to_string();
|
||||
Arc::new(move || {
|
||||
let s = t.open_tunnel(&host, port)?;
|
||||
s.set_read_timeout(Some(Duration::from_millis(50)))?;
|
||||
Ok(Box::new(s) as Box<dyn irc::ReadWrite>)
|
||||
}) as irc::Connector
|
||||
});
|
||||
let mut cfg = clients::vnc::Config {
|
||||
host: host.into(),
|
||||
port,
|
||||
password: None,
|
||||
shared: vc.shared_session,
|
||||
view_only: vc.view_only,
|
||||
quality: vc.quality.clamp(0, 9) as u8,
|
||||
connector,
|
||||
connect_timeout: Duration::from_secs(timeout.max(1) as u64),
|
||||
on_frame,
|
||||
on_clipboard,
|
||||
on_error: cb.on_error,
|
||||
on_close: cb.on_close,
|
||||
..Default::default()
|
||||
};
|
||||
let c = clients::vnc::Client::new(cfg.clone());
|
||||
match c.connect() {
|
||||
Ok(()) => Ok(c),
|
||||
// Ask for the password only when the server wants one.
|
||||
Err(e) if e.to_string().to_lowercase().contains("password") => {
|
||||
cfg.password = Some(password()?.to_string());
|
||||
let c = clients::vnc::Client::new(cfg);
|
||||
c.connect()?;
|
||||
Ok(c)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Where print jobs and similar go: ~/Downloads when it exists, else the home folder.
|
||||
fn downloads_dir() -> PathBuf {
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
|
||||
let d = home.join("Downloads");
|
||||
if d.is_dir() { d } else { home }
|
||||
}
|
||||